<commit_before>#![feature(rustc_private)]
extern crate termion;
extern crate serde_json;
#[macro_use]
extern crate log;
extern crate log4rs;

mod core;

use termion::{color, style, clear, cursor};
use termion::raw::IntoRawMode;
use termion::input::TermRead;
use termion::event::Key;
use std::io::{stdin, stdout, Write, Read};
use std::io;
use core::Core;
use std::{thread, time};
use std::sync::mpsc;

struct Screen<W: Write> {
    stdout: W,
    x: u16,
    y: u16,
    exit: bool,
}

fn init<W: Write>(mut stdout: W, x: u16, y: u16) -> Screen<W> {
    write!(stdout, "{}", clear::All).unwrap();
    stdout.flush();
    Screen {
        x: x,
        y: y,
        stdout: stdout,
        exit: false,
    }
}

impl<W: Write> Screen<W> {
    fn handle_update(&mut self, lines: Vec<String>, x: u16, y: u16) {
        write!(self.stdout, "{}", termion::clear::All);
        write!(self.stdout, "{}", cursor::Up(self.y));
        for (i, line) in lines.into_iter().enumerate() {
            self.stdout.write_all(line.as_bytes());
            write!(self.stdout, "{}", cursor::Left(self.x));
        }
        self.stdout.flush();
    }
}

pub struct Input {
    tx: mpsc::Sender<Option<termion::event::Key>>,
    rx: mpsc::Receiver<Option<termion::event::Key>>
}

impl Input {
    pub fn new() -> Input {
        let (tx, rx) = mpsc::channel();
        Input {
            tx: tx,
            rx: rx,
        }
    }

    pub fn run(&mut self) {
        let tx = self.tx.clone();
        thread::spawn(move || {
            for k in stdin().keys() {
                tx.send(Some(k.unwrap()));
            }
        });
    }

    pub fn into_iter(&mut self) -> InputIntoIterator {
        InputIntoIterator {
            input: self
        }
    }
}

pub struct InputIntoIterator<'a> {
    input: &'a mut Input,
}

impl <'a>Iterator for InputIntoIterator<'a> {

    type Item = Option<termion::event::Key>;

    fn next(&mut self) -> Option<Option<termion::event::Key>> {
        let data = self.input.rx.try_recv();
        if data.is_ok() {
            return Some(data.unwrap());
        }
        else {
            return Some(None);
        }
    }
}

fn main() {
    log4rs::init_file("log_config.yaml", Default::default()).unwrap();
    let mut core = Core::new("../xi-editor/rust/target/debug/xi-core");
    let mut stdout = stdout().into_raw_mode().unwrap();
    let size = termion::terminal_size().unwrap();
    let mut screen = init(stdout, size.0, size.1);

    let mut input = Input::new();
    input.run();
    let mut keys = input.into_iter();
    loop {
        if let Some(key) = keys.next().unwrap() {
            match key {
                termion::event::Key::Char(c) => {
                    &mut core.char(c);
                }
                _ => {}
            }
        }
        if let Ok(update_msg) = core.update_rx.try_recv() {
            let update = update_msg.as_object().unwrap().get("update").unwrap().as_object().unwrap();
            // first_line = dict.get("first_line").unwrap().as_u64().unwrap();
            // height = dict.get("height").unwrap().as_u64().unwrap();
            let lines = update.get("lines").unwrap().as_array().unwrap().into_iter().map(
                |line| line.as_array().unwrap()[0].as_str().unwrap().to_string()).collect();
            let scrollto = update.get("scrollto").unwrap().as_array().unwrap();
            screen.handle_update(lines, scrollto[0].as_u64().unwrap() as u16, scrollto[1].as_u64().unwrap() as u16);
        }
    }
}
<commit_msg>sleep to avoid 100% cpu usage<commit_after>#![feature(rustc_private)]
extern crate termion;
extern crate serde_json;
#[macro_use]
extern crate log;
extern crate log4rs;

mod core;

use termion::{color, style, clear, cursor};
use termion::raw::IntoRawMode;
use termion::input::TermRead;
use termion::event::Key;
use std::io::{stdin, stdout, Write, Read};
use std::io;
use core::Core;
use std::{thread, time};
use std::sync::mpsc;

struct Screen<W: Write> {
    stdout: W,
    x: u16,
    y: u16,
    exit: bool,
}

fn init<W: Write>(mut stdout: W, x: u16, y: u16) -> Screen<W> {
    write!(stdout, "{}", clear::All).unwrap();
    stdout.flush();
    Screen {
        x: x,
        y: y,
        stdout: stdout,
        exit: false,
    }
}

impl<W: Write> Screen<W> {
    fn handle_update(&mut self, lines: Vec<String>, x: u16, y: u16) {
        write!(self.stdout, "{}", termion::clear::All);
        write!(self.stdout, "{}", cursor::Up(self.y));
        for (i, line) in lines.into_iter().enumerate() {
            self.stdout.write_all(line.as_bytes());
            write!(self.stdout, "{}", cursor::Left(self.x));
        }
        self.stdout.flush();
    }
}

pub struct Input {
    tx: mpsc::Sender<Option<termion::event::Key>>,
    rx: mpsc::Receiver<Option<termion::event::Key>>
}

impl Input {
    pub fn new() -> Input {
        let (tx, rx) = mpsc::channel();
        Input {
            tx: tx,
            rx: rx,
        }
    }

    pub fn run(&mut self) {
        let tx = self.tx.clone();
        thread::spawn(move || {
            for k in stdin().keys() {
                tx.send(Some(k.unwrap()));
            }
        });
    }

    pub fn into_iter(&mut self) -> InputIntoIterator {
        InputIntoIterator {
            input: self
        }
    }
}

pub struct InputIntoIterator<'a> {
    input: &'a mut Input,
}

impl <'a>Iterator for InputIntoIterator<'a> {

    type Item = Option<termion::event::Key>;

    fn next(&mut self) -> Option<Option<termion::event::Key>> {
        let data = self.input.rx.try_recv();
        if data.is_ok() {
            return Some(data.unwrap());
        }
        else {
            return Some(None);
        }
    }
}

fn main() {
    log4rs::init_file("log_config.yaml", Default::default()).unwrap();
    let mut core = Core::new("../xi-editor/rust/target/debug/xi-core");
    let mut stdout = stdout().into_raw_mode().unwrap();
    let size = termion::terminal_size().unwrap();
    let mut screen = init(stdout, size.0, size.1);

    let mut input = Input::new();
    input.run();
    let mut keys = input.into_iter();
    loop {
        if let Some(key) = keys.next().unwrap() {
            match key {
                termion::event::Key::Char(c) => {
                    &mut core.char(c);
                }
                _ => {}
            }
        }
        if let Ok(update_msg) = core.update_rx.try_recv() {
            let update = update_msg.as_object().unwrap().get("update").unwrap().as_object().unwrap();
            // first_line = dict.get("first_line").unwrap().as_u64().unwrap();
            // height = dict.get("height").unwrap().as_u64().unwrap();
            let lines = update.get("lines").unwrap().as_array().unwrap().into_iter().map(
                |line| line.as_array().unwrap()[0].as_str().unwrap().to_string()).collect();
            let scrollto = update.get("scrollto").unwrap().as_array().unwrap();
            screen.handle_update(lines, scrollto[0].as_u64().unwrap() as u16, scrollto[1].as_u64().unwrap() as u16);
        }
        thread::sleep_ms(10);
    }
}
<|endoftext|>


<commit_before>extern crate piston_window;
extern crate graphics;
extern crate itertools;
extern crate opengl_graphics;
extern crate piston;
extern crate rand;

mod drawing;
mod game;
mod models;
mod traits;

use piston_window::*;
use opengl_graphics::GlGraphics;

use game::Game;

// Returns a result containing a GlutinWindow or an error if the window
// settings are not supported
fn main() {

    let opengl = OpenGL::V3_2;

    let mut game = Game::new(drawing::Size::new(1024.0, 600.0));

    let mut window: PistonWindow = WindowSettings::new("Rocket!", [1024, 600])
        .opengl(opengl).exit_on_esc(true).build().unwrap();

    window.set_ups(60);
    window.set_max_fps(60);

    let mut gl = GlGraphics::new(opengl);

    let mut events = window.events();

    while let Some(e) = events.next(&mut window) {
    // Event handling
        match e {
            Event::Input(Input::Press(Button::Keyboard(key))) => {
                game.key_press(key);
            }

            Event::Input(Input::Release(Button::Keyboard(key))) => {
                game.key_release(key);
            }

            Event::Render(args) => {
                gl.draw(args.viewport(), |c, g| game.render(c, g));
            }

            Event::Update(args) => {
                game.update(args.dt);
            }

            _ => {}
        }
    }

}
<commit_msg>Adjust the sample rate back to 8<commit_after>extern crate piston_window;
extern crate graphics;
extern crate itertools;
extern crate opengl_graphics;
extern crate piston;
extern crate rand;

mod drawing;
mod game;
mod models;
mod traits;

use piston_window::*;
use opengl_graphics::GlGraphics;

use game::Game;

// Returns a result containing a GlutinWindow or an error if the window
// settings are not supported
fn main() {

    let opengl = OpenGL::V3_2;

    let mut game = Game::new(drawing::Size::new(1024.0, 600.0));

    let mut window: PistonWindow = WindowSettings::new("Rocket!", [1024, 600])
        .opengl(opengl).samples(8).exit_on_esc(true).build().unwrap();

    window.set_ups(60);
    window.set_max_fps(60);

    let mut gl = GlGraphics::new(opengl);

    let mut events = window.events();

    while let Some(e) = events.next(&mut window) {
    // Event handling
        match e {
            Event::Input(Input::Press(Button::Keyboard(key))) => {
                game.key_press(key);
            }

            Event::Input(Input::Release(Button::Keyboard(key))) => {
                game.key_release(key);
            }

            Event::Render(args) => {
                gl.draw(args.viewport(), |c, g| game.render(c, g));
            }

            Event::Update(args) => {
                game.update(args.dt);
            }

            _ => {}
        }
    }

}
<|endoftext|>


<commit_before>#![feature(exit_status)]

extern crate identicon;
extern crate openssl;
extern crate image;

use std::env;
use std::io;
use std::io::{Read, Write, Result};

use image::ColorType;
use image::png::PNGEncoder;
use openssl::crypto::hash::{Hasher, Type};

use identicon::Identicon;

fn main() {
    match hash() {
        Ok(bytes) => {
            match generate(&bytes[..]) {
                Ok(_) => (),
                Err(e) => {
                    println!("{}", e);
                    env::set_exit_status(2);
                },
            }
        },
        Err(e) => {
            println!("{}", e);
            env::set_exit_status(1)
        },
    }
}

fn generate(input: &[u8]) -> Result<()> {
    let identicon = Identicon::new(input);
    let image = identicon.image();
    let (width, height) = image.dimensions();
    let output = &mut io::stdout();
    let mut encoder = PNGEncoder::new(output);
    encoder.encode(image.as_ref(), width, height, ColorType::RGB(8))
}

fn hash() -> Result<Vec<u8>> {
    let mut hash = Hasher::new(Type::MD5);
    let input = io::stdin();
    let mut reader = input.lock();
    match pipe(&mut reader, &mut hash) {
        Ok(..) => Ok(hash.finish()),
        Err(e) => Err(e),
    }
}

fn pipe(input: &mut Read, output: &mut Write) -> Result<usize> {
    let mut total = 0;
    let mut buf = [0; 1024];
    loop {
        match try!(input.read(&mut buf)) {
            0 => break,
            n => {
                try!(output.write(&buf[0..n]));
                total += n;
            },
        }
    }
    Ok(total)
}
<commit_msg>Allow main to panic on IO errors.<commit_after>extern crate identicon;
extern crate openssl;
extern crate image;

use std::io;
use std::io::{Read, Write, Result};

use image::ColorType;
use image::png::PNGEncoder;
use openssl::crypto::hash::{Hasher, Type};

use identicon::Identicon;

fn main() {
    let bytes = hash().unwrap();
    generate(&bytes[..]).unwrap();
}

fn generate(input: &[u8]) -> Result<()> {
    let identicon = Identicon::new(input);
    let image = identicon.image();
    let (width, height) = image.dimensions();
    let output = &mut io::stdout();
    let mut encoder = PNGEncoder::new(output);
    encoder.encode(image.as_ref(), width, height, ColorType::RGB(8))
}

fn hash() -> Result<Vec<u8>> {
    let mut hash = Hasher::new(Type::MD5);
    let input = io::stdin();
    let mut reader = input.lock();
    match pipe(&mut reader, &mut hash) {
        Ok(..) => Ok(hash.finish()),
        Err(e) => Err(e),
    }
}

fn pipe(input: &mut Read, output: &mut Write) -> Result<usize> {
    let mut total = 0;
    let mut buf = [0; 1024];
    loop {
        match try!(input.read(&mut buf)) {
            0 => break,
            n => {
                try!(output.write(&buf[0..n]));
                total += n;
            },
        }
    }
    Ok(total)
}
<|endoftext|>


<commit_before>extern crate futures;
extern crate tokio_core;
extern crate tokio_io;

extern crate tokio_process;

extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;

extern crate regex;

#[macro_use]
extern crate error_chain;

extern crate telegram_bot_client;
use telegram_bot_client::{BotFactory, Update};
use telegram_bot_client::errors::Error as TGError;

extern crate telegram_bot_types;
use telegram_bot_types as types;

use tokio_core::reactor;
use tokio_io::io;
use futures::{Future, Stream};
use futures::future;

use std::process::{Command, Stdio};
use tokio_process::CommandExt;

extern crate structopt;
#[macro_use]
extern crate structopt_derive;

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "overbot", about = "A telegram bot manager")]
struct Opt {
    #[structopt(help = "Config files directory")]
    config_dir: String,
}

mod config;
mod errors;

fn main() {
    let opt = Opt::from_args();
    let config = config::get_all(&opt.config_dir).expect("Wrong path for config dir");

    let mut event_loop = reactor::Core::new().unwrap();
    let handle = event_loop.handle();

    let factory = BotFactory::new(handle.clone());
    let work =
        future::join_all(config.into_iter().map(|config_bot| {
            let handle = handle.clone();
            let (bot, updates) = factory.new_bot(&config_bot.token);
            updates
                .filter_map(move |update| {
                    println!("{:?}", update);
                    match update {
                        Update::Message(msg) => {
                            let original = msg.clone();
                            let msg: types::response::Message =
                                serde_json::from_value(msg).expect("Unexpected message format");
                            if let Some(text) = msg.text.clone() {
                                for c in &config_bot.commands {
                                    if c.allowed(msg.from.id) && c.allowed(msg.chat.id) &&
                                        c.regex.is_match(&text)
                                    {
                                        return Some((c.clone(), msg, original));
                                    }
                                }
                            }
                        }
                        _ => {}
                    };
                    None
                })
                .for_each(move |(cmd, msg, original)| {
                    let handle = handle.clone();
                    let bot = bot.clone();
                    let text = msg.text.clone().unwrap();
                    let args : Vec<String> = {
                        let captures = cmd.regex.captures(&text).expect(
                            "we already checked for match",
                        );
                        cmd.args.iter().map(|a| {
                            let mut buf = String::new();
                            captures.expand(a, &mut buf);
                            buf
                        }).collect()
                    };
                    let mut child = Command::new(&cmd.executable)
                        .args(&args)
                        .stdin(Stdio::piped())
                        .stdout(Stdio::piped())
                        .spawn_async(&handle)
                        .expect("failed to spawn process");
                    let stdin = child.stdin().take().unwrap();
                    let res = match cmd.input {
                        config::InputType::Text => {
                            io::write_all(stdin, text.into_bytes())
                        }
                        config::InputType::Json => {
                            io::write_all(stdin, serde_json::to_vec(&original).unwrap())
                        }
                    };
                    let res = res.map_err(|e| e.into());
                    res.and_then(|_| {
                        child
                            .wait_with_output()
                            .map_err(|e| TGError::from(e))
                            .and_then(move |out| {
                                let mut out = String::from_utf8(out.stdout).unwrap();
                                println!("out: {:?}", out);
                                if cmd.output == config::OutputType::TextMono {
                                    out = format!("```{}```", out);
                                }
                                let work;
                                if cmd.output == config::OutputType::Json {
                                    let json: serde_json::Value = serde_json::from_str(&out)?;
                                    work =
                                        bot.request::<_, serde_json::Value>("sendMessage", &json);
                                } else {
                                    let parse_mode = match cmd.output {
                                        config::OutputType::Text => types::request::ParseMode::Text,
                                        config::OutputType::TextMono => {
                                            types::request::ParseMode::Markdown
                                        }
                                        config::OutputType::Markdown => {
                                            types::request::ParseMode::Markdown
                                        }
                                        config::OutputType::Html => types::request::ParseMode::Html,
                                        config::OutputType::Json => unreachable!(),
                                    };
                                    work = bot.request::<_, serde_json::Value>(
                                        "sendMessage",
                                        &serde_json::to_value(
                                            types::request::Message::new(msg.chat.id, out)
                                                .parse_mode(parse_mode),
                                        ).unwrap(),
                                    );
                                }
                                let work = work.and_then(|r| {
                                    println!("{:?}", r);
                                    future::ok(())
                                }).map_err(|e| println!("error: {:?}", e));
                                handle.spawn(work);
                                Ok(())
                            })
                    }).or_else(|e| {
                            println!("error: {:?}", e);
                            future::ok(())
                        })
                })
        }));
    event_loop.run(work).expect("exit with error");
}
<commit_msg>cargo fmt<commit_after>extern crate futures;
extern crate tokio_core;
extern crate tokio_io;

extern crate tokio_process;

extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;

extern crate regex;

#[macro_use]
extern crate error_chain;

extern crate telegram_bot_client;
use telegram_bot_client::{BotFactory, Update};
use telegram_bot_client::errors::Error as TGError;

extern crate telegram_bot_types;
use telegram_bot_types as types;

use tokio_core::reactor;
use tokio_io::io;
use futures::{Future, Stream};
use futures::future;

use std::process::{Command, Stdio};
use tokio_process::CommandExt;

extern crate structopt;
#[macro_use]
extern crate structopt_derive;

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "overbot", about = "A telegram bot manager")]
struct Opt {
    #[structopt(help = "Config files directory")]
    config_dir: String,
}

mod config;
mod errors;

fn main() {
    let opt = Opt::from_args();
    let config = config::get_all(&opt.config_dir).expect("Wrong path for config dir");

    let mut event_loop = reactor::Core::new().unwrap();
    let handle = event_loop.handle();

    let factory = BotFactory::new(handle.clone());
    let work = future::join_all(config.into_iter().map(|config_bot| {
        let handle = handle.clone();
        let (bot, updates) = factory.new_bot(&config_bot.token);
        updates
            .filter_map(move |update| {
                println!("{:?}", update);
                match update {
                    Update::Message(msg) => {
                        let original = msg.clone();
                        let msg: types::response::Message =
                            serde_json::from_value(msg).expect("Unexpected message format");
                        if let Some(text) = msg.text.clone() {
                            for c in &config_bot.commands {
                                if c.allowed(msg.from.id) && c.allowed(msg.chat.id) &&
                                    c.regex.is_match(&text)
                                {
                                    return Some((c.clone(), msg, original));
                                }
                            }
                        }
                    }
                    _ => {}
                };
                None
            })
            .for_each(move |(cmd, msg, original)| {
                let handle = handle.clone();
                let bot = bot.clone();
                let text = msg.text.clone().unwrap();
                let args: Vec<String> = {
                    let captures = cmd.regex.captures(&text).expect(
                        "we already checked for match",
                    );
                    cmd.args
                        .iter()
                        .map(|a| {
                            let mut buf = String::new();
                            captures.expand(a, &mut buf);
                            buf
                        })
                        .collect()
                };
                let mut child = Command::new(&cmd.executable)
                    .args(&args)
                    .stdin(Stdio::piped())
                    .stdout(Stdio::piped())
                    .spawn_async(&handle)
                    .expect("failed to spawn process");
                let stdin = child.stdin().take().unwrap();
                let res = match cmd.input {
                    config::InputType::Text => io::write_all(stdin, text.into_bytes()),
                    config::InputType::Json => {
                        io::write_all(stdin, serde_json::to_vec(&original).unwrap())
                    }
                };
                let res = res.map_err(|e| e.into());
                res.and_then(|_| {
                    child
                        .wait_with_output()
                        .map_err(|e| TGError::from(e))
                        .and_then(move |out| {
                            let mut out = String::from_utf8(out.stdout).unwrap();
                            println!("out: {:?}", out);
                            if cmd.output == config::OutputType::TextMono {
                                out = format!("```{}```", out);
                            }
                            let work;
                            if cmd.output == config::OutputType::Json {
                                let json: serde_json::Value = serde_json::from_str(&out)?;
                                work = bot.request::<_, serde_json::Value>("sendMessage", &json);
                            } else {
                                let parse_mode = match cmd.output {
                                    config::OutputType::Text => types::request::ParseMode::Text,
                                    config::OutputType::TextMono => {
                                        types::request::ParseMode::Markdown
                                    }
                                    config::OutputType::Markdown => {
                                        types::request::ParseMode::Markdown
                                    }
                                    config::OutputType::Html => types::request::ParseMode::Html,
                                    config::OutputType::Json => unreachable!(),
                                };
                                work = bot.request::<_, serde_json::Value>(
                                    "sendMessage",
                                    &serde_json::to_value(
                                        types::request::Message::new(msg.chat.id, out)
                                            .parse_mode(parse_mode),
                                    ).unwrap(),
                                );
                            }
                            let work = work.and_then(|r| {
                                println!("{:?}", r);
                                future::ok(())
                            }).map_err(|e| println!("error: {:?}", e));
                            handle.spawn(work);
                            Ok(())
                        })
                }).or_else(|e| {
                        println!("error: {:?}", e);
                        future::ok(())
                    })
            })
    }));
    event_loop.run(work).expect("exit with error");
}
<|endoftext|>


<commit_before>#![feature(lang_items, unboxed_closures)]

use std::io::{File, IoResult, Truncate, Write};
use std::num::Float;
use std::num::FloatMath;
use std::rand;
use std::rand::Rng;

struct SinWave(pub f64);

impl Fn<(f64, ), f64> for SinWave {
    extern "rust-call" fn call(&self, (t, ): (f64, )) -> f64 {
        let SinWave(frequency) = *self;
        FloatMath::sin(t * frequency)
    }
}

struct SquareWave(pub f64);

impl Fn<(f64, ), f64> for SquareWave {
    extern "rust-call" fn call(&self, (t, ): (f64, )) -> f64 {
        let SquareWave(frequency) = *self;
        let sin_wave = SinWave(frequency);
        if sin_wave(t).is_positive() { 1.0 } else { -1.0 }
    }
}

struct SawtoothWave(pub f64);

impl Fn<(f64, ), f64> for SawtoothWave {
    extern "rust-call" fn call(&self, (t, ): (f64, )) -> f64 {
        let SawtoothWave(frequency) = *self;
        let t_factor = t * frequency;
        t_factor - t_factor.floor()
    }
}

fn generate<F>(x: f64, f: F) -> f64 where F: Fn<(f64, ), f64> {
    f(x)
}

fn quantize_16(y: f64) -> i16 {
    // Quantization levels for 16 bits
    let levels = 2.0.powf(16.0) - 1.0;

    // Convert from [-1, 1] to [-2**16 / 2, 2**16 / 2]
    (y * (levels / 2.0)) as i16
}

fn make_sample_16<F>(length: f64, sample_rate: uint, waveform: F) -> Vec<i16> where F: Fn<(f64, ), f64>+Copy {
    let num_samples = (sample_rate as f64 * length).floor() as uint;
    let mut samples: Vec<i16> = Vec::with_capacity(num_samples);

    for i in range(0u, num_samples) {
        let t = i as f64 / sample_rate as f64;
        samples.push(quantize_16(generate(t, waveform)));
    }

    samples
}

fn write_pcm(filename: &str, samples: Vec<i16>) -> IoResult<()> {
    let path = Path::new(filename);
    let mut f = match File::open_mode(&path, Truncate, Write) {
        Ok(f) => f,
        Err(e) => panic!("File error: {}", e)
    };

    for sample in samples.iter() {
        try!(f.write_le_i16(*sample));
    }

    Ok(())
}

// See: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
fn write_wav(filename: &str, sample_rate: uint, samples: Vec<i16>) -> IoResult<()> {
    let path = Path::new(filename);
    let mut f = match File::open_mode(&path, Truncate, Write) {
        Ok(f) => f,
        Err(e) => panic!("File error: {}", e)
    };

    // Some WAV header fields
    let channels = 1;
    let bit_depth = 16;
    let subchunk_2_size = samples.len() * channels * bit_depth / 8;
    let chunk_size = 36 + subchunk_2_size as i32;
    let byte_rate = (sample_rate * channels * bit_depth / 8) as i32;
    let block_align = (channels * bit_depth / 8) as i16;

    try!(f.write_be_i32(0x52494646))              // ChunkID, RIFF
    try!(f.write_le_i32(chunk_size));             // ChunkSize
    try!(f.write_be_i32(0x57415645));             // Format, WAVE

    try!(f.write_be_i32(0x666d7420));             // Subchunk1ID, fmt
    try!(f.write_le_i32(16));                     // Subchunk1Size, 16 for PCM
    try!(f.write_le_i16(1));                      // AudioFormat, PCM = 1 (linear quantization)
    try!(f.write_le_i16(channels as i16));        // NumChannels
    try!(f.write_le_i32(sample_rate as i32));     // SampleRate
    try!(f.write_le_i32(byte_rate));              // ByteRate
    try!(f.write_le_i16(block_align));            // BlockAlign
    try!(f.write_le_i16(bit_depth as i16));       // BitsPerSample

    try!(f.write_be_i32(0x64617461));             // Subchunk2ID, data
    try!(f.write_le_i32(subchunk_2_size as i32)); // Subchunk2Size, number of bytes in the data

    for sample in samples.iter() {
        try!(f.write_le_i16(*sample))
    }

    Ok(())
}

fn main() {
    println!("Hello, synthrs!");

    write_pcm("out/sin.pcm", make_sample_16(1.0, 44100, SinWave(1000.0))).ok();
    write_wav("out/sin.wav", 44100, make_sample_16(1.0, 44100, SinWave(1000.0))).ok();
    write_wav("out/square.wav", 44100, make_sample_16(1.0, 44100, SquareWave(1000.0))).ok();
    write_wav("out/sawtooth.wav", 44100, make_sample_16(1.0, 44100, SawtoothWave(1000.0))).ok();

    write_wav("out/wolftone.wav", 44100, make_sample_16(1.0, 44100, |t: f64| -> f64 {
        SinWave(1000.0)(t) + SinWave(1010.0)(t)
    })).ok();

    write_wav("out/whitenoise.wav", 44100, make_sample_16(1.0, 44100, |_t: f64| -> f64 {
        let mut rng = rand::task_rng();
        (rng.gen::<f64>() - 0.5) * 2.0
    })).ok();

    write_wav("out/rising.wav", 44100, make_sample_16(1.0, 44100, |t: f64| -> f64 {
        let (min_f, max_f) = (1000.0, 8000.0);
        let max_t = 1.0; // Duration of clip in seconds
        let range = max_f - min_f;
        let f = max_f - (max_t - t) * range;
        SinWave(f)(t)
    })).ok();
}
<commit_msg>Fix wolf tone example clipping, add complex example<commit_after>#![feature(lang_items, unboxed_closures)]

use std::io::{File, IoResult, Truncate, Write};
use std::num::Float;
use std::num::FloatMath;
use std::rand;
use std::rand::Rng;

struct SinWave(pub f64);

impl Fn<(f64, ), f64> for SinWave {
    extern "rust-call" fn call(&self, (t, ): (f64, )) -> f64 {
        let SinWave(frequency) = *self;
        FloatMath::sin(t * frequency)
    }
}

struct SquareWave(pub f64);

impl Fn<(f64, ), f64> for SquareWave {
    extern "rust-call" fn call(&self, (t, ): (f64, )) -> f64 {
        let SquareWave(frequency) = *self;
        let sin_wave = SinWave(frequency);
        if sin_wave(t).is_positive() { 1.0 } else { -1.0 }
    }
}

struct SawtoothWave(pub f64);

impl Fn<(f64, ), f64> for SawtoothWave {
    extern "rust-call" fn call(&self, (t, ): (f64, )) -> f64 {
        let SawtoothWave(frequency) = *self;
        let t_factor = t * frequency;
        t_factor - t_factor.floor()
    }
}

fn generate<F>(x: f64, f: F) -> f64 where F: Fn<(f64, ), f64> {
    f(x)
}

fn quantize_16(y: f64) -> i16 {
    // Quantization levels for 16 bits
    let levels = 2.0.powf(16.0) - 1.0;

    // Convert from [-1, 1] to [-2**16 / 2, 2**16 / 2]
    (y * (levels / 2.0)) as i16
}

fn make_sample_16<F>(length: f64, sample_rate: uint, waveform: F) -> Vec<i16> where F: Fn<(f64, ), f64>+Copy {
    let num_samples = (sample_rate as f64 * length).floor() as uint;
    let mut samples: Vec<i16> = Vec::with_capacity(num_samples);

    for i in range(0u, num_samples) {
        let t = i as f64 / sample_rate as f64;
        samples.push(quantize_16(generate(t, waveform)));
    }

    samples
}

fn write_pcm(filename: &str, samples: Vec<i16>) -> IoResult<()> {
    let path = Path::new(filename);
    let mut f = match File::open_mode(&path, Truncate, Write) {
        Ok(f) => f,
        Err(e) => panic!("File error: {}", e)
    };

    for sample in samples.iter() {
        try!(f.write_le_i16(*sample));
    }

    Ok(())
}

// See: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
fn write_wav(filename: &str, sample_rate: uint, samples: Vec<i16>) -> IoResult<()> {
    let path = Path::new(filename);
    let mut f = match File::open_mode(&path, Truncate, Write) {
        Ok(f) => f,
        Err(e) => panic!("File error: {}", e)
    };

    // Some WAV header fields
    let channels = 1;
    let bit_depth = 16;
    let subchunk_2_size = samples.len() * channels * bit_depth / 8;
    let chunk_size = 36 + subchunk_2_size as i32;
    let byte_rate = (sample_rate * channels * bit_depth / 8) as i32;
    let block_align = (channels * bit_depth / 8) as i16;

    try!(f.write_be_i32(0x52494646))              // ChunkID, RIFF
    try!(f.write_le_i32(chunk_size));             // ChunkSize
    try!(f.write_be_i32(0x57415645));             // Format, WAVE

    try!(f.write_be_i32(0x666d7420));             // Subchunk1ID, fmt
    try!(f.write_le_i32(16));                     // Subchunk1Size, 16 for PCM
    try!(f.write_le_i16(1));                      // AudioFormat, PCM = 1 (linear quantization)
    try!(f.write_le_i16(channels as i16));        // NumChannels
    try!(f.write_le_i32(sample_rate as i32));     // SampleRate
    try!(f.write_le_i32(byte_rate));              // ByteRate
    try!(f.write_le_i16(block_align));            // BlockAlign
    try!(f.write_le_i16(bit_depth as i16));       // BitsPerSample

    try!(f.write_be_i32(0x64617461));             // Subchunk2ID, data
    try!(f.write_le_i32(subchunk_2_size as i32)); // Subchunk2Size, number of bytes in the data

    for sample in samples.iter() {
        try!(f.write_le_i16(*sample))
    }

    Ok(())
}

fn main() {
    println!("Hello, synthrs!");

    write_pcm("out/sin.pcm", make_sample_16(1.0, 44100, SinWave(1000.0))).ok();
    write_wav("out/sin.wav", 44100, make_sample_16(1.0, 44100, SinWave(1000.0))).ok();
    write_wav("out/square.wav", 44100, make_sample_16(1.0, 44100, SquareWave(1000.0))).ok();
    write_wav("out/sawtooth.wav", 44100, make_sample_16(1.0, 44100, SawtoothWave(1000.0))).ok();

    write_wav("out/wolftone.wav", 44100, make_sample_16(1.0, 44100, |t: f64| -> f64 {
        (SquareWave(1000.0)(t) + SquareWave(1020.0)(t)) / 2.0
    })).ok();

    write_wav("out/whitenoise.wav", 44100, make_sample_16(1.0, 44100, |_t: f64| -> f64 {
        let mut rng = rand::task_rng();
        (rng.gen::<f64>() - 0.5) * 2.0
    })).ok();

    write_wav("out/rising.wav", 44100, make_sample_16(1.0, 44100, |t: f64| -> f64 {
        let (min_f, max_f) = (1000.0, 8000.0);
        let max_t = 1.0; // Duration of clip in seconds
        let range = max_f - min_f;
        let f = max_f - (max_t - t) * range;
        SinWave(f)(t)
    })).ok();

    write_wav("out/racecar.wav", 44100, make_sample_16(15.0, 44100, |t: f64| -> f64 {
        let mut rng = rand::task_rng();
        let mut out = 0.0;
        if t < 14.0 { out += SawtoothWave(40.63 * (t / 2.0))(t); } // Engine
        if t < 1.0 { out += SawtoothWave(30.0)(t) * 10.0; } // Engine start
        if t < 14.0 && t.tan() > 0.0 { out += SquareWave(t.fract() * 523.25)(t); } // Gear
        if t < 14.0 && t.tan() < 0.0 { out += SquareWave(t.sin() * 1046.5)(t); } // Gear
        if t < 14.0 && t.tan() > 0.866 { out += SquareWave(t.fract() * 2093.0)(t); } // Gear
        if t > 14.0 { out += (rng.gen::<f64>() - 0.5) * 8.0 } // Tree
        (out / 4.0).min(1.0)
    })).ok();
}
<|endoftext|>


<commit_before>#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;

use std::env;
use std::env::VarError;
use std::io::prelude::*;
use std::fs::File;
use clap::{App, Arg};

mod github;

static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";

fn main() {
    let matches = App::new("release-party-br")
        .version("0.3.1")
        .author("Matthew Mayer <matthewkmayer@gmail.com>")
        .about("Release party automation")
        .arg(
            Arg::with_name("ORG")
                .short("o")
                .long("org")
                .value_name("github org")
                .help("Github org")
                .takes_value(true)
                .required(true),
        )
        .arg(
            Arg::with_name("DRYRUN")
                .short("d")
                .long("dry-run")
                .help("dry-run - don't actually create PRs"),
        )
        .get_matches();

    let org = matches
        .value_of("ORG")
        .expect("Please specify a github org");
    let org_url = format!("https://api.github.com/orgs/{}/repos", org);
    let dryrun = if matches.is_present("DRYRUN") {
        true
    } else {
        false
    };

    let token = match get_github_token() {
        Ok(gh_token) => gh_token,
        Err(e) => panic!(format!("Couldn't find {}: {}", GITHUB_TOKEN, e)),
    };
    let reqwest_client = match reqwest::Client::new() {
        Ok(new_client) => new_client,
        Err(e) => panic!("Couldn't create new reqwest client: {}", e),
    };

    let repos = get_repos_we_care_about(&token, &org_url, &reqwest_client);

    let mut pr_links: Vec<Option<String>> = repos
        .into_iter()
        .map(|repo| match get_release_pr_for(&repo, &token, &reqwest_client, dryrun) {
            Some(pr_url) => Some(pr_url),
            None => None,
        })
        .collect();
    // only keep the Some(PR_URL) items:
    pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());

    print_party_links(pr_links);
}

fn get_repos_we_care_about(token: &str, github_org_url: &str, reqwest_client: &reqwest::Client) -> Vec<github::GithubRepo> {
    let mut repos = match github::get_repos_at(&github_org_url, token, reqwest_client) {
        Ok(repos) => repos,
        Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
    };
    let repos_to_ignore = ignored_repos();

    // remove repos we don't care about:
    repos.retain(|repo| !repos_to_ignore.contains(&repo.name));

    repos
}

fn get_release_pr_for(repo: &github::GithubRepo, token: &str, client: &reqwest::Client, dryrun: bool) -> Option<String> {
    println!("looking for release PR for {}", repo.name);
    match github::existing_release_pr_location(repo, token, client) {
        Some(url) => Some(url),
        None => if !github::is_release_up_to_date_with_master(&repo.url, token, client) {
            if dryrun {
                Some(format!("Dry run: {} would get a release PR.", repo.url))
            } else {
                match github::create_release_pull_request(repo, token, client) {
                    Ok(pr_url) => Some(pr_url),
                    Err(_) => None,
                }
            }
        } else {
            None
        },
    }
}

fn print_party_links(pr_links: Vec<Option<String>>) {
    if !pr_links.is_empty() {
        println!("\nIt's a release party!  PRs to review and approve:");
        for link in pr_links {
            match link {
                Some(pr_link) => println!("{}", pr_link),
                None => println!("Party link is None: this shouldn't happen."),
            }
        }
    } else {
        println!("\nNo party today, all releases are done.");
    }
}

#[derive(Deserialize, Debug)]
struct IgnoredRepo {
    ignore: Option<Vec<String>>,
}

fn ignored_repos() -> Vec<String> {
    let mut f = match File::open("ignoredrepos.toml") {
        Ok(file) => file,
        Err(e) => {
            println!("Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}", e);
            return Vec::new();
        }
    };
    let mut buffer = String::new();
    match f.read_to_string(&mut buffer) {
        Ok(_) => (),
        Err(e) => {
            println!("Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}", e);
            return Vec::new();
        }
    }

    let ignored: IgnoredRepo = match toml::from_str(&buffer) {
        Ok(ignored_repos) => ignored_repos,
        Err(e) => {
            println!(
                "Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
                e
            );
            return Vec::new();
        }
    };
    match ignored.ignore {
        Some(repos_to_ignore) => repos_to_ignore,
        None => Vec::new(),
    }
}

fn get_github_token() -> Result<String, VarError> {
    env::var(GITHUB_TOKEN)
}
<commit_msg>Refactors main.<commit_after>#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;

use std::env;
use std::io::prelude::*;
use std::fs::File;
use clap::{App, Arg};

mod github;

static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";

fn main() {
    let matches = App::new("release-party-br")
        .version("0.3.1")
        .author("Matthew Mayer <matthewkmayer@gmail.com>")
        .about("Release party automation")
        .arg(
            Arg::with_name("ORG")
                .short("o")
                .long("org")
                .value_name("github org")
                .help("Github org")
                .takes_value(true)
                .required(true),
        )
        .arg(
            Arg::with_name("DRYRUN")
                .short("d")
                .long("dry-run")
                .help("dry-run - don't actually create PRs"),
        )
        .get_matches();

    let org_url = make_org_url(&matches);
    let token = get_github_token();
    let reqwest_client = get_reqwest_client();

    print_party_links(get_pr_links(get_repos_we_care_about(&token, &org_url, &reqwest_client), &token, &reqwest_client, is_dryrun(&matches)));
}

fn is_dryrun(matches: &clap::ArgMatches) -> bool {
    if matches.is_present("DRYRUN") {
        true
    } else {
        false
    }
}

fn make_org_url(matches: &clap::ArgMatches) -> String {
    let org = matches
        .value_of("ORG")
        .expect("Please specify a github org");

    format!("https://api.github.com/orgs/{}/repos", org)
}

fn get_pr_links(repos: Vec<github::GithubRepo>, token: &str, reqwest_client: &reqwest::Client, dryrun: bool) -> Vec<Option<String>> {
    let mut pr_links: Vec<Option<String>>  = repos.into_iter()
        .map(|repo| match get_release_pr_for(&repo, &token, &reqwest_client, dryrun) {
            Some(pr_url) => Some(pr_url),
            None => None,
        })
        .collect();
    // only keep the Some(PR_URL) items:
    pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
    pr_links
}

fn get_reqwest_client() -> reqwest::Client {
    match reqwest::Client::new() {
        Ok(new_client) => new_client,
        Err(e) => panic!("Couldn't create new reqwest client: {}", e),
    }
}

fn get_repos_we_care_about(token: &str, github_org_url: &str, reqwest_client: &reqwest::Client) -> Vec<github::GithubRepo> {
    let mut repos = match github::get_repos_at(&github_org_url, token, reqwest_client) {
        Ok(repos) => repos,
        Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
    };
    let repos_to_ignore = ignored_repos();

    // remove repos we don't care about:
    repos.retain(|repo| !repos_to_ignore.contains(&repo.name));

    repos
}

fn get_release_pr_for(repo: &github::GithubRepo, token: &str, client: &reqwest::Client, dryrun: bool) -> Option<String> {
    println!("looking for release PR for {}", repo.name);
    match github::existing_release_pr_location(repo, token, client) {
        Some(url) => Some(url),
        None => if !github::is_release_up_to_date_with_master(&repo.url, token, client) {
            if dryrun {
                Some(format!("Dry run: {} would get a release PR.", repo.url))
            } else {
                match github::create_release_pull_request(repo, token, client) {
                    Ok(pr_url) => Some(pr_url),
                    Err(_) => None,
                }
            }
        } else {
            None
        },
    }
}

fn print_party_links(pr_links: Vec<Option<String>>) {
    if !pr_links.is_empty() {
        println!("\nIt's a release party!  PRs to review and approve:");
        for link in pr_links {
            match link {
                Some(pr_link) => println!("{}", pr_link),
                None => println!("Party link is None: this shouldn't happen."),
            }
        }
    } else {
        println!("\nNo party today, all releases are done.");
    }
}

#[derive(Deserialize, Debug)]
struct IgnoredRepo {
    ignore: Option<Vec<String>>,
}

fn ignored_repos() -> Vec<String> {
    let mut f = match File::open("ignoredrepos.toml") {
        Ok(file) => file,
        Err(e) => {
            println!("Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}", e);
            return Vec::new();
        }
    };
    let mut buffer = String::new();
    match f.read_to_string(&mut buffer) {
        Ok(_) => (),
        Err(e) => {
            println!("Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}", e);
            return Vec::new();
        }
    }

    let ignored: IgnoredRepo = match toml::from_str(&buffer) {
        Ok(ignored_repos) => ignored_repos,
        Err(e) => {
            println!(
                "Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
                e
            );
            return Vec::new();
        }
    };
    match ignored.ignore {
        Some(repos_to_ignore) => repos_to_ignore,
        None => Vec::new(),
    }
}

fn get_github_token() -> String {
    match env::var(GITHUB_TOKEN){
        Ok(gh_token) => gh_token,
        Err(e) => panic!(format!("Couldn't find {}: {}", GITHUB_TOKEN, e)),
    }
}
<|endoftext|>


<commit_before>extern crate discord;

use std::env;
use discord::{Discord, State};
use discord::model::Event;

pub fn main() {
	// Log in to Discord using a bot token from the environment
	let discord = Discord::from_bot_token(
		&env::var("DISCORD_TOKEN").expect("Expected token"),
	).expect("login failed");

	// establish websocket and voice connection
	let (mut connection, ready) = discord.connect().expect("connect failed");
	println!("[Ready] {} is serving {} servers", ready.user.username, ready.servers.len());
	let mut state = State::new(ready);
	connection.sync_calls(&state.all_private_channels());

	// receive events forever
	loop {
		let event = match connection.recv_event() {
			Ok(event) => event,
			Err(err) => {
				println!("[Warning] Receive error: {:?}", err);
				if let discord::Error::WebSocket(..) = err {
					// Handle the websocket connection being dropped
					let (new_connection, ready) = discord.connect().expect("connect failed");
					connection = new_connection;
					state = State::new(ready);
					println!("[Ready] Reconnected successfully.");
				}
				if let discord::Error::Closed(..) = err {
					break
				}
				continue
			},
		};
		state.update(&event);

		match event {
			Event::MessageCreate(message) => {
				use std::ascii::AsciiExt;
				// safeguard: stop if the message is from us
				if message.author.id == state.user().id {
					continue
				}

				// reply to a command if there was one
				let mut split = message.content.split(' ');
				let first_word = split.next().unwrap_or("");
				let argument = split.next().unwrap_or("");

                if first_word.eq_ignore_ascii_case("!help") {
                    if argument.eq_ignore_ascii_case("commands") {
                        warn(discord.send_message(message.channel_id, "help, about, uber, distrowiki, and sourcecode are the avaliable commands. (!dj is buggy)", "", false))
                    }
                    else {
                    warn(discord.send_message(message.channel_id, "Umm, you gotta use it like this. !help [args]", "", false))
                    }
                }

                if first_word.eq_ignore_ascii_case("!about") {
                    warn(discord.send_message(message.channel_id, "I have no clue. All I know is that I was written by Arroz in a language called Rust, and my code is still being developed.", "", false))
                }

                if first_word.eq_ignore_ascii_case("!uber"){
					if argument.eq_ignore_ascii_case("ddog75") {
                        warn(discord.send_message(message.channel_id, "Alright, 10 minutes.", "", false))
                    } else {
                        warn(discord.send_message(message.channel_id, "Fuck off!", "", false))
                    }
                }

                if first_word.eq_ignore_ascii_case("!sourcecode") {
                    warn(discord.send_message(message.channel_id, "Okay, here you go. https://github.com/aarroz/rice_bot2", "", false))
                }
				//Section that prints wikis for linux distributions.
				if first_word.eq_ignore_ascii_case("!distrowiki") {
					if argument.eq_ignore_ascii_case("arch") {
						warn(discord.send_message(message.channel_id, "Here's the Arch Wiki! https://wiki.archlinux.org/", "", false))
					}
					if argument.eq_ignore_ascii_case("ubuntu") {
						warn(discord.send_message(message.channel_id, "Here's the Ubuntu Wiki! https://wiki.ubuntu.com/", "", false))
					}
					if argument.eq_ignore_ascii_case("debian") {
						warn(discord.send_message(message.channel_id, "Here's the Debian Wiki! https://wiki.debian.org/", "", false))
					}
					if argument.eq_ignore_ascii_case("antergos") {
						warn(discord.send_message(message.channel_id, "Here's the Antergos Wiki! https://antergos.com/wiki/", "", false))
					}
					if argument.eq_ignore_ascii_case("centos") {
						warn(discord.send_message(message.channel_id, "Here's the CentOS Wiki! https://wiki.centos.org/", "", false))
					}
					//Sorry OpenBSD users.
					if argument.eq_ignore_ascii_case("openbsd") {
						warn(discord.send_message(message.channel_id, "No, just no.", "", false))
					}
				}

                // Command for using dj.
				if first_word.eq_ignore_ascii_case("!dj") {
					let vchan = state.find_voice_user(message.author.id);
					if argument.eq_ignore_ascii_case("stop") {
						vchan.map(|(sid, _)| connection.voice(sid).stop());
					} else if argument.eq_ignore_ascii_case("quit") {
						vchan.map(|(sid, _)| connection.drop_voice(sid));
					} else {
						let output = if let Some((server_id, channel_id)) = vchan {
							match discord::voice::open_ytdl_stream(argument) {
								Ok(stream) => {
									let voice = connection.voice(server_id);
									voice.set_deaf(true);
									voice.connect(channel_id);
									voice.play(stream);
									String::new()
								},
								Err(error) => format!("Error: {}", error),
							}
						} else {
							"You must be in a voice channel to DJ".to_owned()
						};
						if !output.is_empty() {
							warn(discord.send_message(message.channel_id, &output, "", false));
						}
					}
				}
			}
			Event::VoiceStateUpdate(server_id, _) => {
				// If someone moves/hangs up, and we are in a voice channel,
				if let Some(cur_channel) = connection.voice(server_id).current_channel() {
					// and our current voice channel is empty, disconnect from voice
					match server_id {
						Some(server_id) => if let Some(srv) = state.servers().iter().find(|srv| srv.id == server_id) {
							if srv.voice_states.iter().filter(|vs| vs.channel_id == Some(cur_channel)).count() <= 1 {
								connection.voice(Some(server_id)).disconnect();
							}
						},
						None => if let Some(call) = state.calls().get(&cur_channel) {
							if call.voice_states.len() <= 1 {
								connection.voice(server_id).disconnect();
							}
						}
					}
				}
			}
			_ => {}, // discard other events
		}
	}
}

fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
	match result {
		Ok(_) => {},
		Err(err) => println!("[Warning] {:?}", err)
	}
}
<commit_msg>Added Gentoo Wiki<commit_after>extern crate discord;

use std::env;
use discord::{Discord, State};
use discord::model::Event;

pub fn main() {
	// Log in to Discord using a bot token from the environment
	let discord = Discord::from_bot_token(
		&env::var("DISCORD_TOKEN").expect("Expected token"),
	).expect("login failed");

	// establish websocket and voice connection
	let (mut connection, ready) = discord.connect().expect("connect failed");
	println!("[Ready] {} is serving {} servers", ready.user.username, ready.servers.len());
	let mut state = State::new(ready);
	connection.sync_calls(&state.all_private_channels());

	// receive events forever
	loop {
		let event = match connection.recv_event() {
			Ok(event) => event,
			Err(err) => {
				println!("[Warning] Receive error: {:?}", err);
				if let discord::Error::WebSocket(..) = err {
					// Handle the websocket connection being dropped
					let (new_connection, ready) = discord.connect().expect("connect failed");
					connection = new_connection;
					state = State::new(ready);
					println!("[Ready] Reconnected successfully.");
				}
				if let discord::Error::Closed(..) = err {
					break
				}
				continue
			},
		};
		state.update(&event);

		match event {
			Event::MessageCreate(message) => {
				use std::ascii::AsciiExt;
				// safeguard: stop if the message is from us
				if message.author.id == state.user().id {
					continue
				}

				// reply to a command if there was one
				let mut split = message.content.split(' ');
				let first_word = split.next().unwrap_or("");
				let argument = split.next().unwrap_or("");

                if first_word.eq_ignore_ascii_case("!help") {
                    if argument.eq_ignore_ascii_case("commands") {
                        warn(discord.send_message(message.channel_id, "help, about, uber, distrowiki, and sourcecode are the avaliable commands. (!dj is buggy)", "", false))
                    }
                    else {
                    warn(discord.send_message(message.channel_id, "Umm, you gotta use it like this. !help [args]", "", false))
                    }
                }

                if first_word.eq_ignore_ascii_case("!about") {
                    warn(discord.send_message(message.channel_id, "I have no clue. All I know is that I was written by Arroz in a language called Rust, and my code is still being developed.", "", false))
                }

                if first_word.eq_ignore_ascii_case("!uber"){
					if argument.eq_ignore_ascii_case("ddog75") {
                        warn(discord.send_message(message.channel_id, "Alright, 10 minutes.", "", false))
                    } else {
                        warn(discord.send_message(message.channel_id, "Fuck off!", "", false))
                    }
                }

                if first_word.eq_ignore_ascii_case("!sourcecode") {
                    warn(discord.send_message(message.channel_id, "Okay, here you go. https://github.com/aarroz/rice_bot2", "", false))
                }
				//Section that prints wikis for linux distributions.
				if first_word.eq_ignore_ascii_case("!distrowiki") {
					if argument.eq_ignore_ascii_case("arch") {
						warn(discord.send_message(message.channel_id, "Here's the Arch Wiki! https://wiki.archlinux.org/", "", false))
					}
					if argument.eq_ignore_ascii_case("ubuntu") {
						warn(discord.send_message(message.channel_id, "Here's the Ubuntu Wiki! https://wiki.ubuntu.com/", "", false))
					}
					if argument.eq_ignore_ascii_case("debian") {
						warn(discord.send_message(message.channel_id, "Here's the Debian Wiki! https://wiki.debian.org/", "", false))
					}
					if argument.eq_ignore_ascii_case("antergos") {
						warn(discord.send_message(message.channel_id, "Here's the Antergos Wiki! https://antergos.com/wiki/", "", false))
					}
					if argument.eq_ignore_ascii_case("centos") {
						warn(discord.send_message(message.channel_id, "Here's the CentOS Wiki! https://wiki.centos.org/", "", false))
					}
					//Sorry OpenBSD users.
					if argument.eq_ignore_ascii_case("openbsd") {
						warn(discord.send_message(message.channel_id, "No, just no.", "", false))
					}
					if argument.eq_ignore_ascii_case("gentoo") {
						warn(discord.send_message(message.channel_id, "Here's the Gentoo Wiki! https://wiki.gentoo.org/wiki/Main_Page", "", false))
					}
				}

                // Command for using dj.
				if first_word.eq_ignore_ascii_case("!dj") {
					let vchan = state.find_voice_user(message.author.id);
					if argument.eq_ignore_ascii_case("stop") {
						vchan.map(|(sid, _)| connection.voice(sid).stop());
					} else if argument.eq_ignore_ascii_case("quit") {
						vchan.map(|(sid, _)| connection.drop_voice(sid));
					} else {
						let output = if let Some((server_id, channel_id)) = vchan {
							match discord::voice::open_ytdl_stream(argument) {
								Ok(stream) => {
									let voice = connection.voice(server_id);
									voice.set_deaf(true);
									voice.connect(channel_id);
									voice.play(stream);
									String::new()
								},
								Err(error) => format!("Error: {}", error),
							}
						} else {
							"You must be in a voice channel to DJ".to_owned()
						};
						if !output.is_empty() {
							warn(discord.send_message(message.channel_id, &output, "", false));
						}
					}
				}
			}
			Event::VoiceStateUpdate(server_id, _) => {
				// If someone moves/hangs up, and we are in a voice channel,
				if let Some(cur_channel) = connection.voice(server_id).current_channel() {
					// and our current voice channel is empty, disconnect from voice
					match server_id {
						Some(server_id) => if let Some(srv) = state.servers().iter().find(|srv| srv.id == server_id) {
							if srv.voice_states.iter().filter(|vs| vs.channel_id == Some(cur_channel)).count() <= 1 {
								connection.voice(Some(server_id)).disconnect();
							}
						},
						None => if let Some(call) = state.calls().get(&cur_channel) {
							if call.voice_states.len() <= 1 {
								connection.voice(server_id).disconnect();
							}
						}
					}
				}
			}
			_ => {}, // discard other events
		}
	}
}

fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
	match result {
		Ok(_) => {},
		Err(err) => println!("[Warning] {:?}", err)
	}
}
<|endoftext|>


<commit_before>extern crate libc;

use std::cmp::min;
use std::io::{BufRead, BufReader};
use std::time::Duration;

const USAGE_STRING: &'static str = "\
usage: gol genmap SIZE_V SIZE_H  (generates an empty map)
       gol play FILE [TIME_MS]   (plays the game)

       maps: must be rectangular
             '·' is a dead cell, anything else is a living cell
         ^C: exit
";

static mut exit: bool = false;

type Map = Vec<Vec<Cell>>;

struct Cell {
    alive: bool,
    lives: bool,
}

fn print_usage() {
    print!("{}", USAGE_STRING);
}

fn print_new_map(size_args: &[String]) {
    let sizev = size_args[0].parse::<usize>().unwrap();
    let sizeh = size_args[1].parse::<usize>().unwrap();
    let map_line = std::iter::repeat('·').take(sizeh).collect::<String>();
    for _ in 0..sizev {
        println!("{}", map_line);
    }
}

fn get_map(filename: &String) -> Option<Map> {
    let file = match std::fs::File::open(filename) {
        Ok(file) => file,
        Err(error) => {
            println!("{}: {}", filename, error);
            return None
        },
    };
    let reader = BufReader::new(file);
    Some(reader.lines().map(|l| l.unwrap().chars().map(|c| match c {
        '·' => Cell { alive: false, lives: false },
        _   => Cell { alive: true, lives: true },
    }).collect()).collect())
}

fn iterate(map: &mut Map) {
    let i_max = map.len();
    let j_max = map[0].len();
    let mut live_neighbours: usize;
    for i in 0..i_max {
        for j in 0..j_max {
            live_neighbours = 0;
            for m in i.saturating_sub(1)..min(i + 2, i_max) {
                for n in j.saturating_sub(1)..min(j + 2, j_max) {
                    if map[m][n].alive && (m != i || n !=  j) { live_neighbours += 1; }
                }
            }
            if !map[i][j].alive {
                if live_neighbours == 3  { map[i][j].lives = true; }
            }
            else if live_neighbours < 2 || 3 < live_neighbours { map[i][j].lives = false; }
        }
    }
    for i in 0..map.len() {
        for j in 0..map[0].len() {
            map[i][j].alive = map[i][j].lives;
        }
    }
}

fn display_map(map: &Map) {
    let mut screen = String::with_capacity(map.len() * (map[0].len() * 3 + 1) + 7);
    screen.push_str("\x1B[2J\x1B[H"); // clear screen and move cursor to 1;1
    for i in 0..map.len() {
        for j in 0..map[0].len() {
            if map[i][j].alive { screen.push_str(" X"); }
            else { screen.push_str(" ·"); }
        }
        screen.push('\n');
    }
    print!("{}{}x{}, ", screen, map.len(), map[0].len());
}

fn play_map(filename: &String, pause_time_ms: u64) {
    unsafe {
        let handler = interrupt as *const usize;
        libc::signal(libc::SIGINT, handler as usize);
    }
    let mut map = get_map(filename).unwrap();
    let size_row = map[0].len();
    for row in map.iter() {
        if row.len() != size_row {
            println!("error: map is not a rectangle");
            return
        }
    }
    let mut niter = 0usize;
    print!("\x1B[?47h\x1B[?25l"); // save screen and hide cursor
    loop {
        display_map(&map);
        println!("iteration: {}", niter);
        iterate(&mut map);
        niter += 1;
        std::thread::sleep(Duration::from_millis(pause_time_ms));
        unsafe {
            if exit {
                print!("\x1B[?47l\x1B[?25h"); // restore screen and show cursor
                return
            }
        }
    }
}

fn interrupt(_: libc::c_int) {
    unsafe { exit = true; }
}

fn main() {
    let args: Vec<_> = std::env::args().collect();
    if args.len() == 4 && args[1] == "genmap" { print_new_map(&args[2..4]); }
    else if args.len() == 3 && args[1] == "play" { play_map(&args[2], 400); }
    else if args.len() == 4 && args[1] == "play" { play_map(&args[2], args[3].parse::<u64>().unwrap()); }
    else { print_usage(); }
}
<commit_msg>use libc::sighandler_t type<commit_after>extern crate libc;

use std::cmp::min;
use std::io::{BufRead, BufReader};
use std::time::Duration;

const USAGE_STRING: &'static str = "\
usage: gol genmap SIZE_V SIZE_H  (generates an empty map)
       gol play FILE [TIME_MS]   (plays the game)

       maps: must be rectangular
             '·' is a dead cell, anything else is a living cell
         ^C: exit
";

static mut exit: bool = false;

type Map = Vec<Vec<Cell>>;

struct Cell {
    alive: bool,
    lives: bool,
}

fn print_usage() {
    print!("{}", USAGE_STRING);
}

fn print_new_map(size_args: &[String]) {
    let sizev = size_args[0].parse::<usize>().unwrap();
    let sizeh = size_args[1].parse::<usize>().unwrap();
    let map_line = std::iter::repeat('·').take(sizeh).collect::<String>();
    for _ in 0..sizev {
        println!("{}", map_line);
    }
}

fn get_map(filename: &String) -> Option<Map> {
    let file = match std::fs::File::open(filename) {
        Ok(file) => file,
        Err(error) => {
            println!("{}: {}", filename, error);
            return None
        },
    };
    let reader = BufReader::new(file);
    Some(reader.lines().map(|l| l.unwrap().chars().map(|c| match c {
        '·' => Cell { alive: false, lives: false },
        _   => Cell { alive: true, lives: true },
    }).collect()).collect())
}

fn iterate(map: &mut Map) {
    let i_max = map.len();
    let j_max = map[0].len();
    let mut live_neighbours: usize;
    for i in 0..i_max {
        for j in 0..j_max {
            live_neighbours = 0;
            for m in i.saturating_sub(1)..min(i + 2, i_max) {
                for n in j.saturating_sub(1)..min(j + 2, j_max) {
                    if map[m][n].alive && (m != i || n !=  j) { live_neighbours += 1; }
                }
            }
            if !map[i][j].alive {
                if live_neighbours == 3  { map[i][j].lives = true; }
            }
            else if live_neighbours < 2 || 3 < live_neighbours { map[i][j].lives = false; }
        }
    }
    for i in 0..map.len() {
        for j in 0..map[0].len() {
            map[i][j].alive = map[i][j].lives;
        }
    }
}

fn display_map(map: &Map) {
    let mut screen = String::with_capacity(map.len() * (map[0].len() * 3 + 1) + 7);
    screen.push_str("\x1B[2J\x1B[H"); // clear screen and move cursor to 1;1
    for i in 0..map.len() {
        for j in 0..map[0].len() {
            if map[i][j].alive { screen.push_str(" X"); }
            else { screen.push_str(" ·"); }
        }
        screen.push('\n');
    }
    print!("{}{}x{}, ", screen, map.len(), map[0].len());
}

fn play_map(filename: &String, pause_time_ms: u64) {
    unsafe { libc::signal(libc::SIGINT, interrupt as libc::sighandler_t); }
    let mut map = get_map(filename).unwrap();
    let size_row = map[0].len();
    for row in map.iter() {
        if row.len() != size_row {
            println!("error: map is not a rectangle");
            return
        }
    }
    let mut niter = 0usize;
    print!("\x1B[?47h\x1B[?25l"); // save screen and hide cursor
    loop {
        display_map(&map);
        println!("iteration: {}", niter);
        iterate(&mut map);
        niter += 1;
        std::thread::sleep(Duration::from_millis(pause_time_ms));
        unsafe {
            if exit {
                print!("\x1B[?47l\x1B[?25h"); // restore screen and show cursor
                return
            }
        }
    }
}

fn interrupt(_: libc::c_int) {
    unsafe { exit = true; }
}

fn main() {
    let args: Vec<_> = std::env::args().collect();
    if args.len() == 4 && args[1] == "genmap" { print_new_map(&args[2..4]); }
    else if args.len() == 3 && args[1] == "play" { play_map(&args[2], 400); }
    else if args.len() == 4 && args[1] == "play" { play_map(&args[2], args[3].parse::<u64>().unwrap()); }
    else { print_usage(); }
}
<|endoftext|>


<commit_before>extern crate clap;
extern crate semver;
extern crate tomllib;

mod config;
mod version;

use std::path::Path;
use std::io::{Read, Write};
use std::fs::{File, OpenOptions};

use semver::Version;
use tomllib::TOMLParser;
use tomllib::types::{Value, ParseResult};

fn main() {
    let conf = config::get_config();
    let raw_data = read_file(&conf.manifest);
    let parser = TOMLParser::new();
    let (mut parser, result) = parser.parse(&raw_data);
    match result {
        ParseResult::Full => {},
        _ => panic!("couldn't parse Cargo.toml"),
    }

    let raw_value = parser.get_value("package.version").expect("package.version missing");
    let mut version = if let Value::String(raw_version, _) = raw_value {
        Version::parse(&raw_version).unwrap()
    } else {
        panic!("version not a string")
    };

    let old_version = version.clone();
    version::update_version(&mut version, conf.version);
    println!("Version {} -> {}", old_version, version);

    parser.set_value("package.version", Value::basic_string(version.to_string()).unwrap());

    let mut f = OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(&conf.manifest)
        .unwrap();
    f.write_all(format!("{}", parser).as_bytes()).unwrap();
}

fn read_file(file: &Path) -> String {
    let mut file = File::open(file).unwrap();
    let mut raw_data = String::new();
    file.read_to_string(&mut raw_data).unwrap();
    raw_data
}
<commit_msg>replace awkward `if let` with `match`<commit_after>extern crate clap;
extern crate semver;
extern crate tomllib;

mod config;
mod version;

use std::path::Path;
use std::io::{Read, Write};
use std::fs::{File, OpenOptions};

use semver::Version;
use tomllib::TOMLParser;
use tomllib::types::{Value, ParseResult};

fn main() {
    let conf = config::get_config();
    let raw_data = read_file(&conf.manifest);
    let parser = TOMLParser::new();
    let (mut parser, result) = parser.parse(&raw_data);
    match result {
        ParseResult::Full => {},
        _ => panic!("couldn't parse Cargo.toml"),
    }

    let raw_value = parser.get_value("package.version").expect("package.version missing");
    let mut version = match raw_value {
        Value::String(raw_version, _) => Version::parse(&raw_version).unwrap(),
        _ => panic!("version not a string"),
    };

    let old_version = version.clone();
    version::update_version(&mut version, conf.version);
    println!("Version {} -> {}", old_version, version);

    parser.set_value("package.version", Value::basic_string(version.to_string()).unwrap());

    let mut f = OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(&conf.manifest)
        .unwrap();
    f.write_all(format!("{}", parser).as_bytes()).unwrap();
}

fn read_file(file: &Path) -> String {
    let mut file = File::open(file).unwrap();
    let mut raw_data = String::new();
    file.read_to_string(&mut raw_data).unwrap();
    raw_data
}
<|endoftext|>


<commit_before>use pa::{PaResult, PaError};
use ll;

use std::time::Duration;

pub fn to_pa_result(code: i32) -> PaResult
{
    if code == ll::paNoError
    {
        return Ok(());
    }
    Err(PaError::from_i32(code))
}

pub fn pa_time_to_duration(input: f64) -> Duration
{
    assert!(input >= -1.0);
    let valid_input = if input < 0.0 { 0.0 } else { input };
    let secs = valid_input.floor();
    let nanos = (valid_input - secs) * 1e9;
    Duration::new(secs as u64, nanos as u32)
}

pub fn duration_to_pa_time(duration: Duration) -> f64
{
    duration.as_secs() as f64 + (duration.subsec_nanos() as f64 * 1e-9)
}

#[cfg(test)]
mod test {
    #[test]
    fn test_conversion() {
        let seconds = 2.512389131321938123681627;
        let duration = super::pa_time_to_duration(seconds);
        let seconds2 = super::duration_to_pa_time(duration);

        println!("{}", (seconds - seconds2).abs());
        assert!((seconds - seconds2).abs() <= 1e-8);
    }
}
<commit_msg>Remove assertion.<commit_after>use pa::{PaResult, PaError};
use ll;

use std::time::Duration;

pub fn to_pa_result(code: i32) -> PaResult
{
    if code == ll::paNoError
    {
        return Ok(());
    }
    Err(PaError::from_i32(code))
}

pub fn pa_time_to_duration(input: f64) -> Duration
{
    let valid_input = if input < 0.0 { 0.0 } else { input };
    let secs = valid_input.floor();
    let nanos = (valid_input - secs) * 1e9;
    Duration::new(secs as u64, nanos as u32)
}

pub fn duration_to_pa_time(duration: Duration) -> f64
{
    duration.as_secs() as f64 + (duration.subsec_nanos() as f64 * 1e-9)
}

#[cfg(test)]
mod test {
    #[test]
    fn test_conversion() {
        let seconds = 2.512389131321938123681627;
        let duration = super::pa_time_to_duration(seconds);
        let seconds2 = super::duration_to_pa_time(duration);

        println!("{}", (seconds - seconds2).abs());
        assert!((seconds - seconds2).abs() <= 1e-8);
    }
}
<|endoftext|>


<commit_before>/* Stones esoteric programming language
 * (c) 2016 Zack Hixon - see LICENSE.txt */

/** NOTE: Hey there! This isn't even remotely started yet. I'm gonna need a
 * WHOLE lot of stuff to make this even *resemble* an interpreter. It also
 * isn't currently up-to-date with the "specification," so it features
 * misleading stuff like the Stone struct right below this, along with the
 * field vector.  Expect a lot of this stuff to change. */

#[derive(Debug)]
struct Stone {
    x: i32,
    y: i32,
    color: Color
}

impl Stone {
    fn new(x: i32, y: i32, color: Color) -> Stone {
        Stone {
            x: x,
            y: y,
            color: color
        }
    }

    /* only check stones with 0 <= x <= 9 and 0 <= y <= 9 */
    fn empty() -> Stone {
        Stone {
            x: -1,
            y: -1,
            color: Color::Invisible
        }
    }
}

#[derive(Debug)]
enum Color {
    Red,
    Orange,
    Yellow,
    Green,
    Blue,
    Purple,
    Invisible
}

fn main() {
    println!("test stone: (debug)");

    let mut test_stone = Stone {
        x: 0,
        y: 0,
        color: Color::Yellow
    };

    println!("{:?}", test_stone);

    test_stone.x = 1;
    test_stone.y = 1;
    test_stone.color = Color::Blue;

    println!("{:?}", test_stone);

    let mut field: Vec<Vec<Stone>> =
        vec![vec![Stone::new(0, 0, Color::Red),
                  Stone::new(1, 0, Color::Blue),
                  Stone::new(2, 0, Color::Green)],
             vec![Stone::empty(),
                  Stone::empty(),
                  Stone::empty()],
             vec![Stone::empty(),
                  Stone::empty(),
                  Stone::empty()]];

    println!("\nall stones:");
    for row in field {
        for stone in row {
            print!("{} {} {:?}\n", stone.x, stone.y, stone.color);
        }
        println!("");
    }
}

<commit_msg>Create field<commit_after>/* Stones esoteric programming language
 * (c) 2016 Zack Hixon - see LICENSE.txt */

/** NOTE: Hey there! This isn't even remotely started yet. I'm gonna need a
 * WHOLE lot of stuff to make this even *resemble* an interpreter. It also
 * isn't currently up-to-date with the "specification," so it features
 * misleading stuff like the Stone struct right below this, along with the
 * field vector.  Expect a lot of this stuff to change. */

#[derive(Debug)]
struct Stone {
    x: i32,
    y: i32,
    color: Color
}

impl Stone {
    fn new(x: i32, y: i32, color: Color) -> Stone {
        Stone {
            x: x,
            y: y,
            color: color
        }
    }

    /* only check stones with 0 <= x <= 9 and 0 <= y <= 9 */
    fn empty() -> Stone {
        Stone {
            x: -1,
            y: -1,
            color: Color::Invis
        }
    }
}

#[derive(Debug)]
enum Color {
    Red,
    Orange,
    Yellow,
    Green,
    Blue,
    Purple,
    Invis
}

fn main() {
    println!("test stone: (debug)");

    let mut test_stone = Stone {
        x: 0,
        y: 0,
        color: Color::Yellow
    };

    println!("{:?}", test_stone);

    test_stone.x = 1;
    test_stone.y = 1;
    test_stone.color = Color::Blue;

    println!("{:?}", test_stone);

    let mut field: Vec<Vec<Color>> = /* so much for 80 columns */
        vec![vec![Color::Blue,  Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Orange,Color::Invis, Color::Invis, Color::Invis, Color::Invis ],
             vec![Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis ],
             vec![Color::Invis, Color::Invis, Color::Red,   Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Green, Color::Invis, Color::Invis ],
             vec![Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis ],
             vec![Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Yellow,Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Purple],
             vec![Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis, Color::Invis ]];

    for row in &field {
        for color in row {
            match color {
                &Color::Red => print!("{:?}... ", color),
                &Color::Orange => print!("{:?} ", color),
                &Color::Yellow => print!("{:?} ", color),
                &Color::Green => print!("{:?}. ", color),
                &Color::Blue => print!("{:?}.. ", color),
                &Color::Purple => print!("{:?} ", color),
                &Color::Invis => print!("...... "), /* oh. */
            }
        }
        println!("");
    }
}

<|endoftext|>


<commit_before>#[macro_export]
macro_rules! make_getter_function_for_optional {
    ($fnname:ident, $name:expr, $mapper:ty) => {
        pub fn $fnname(&self) -> Option<$mapper> {
            self.0.get_only($name).cloned().map(From::from)
        }
    }
}

#[macro_export]
macro_rules! make_getter_function_for_values {
    ($fnname:ident, $name:expr, $mapper:ty) => {
        pub fn $fnname(&self) -> Vec<$mapper> {
            self.0
                .get_all($name)
                .iter()
                .map(Clone::clone)
                .map(From::from)
                .collect()
        }
    }
}

#[macro_export]
macro_rules! create_data_type {
    ( $name:ident ) => {
        #[derive(Eq, PartialEq, Debug)]
        pub struct $name(String, $crate::param::Parameters);

        impl $name {
            pub fn new(raw: String, params: $crate::param::Parameters) -> $name {
                $name(raw, params)
            }

            pub fn from_raw(raw: String) -> $name {
                $name(raw, BTreeMap::new())
            }

            pub fn raw(&self) -> &String {
                &self.0
            }

            pub fn into_raw(self) -> String {
                self.0
            }
        }

        impl From<Property> for $name {
            fn from(p: Property) -> $name {
                $name::new(p.raw_value, p.params)
            }
        }
    }
}

#[cfg(feature = "timeconversions")]
pub const DATE_TIME_FMT : &'static str = "%Y%m%dT%H%M%SZ";

#[cfg(feature = "timeconversions")]
pub const DATE_FMT      : &'static str = "%Y%m%d";

<commit_msg>Add params getter for helper datatype generator (#24)<commit_after>#[macro_export]
macro_rules! make_getter_function_for_optional {
    ($fnname:ident, $name:expr, $mapper:ty) => {
        pub fn $fnname(&self) -> Option<$mapper> {
            self.0.get_only($name).cloned().map(From::from)
        }
    }
}

#[macro_export]
macro_rules! make_getter_function_for_values {
    ($fnname:ident, $name:expr, $mapper:ty) => {
        pub fn $fnname(&self) -> Vec<$mapper> {
            self.0
                .get_all($name)
                .iter()
                .map(Clone::clone)
                .map(From::from)
                .collect()
        }
    }
}

#[macro_export]
macro_rules! create_data_type {
    ( $name:ident ) => {
        #[derive(Eq, PartialEq, Debug)]
        pub struct $name(String, $crate::param::Parameters);

        impl $name {
            pub fn new(raw: String, params: $crate::param::Parameters) -> $name {
                $name(raw, params)
            }

            pub fn from_raw(raw: String) -> $name {
                $name(raw, BTreeMap::new())
            }

            pub fn raw(&self) -> &String {
                &self.0
            }

            pub fn into_raw(self) -> String {
                self.0
            }

            pub fn params(&self) -> &$crate::param::Parameters {
                &self.1
            }
        }

        impl From<Property> for $name {
            fn from(p: Property) -> $name {
                $name::new(p.raw_value, p.params)
            }
        }
    }
}

#[cfg(feature = "timeconversions")]
pub const DATE_TIME_FMT : &'static str = "%Y%m%dT%H%M%SZ";

#[cfg(feature = "timeconversions")]
pub const DATE_FMT      : &'static str = "%Y%m%d";

<|endoftext|>


<commit_before>mod words;

mod sort;

use std::env;
use std::collections::{BTreeSet};

fn matches(pat: &String, line: &str) -> bool {
    fn check<P, L>(mut pc: P, lc: L) -> bool where P: Iterator<Item=char>, L: Iterator<Item=char> {
        let mut c = pc.next();
        for outer in lc {
            match c {
                Some(ch) => {
                    if outer == ch {
                        c = pc.next();
                    }
                    else if words::consonant(outer) {
                        return false;
                    }
                },

                None => {
                    return true;
                }
            }
        }

        c.is_none()
    }

    (pat.len() <= line.len()) && (
        check(pat.chars(), line.chars()) ||
        check(pat.chars().rev(), line.chars().rev())
    )
}

fn usage(args: Vec<String>) -> ! {
    println!("Usage: {} <consonants>", args[0]);
    std::process::exit(2);
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 2 {
        usage(args);
    }

    let cons = args[1].to_lowercase();
    if cons.chars().any(|c| {!words::consonant(c)}) {
        usage(args);
    }

    let words = words::WORDS.lines().map(|line| {
        line.to_lowercase()
    }).filter(|line| {
        matches(&cons, line)
    });

    let mut found = BTreeSet::new();
    for word in words {
        found.insert(sort::Length(word));
    }
    if found.len() == 0 {
        println!("No matches found.");
        return;
    }

    for word in found.iter().rev() {
        println!("{}", word.0);
    }
}
<commit_msg>Detect pattern backwards, not word.<commit_after>mod words;

mod sort;

use std::env;
use std::collections::{BTreeSet};

fn matches(pat: &String, line: &str) -> bool {
    fn check<P, L>(mut pc: P, lc: L) -> bool where P: Iterator<Item=char>, L: Iterator<Item=char> {
        let mut c = pc.next();
        for outer in lc {
            match c {
                Some(ch) => {
                    if outer == ch {
                        c = pc.next();
                    }
                    else if words::consonant(outer) {
                        return false;
                    }
                },

                None => {
                    return true;
                }
            }
        }

        c.is_none()
    }

    (pat.len() <= line.len()) && (
        check(pat.chars(), line.chars()) ||
        check(pat.chars().rev(), line.chars())
    )
}

fn usage(args: Vec<String>) -> ! {
    println!("Usage: {} <consonants>", args[0]);
    std::process::exit(2);
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 2 {
        usage(args);
    }

    let cons = args[1].to_lowercase();
    if cons.chars().any(|c| {!words::consonant(c)}) {
        usage(args);
    }

    let words = words::WORDS.lines().map(|line| {
        line.to_lowercase()
    }).filter(|line| {
        matches(&cons, line)
    });

    let mut found = BTreeSet::new();
    for word in words {
        found.insert(sort::Length(word));
    }
    if found.len() == 0 {
        println!("No matches found.");
        return;
    }

    for word in found.iter().rev() {
        println!("{}", word.0);
    }
}
<|endoftext|>


<commit_before>use std::env;
use std::path::PathBuf;
#[cfg(windows)]
use kernel32::GetNativeSystemInfo;

pub fn obtain_groonga_versioned_path() -> PathBuf {
    let base_dir = env::home_dir().unwrap();
    base_dir.join(".groonga").join("versions")
}

pub fn obtain_install_base_path() -> PathBuf {
    let base_dir = env::home_dir().unwrap();
    base_dir.join(".groonga")
}

#[cfg(windows)]
pub fn obtain_arch() -> Option<String> {
    use std::mem;

    // Detect architectures
    const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
    const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0;
    let mut sys_info;
    unsafe {
        sys_info = mem::zeroed();
        GetNativeSystemInfo(&mut sys_info);
    }

    let arch = match sys_info.wProcessorArchitecture {
        PROCESSOR_ARCHITECTURE_AMD64 => "x64",
        PROCESSOR_ARCHITECTURE_INTEL => "x86",
        _ => return None,
    };
    Some(arch.to_string())
}

#[cfg(not(windows))]
pub fn obtain_arch() -> Option<String> {
    use libc;
    use std::mem;
    use std::ffi::CStr;

    let mut sys_info;
    let machine = unsafe {
        sys_info = mem::zeroed();
        if libc::uname(&mut sys_info) != 0 {
            return None;
        }

        CStr::from_ptr(sys_info.machine.as_ptr()).to_bytes()
    };
    Some(String::from_utf8_lossy(machine).into_owned())
}
<commit_msg>util: Add test cases<commit_after>use std::env;
use std::path::PathBuf;
#[cfg(windows)]
use kernel32::GetNativeSystemInfo;

pub fn obtain_groonga_versioned_path() -> PathBuf {
    let base_dir = env::home_dir().unwrap();
    base_dir.join(".groonga").join("versions")
}

pub fn obtain_install_base_path() -> PathBuf {
    let base_dir = env::home_dir().unwrap();
    base_dir.join(".groonga")
}

#[cfg(windows)]
pub fn obtain_arch() -> Option<String> {
    use std::mem;

    // Detect architectures
    const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
    const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0;
    let mut sys_info;
    unsafe {
        sys_info = mem::zeroed();
        GetNativeSystemInfo(&mut sys_info);
    }

    let arch = match sys_info.wProcessorArchitecture {
        PROCESSOR_ARCHITECTURE_AMD64 => "x64",
        PROCESSOR_ARCHITECTURE_INTEL => "x86",
        _ => return None,
    };
    Some(arch.to_string())
}

#[cfg(not(windows))]
pub fn obtain_arch() -> Option<String> {
    use libc;
    use std::mem;
    use std::ffi::CStr;

    let mut sys_info;
    let machine = unsafe {
        sys_info = mem::zeroed();
        if libc::uname(&mut sys_info) != 0 {
            return None;
        }

        CStr::from_ptr(sys_info.machine.as_ptr()).to_bytes()
    };
    Some(String::from_utf8_lossy(machine).into_owned())
}

#[cfg(test)]
mod test {
    use super::*;
    use std::env;
    use std::path::PathBuf;

    #[test]
    fn test_obtain_arch() {
        let arch = obtain_arch();
        assert!(arch.is_some());
    }

    #[test]
    fn test_obtain_groonga_versioned_path() {
        let home = env::home_dir().unwrap();
        let _ = env::set_var("HOME", "/home/grnenv");
        let path = obtain_groonga_versioned_path();
        let mut versioned = PathBuf::new();
        versioned.push("/home/grnenv/.groonga/versions");
        assert_eq!(versioned, path);
        let _ = env::set_var("HOME", home);
    }

    #[test]
    fn test_obtain_install_base_path() {
        let home = env::home_dir().unwrap();
        let _ = env::set_var("HOME", "/home/grnenv");
        let path = obtain_install_base_path();
        let mut versioned = PathBuf::new();
        versioned.push("/home/grnenv/.groonga");
        assert_eq!(versioned, path);
        let _ = env::set_var("HOME", home);
    }
}
<|endoftext|>