<commit_before>#[macro_use] extern crate macro_attr;
#[macro_use] extern crate enum_derive;

use std::io::Write;
use std::env;

mod keybinds;
use keybinds::*;

mod file;
use file::*;

mod terminal;
use terminal::*;

mod state;
use state::*;

fn get_file_size(term: &Terminal, state: &EditorState) -> (i32, i32) {
    let (screen_w, screen_h) = term.get_size();
    let one_liner_offset = match state.one_liner_active() {
        true => 1,
        false => 0
    };
    (screen_w - state.lineno_chars() - 1, screen_h - one_liner_offset - 3)
}

fn render_file(out: &mut Terminal, state: &EditorState) {
    let file_size = get_file_size(out, state);
    let mut x = 1;
    let mut y = 1;

    let file = &state.file;

    for (line_number_maybe, line) in file.wrapped_lines(file_size) {
        if let Some(line_number) = line_number_maybe {
            out.goto((x, y));
            out.set_color_fg(Color::Grey);
            write!(out, "{:1$}",
                   line_number + 1, file.lineno_chars() as usize).unwrap();
            out.set_color_fg(Color::Reset);
        }
        x += file.lineno_chars() + 1;
        out.goto((x, y));
        write!(out, "{}", line).unwrap();
        x = 1;
        y += 1;
    }
}

fn render_footer(out: &mut Terminal, state: &EditorState) {
    let (screen_width, screen_height) = out.get_size();

    let mut x = 1;
    let mut y = screen_height - 1;
    for (key, action) in state.keys.entries() {
        out.goto((x, y));
        out.set_color_fg(Color::Black);
        out.set_color_bg(Color::White);
        write!(out, "{}", key).unwrap();
        out.set_color_fg(Color::Reset);
        out.set_color_bg(Color::Reset);
        write!(out, " {}", action).unwrap();
        x += 16;
        if x > screen_width {
            x = 1;
            y -= 1;
        }
    }
}

fn render_status(out: &mut Terminal, state: &EditorState) {
    let (_, height) = out.get_size();
    let file_size = get_file_size(out, state);
    let x = 1;
    let y = height;
    out.goto((x, y));
    write!(out, "{}", state.file.debug(file_size)).unwrap();
}

fn render_one_liner(out: &mut Terminal, state: &EditorState) {
    if let Some(ref ols) = state.one_liner {
        let (_, screen_height) = out.get_size();
        let y = screen_height - 3;

        out.goto((1, y));
        out.set_color_fg(Color::Black);
        out.set_color_bg(Color::White);
        write!(out, "{} ", ols.label).unwrap();
        out.set_color_fg(Color::Reset);
        out.set_color_bg(Color::Reset);
        write!(out, "{}", ols.value()).unwrap();
    }
}

fn main() {
    let mut term = Terminal::default();
    term.clear();
    term.flush().unwrap();
    let args: Vec<String> = env::args().collect();
    let filename = args.get(1).cloned().unwrap_or(String::from("README.md"));
    let mut state = EditorState {
        keys: KeybindTable::default(),
        file: File::open(&filename),
        one_liner: None,
    };
    render_footer(&mut term, &state);
    render_file(&mut term, &state);
    render_status(&mut term, &state);
    let file_size = get_file_size(&term, &state);
    term.goto(state.cursor(file_size));
    term.flush().unwrap();
    let mut file_lines = state.lines_len();
    let mut file_wrapped_lines = state.wrapped_lines(file_size).len();
    let mut file_dirty = false;
    let mut screen_dirty = false;
    for evt in term.keys() {
        let file_size = get_file_size(&term, &state);
        match evt {
            Event::Mouse(_) => (),
            Event::Unsupported(_) => (),
            Event::Key(Key::Null) => (),
            Event::Key(Key::Insert) => (),
            Event::Key(Key::F(_)) => (),
            Event::Key(Key::Esc) => (),
            Event::Key(k @ Key::Ctrl(_)) | Event::Key(k @ Key::Alt(_)) => {
                match state.keys.lookup(k) {
                    Some(Command::Quit) => break,
                    Some(Command::Refresh) => {
                        state.refresh(file_size);
                        screen_dirty = true;
                    },
                    Some(Command::SaveFile) => {
                        let mut ols = OneLinerState::from(Command::SaveFile);
                        ols.file.lines[0] = state.file.name.clone();
                        state.one_liner = Some(ols);
                        screen_dirty = true;
                    },
                    None => (),
                    _ => ()
                }
            },
            Event::Key(Key::Left) => {
                screen_dirty = state.move_cursor_left(file_size);
            },
            Event::Key(Key::Right) => {
                screen_dirty = state.move_cursor_right(file_size);
            },
            Event::Key(Key::Up) => {
                screen_dirty = state.move_cursor_up(file_size);
            },
            Event::Key(Key::Down) => {
                screen_dirty = state.move_cursor_down(file_size);
            },
            Event::Key(Key::Home) => state.move_cursor_home(file_size),
            Event::Key(Key::End) => state.move_cursor_end(file_size),
            Event::Key(Key::PageUp) => {
                state.page_up(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::PageDown) => {
                state.page_down(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::Char('\t')) => {
                for _ in 0..4 {
                    state.insert(file_size, ' ');
                }
                file_dirty = true;
            },
            Event::Key(Key::Char('\n')) => {
                let mut reset_one_liner = false;
                if let Some(ref ols) = state.one_liner {
                    match ols.command {
                        Command::SaveFile => {
                            state.save_file(ols.value());
                            reset_one_liner = true;
                        },
                        _ => ()
                    }
                } else {
                    state.insert_newline(file_size);
                    screen_dirty = true;
                }
                if reset_one_liner {
                    state.one_liner = None;
                    screen_dirty = true;
                }
            },
            Event::Key(Key::Delete) => {
                state.delete(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::Backspace) => {
                state.backspace(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::Char(c)) => {
                state.insert(file_size, c);
                file_dirty = true;
            },
        }
        let file_size = get_file_size(&term, &state);
        if screen_dirty {
            file_dirty = true;
        }
        if file_dirty {
            let new_file_lines = state.lines_len();
            let new_file_wrapped_lines = state.wrapped_lines(file_size).len();
            if new_file_lines != file_lines {
                screen_dirty = true;
                file_lines = new_file_lines;
            }
            if new_file_wrapped_lines != file_wrapped_lines {
                screen_dirty = true;
                file_wrapped_lines = new_file_wrapped_lines;
            }
        }
        if screen_dirty {
            term.clear();
            render_footer(&mut term, &state);
            screen_dirty = false;
        }
        if file_dirty {
            render_file(&mut term, &state);
            render_one_liner(&mut term, &state);
            file_dirty = false;
        }
        render_status(&mut term, &state);
        term.goto(state.cursor(file_size));
        term.flush().unwrap();
    }
}
<commit_msg>Jump to end of one liner when saving<commit_after>#[macro_use] extern crate macro_attr;
#[macro_use] extern crate enum_derive;

use std::io::Write;
use std::env;

mod keybinds;
use keybinds::*;

mod file;
use file::*;

mod terminal;
use terminal::*;

mod state;
use state::*;

fn get_file_size(term: &Terminal, state: &EditorState) -> (i32, i32) {
    let (screen_w, screen_h) = term.get_size();
    let one_liner_offset = match state.one_liner_active() {
        true => 1,
        false => 0
    };
    (screen_w - state.lineno_chars() - 1, screen_h - one_liner_offset - 3)
}

fn render_file(out: &mut Terminal, state: &EditorState) {
    let file_size = get_file_size(out, state);
    let mut x = 1;
    let mut y = 1;

    let file = &state.file;

    for (line_number_maybe, line) in file.wrapped_lines(file_size) {
        if let Some(line_number) = line_number_maybe {
            out.goto((x, y));
            out.set_color_fg(Color::Grey);
            write!(out, "{:1$}",
                   line_number + 1, file.lineno_chars() as usize).unwrap();
            out.set_color_fg(Color::Reset);
        }
        x += file.lineno_chars() + 1;
        out.goto((x, y));
        write!(out, "{}", line).unwrap();
        x = 1;
        y += 1;
    }
}

fn render_footer(out: &mut Terminal, state: &EditorState) {
    let (screen_width, screen_height) = out.get_size();

    let mut x = 1;
    let mut y = screen_height - 1;
    for (key, action) in state.keys.entries() {
        out.goto((x, y));
        out.set_color_fg(Color::Black);
        out.set_color_bg(Color::White);
        write!(out, "{}", key).unwrap();
        out.set_color_fg(Color::Reset);
        out.set_color_bg(Color::Reset);
        write!(out, " {}", action).unwrap();
        x += 16;
        if x > screen_width {
            x = 1;
            y -= 1;
        }
    }
}

fn render_status(out: &mut Terminal, state: &EditorState) {
    let (_, height) = out.get_size();
    let file_size = get_file_size(out, state);
    let x = 1;
    let y = height;
    out.goto((x, y));
    write!(out, "{}", state.file.debug(file_size)).unwrap();
}

fn render_one_liner(out: &mut Terminal, state: &EditorState) {
    if let Some(ref ols) = state.one_liner {
        let (_, screen_height) = out.get_size();
        let y = screen_height - 3;

        out.goto((1, y));
        out.set_color_fg(Color::Black);
        out.set_color_bg(Color::White);
        write!(out, "{} ", ols.label).unwrap();
        out.set_color_fg(Color::Reset);
        out.set_color_bg(Color::Reset);
        write!(out, "{}", ols.value()).unwrap();
    }
}

fn main() {
    let mut term = Terminal::default();
    term.clear();
    term.flush().unwrap();
    let args: Vec<String> = env::args().collect();
    let filename = args.get(1).cloned().unwrap_or(String::from("README.md"));
    let mut state = EditorState {
        keys: KeybindTable::default(),
        file: File::open(&filename),
        one_liner: None,
    };
    render_footer(&mut term, &state);
    render_file(&mut term, &state);
    render_status(&mut term, &state);
    let file_size = get_file_size(&term, &state);
    term.goto(state.cursor(file_size));
    term.flush().unwrap();
    let mut file_lines = state.lines_len();
    let mut file_wrapped_lines = state.wrapped_lines(file_size).len();
    let mut file_dirty = false;
    let mut screen_dirty = false;
    for evt in term.keys() {
        let file_size = get_file_size(&term, &state);
        match evt {
            Event::Mouse(_) => (),
            Event::Unsupported(_) => (),
            Event::Key(Key::Null) => (),
            Event::Key(Key::Insert) => (),
            Event::Key(Key::F(_)) => (),
            Event::Key(Key::Esc) => (),
            Event::Key(k @ Key::Ctrl(_)) | Event::Key(k @ Key::Alt(_)) => {
                match state.keys.lookup(k) {
                    Some(Command::Quit) => break,
                    Some(Command::Refresh) => {
                        state.refresh(file_size);
                        screen_dirty = true;
                    },
                    Some(Command::SaveFile) => {
                        let mut ols = OneLinerState::from(Command::SaveFile);
                        ols.file.lines[0] = state.file.name.clone();
                        ols.file.move_cursor_end(file_size);
                        state.one_liner = Some(ols);
                        screen_dirty = true;
                    },
                    None => (),
                    _ => ()
                }
            },
            Event::Key(Key::Left) => {
                screen_dirty = state.move_cursor_left(file_size);
            },
            Event::Key(Key::Right) => {
                screen_dirty = state.move_cursor_right(file_size);
            },
            Event::Key(Key::Up) => {
                screen_dirty = state.move_cursor_up(file_size);
            },
            Event::Key(Key::Down) => {
                screen_dirty = state.move_cursor_down(file_size);
            },
            Event::Key(Key::Home) => state.move_cursor_home(file_size),
            Event::Key(Key::End) => state.move_cursor_end(file_size),
            Event::Key(Key::PageUp) => {
                state.page_up(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::PageDown) => {
                state.page_down(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::Char('\t')) => {
                for _ in 0..4 {
                    state.insert(file_size, ' ');
                }
                file_dirty = true;
            },
            Event::Key(Key::Char('\n')) => {
                let mut reset_one_liner = false;
                if let Some(ref ols) = state.one_liner {
                    match ols.command {
                        Command::SaveFile => {
                            state.save_file(ols.value());
                            reset_one_liner = true;
                        },
                        _ => ()
                    }
                } else {
                    state.insert_newline(file_size);
                    screen_dirty = true;
                }
                if reset_one_liner {
                    state.one_liner = None;
                    screen_dirty = true;
                }
            },
            Event::Key(Key::Delete) => {
                state.delete(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::Backspace) => {
                state.backspace(file_size);
                screen_dirty = true;
            },
            Event::Key(Key::Char(c)) => {
                state.insert(file_size, c);
                file_dirty = true;
            },
        }
        let file_size = get_file_size(&term, &state);
        if screen_dirty {
            file_dirty = true;
        }
        if file_dirty {
            let new_file_lines = state.lines_len();
            let new_file_wrapped_lines = state.wrapped_lines(file_size).len();
            if new_file_lines != file_lines {
                screen_dirty = true;
                file_lines = new_file_lines;
            }
            if new_file_wrapped_lines != file_wrapped_lines {
                screen_dirty = true;
                file_wrapped_lines = new_file_wrapped_lines;
            }
        }
        if screen_dirty {
            term.clear();
            render_footer(&mut term, &state);
            screen_dirty = false;
        }
        if file_dirty {
            render_file(&mut term, &state);
            render_one_liner(&mut term, &state);
            file_dirty = false;
        }
        render_status(&mut term, &state);
        term.goto(state.cursor(file_size));
        term.flush().unwrap();
    }
}
<|endoftext|>


<commit_before>extern crate rsdocs2docset;
extern crate html5ever;
#[macro_use]
extern crate quick_error;
extern crate clap;
extern crate url;
extern crate sqlite;

use clap::{Arg, App};
use html5ever::driver::{ParseOpts, parse_document};
use html5ever::rcdom::RcDom;
use html5ever::serialize::{SerializeOpts, serialize};
use html5ever::tendril::TendrilSink;

use std::ffi::OsStr;
use std::fs::{self, DirBuilder, DirEntry, File};
use std::io::{self,Write};
use std::path::Path;

use rsdocs2docset::dom::{manipulator, parser};

type Result = std::result::Result<(), RsDoc2DocsetError>;

quick_error! {
    #[derive(Debug)]
    pub enum RsDoc2DocsetError {
        Io(err: std::io::Error) {
            from()
                cause(err)
                description(err.description())
        }
        Utf8(err: std::string::FromUtf8Error) {
            from()
                cause(err)
                description(err.description())
        }
        Sqlite(err: sqlite::Error) {
            from()
                cause(err)
                description(err.description())
        }
    }
}

fn main() {
    let args = App::new("RsDoc2Docset")
        .version(include_str!("../VERSION"))
        .about("A tool that converts rust docs to Dash docset files")
        .arg(Arg::with_name("indir")
             .short("i")
             .long("rsdoc")
             .value_name("INDIR")
             .help("directory that contains rustdoc files")
             .required(true)
             .takes_value(true))
        .arg(Arg::with_name("name")
             .short("n")
             .long("name")
             .value_name("NAME")
             .help("name of the docset")
             .required(true)
             .takes_value(true))
        .get_matches();

    create_docset(args.value_of("indir").unwrap(), args.value_of("name").unwrap()).expect("error creating docset");
    println!("\n{}.docset successfully created!", args.value_of("name").unwrap())
}

fn create_docset(indir: &str, name: &str) -> Result {
    let db_filename = format!("{}.docset/Contents/Resources/docSet.dsidx", name);
    let db_path = Path::new(&db_filename);

    try!(write_file(Path::new(format!("{}.docset/Contents/Info.plist", name).as_str()), format!(include_str!("Info.plist.tmpl"), name = name, identifier = name.replace(" ", "-").to_lowercase()).as_ref()));
    try!(write_file(Path::new(format!("{}.docset/icon.png", name).as_str()), include_bytes!("icon.png")));
    try!(write_file(Path::new(format!("{}.docset/icon@2x.png", name).as_str()), include_bytes!("icon@2x.png")));

    try!(touch(db_path));
    try!(sqlite::open(db_path).and_then(|c| c.execute("CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT);")));

    try!(docset_from_rs_doc_tree(&Path::new(indir), format!("{}.docset/Contents/Resources/Documents/", name).as_str(), Path::new(db_path)));

    Ok(())
}

fn touch(path: &Path) -> Result {
    write_file(path, "".as_bytes())
}

fn write_file(path: &Path, data: &[u8]) -> Result {
    let dir = path.parent().unwrap();

    try!(DirBuilder::new()
         .recursive(true)
         .create(dir));

    try!(File::create(path).and_then(|mut f| f.write_all(data)));
    Ok(())
}

fn docset_from_rs_doc_tree(source_dir: &Path, out_dir: &str, db_path: &Path) -> Result {
        if !source_dir.exists() {
            return Err(io::Error::new(io::ErrorKind::NotFound, format!("{} does not exist", source_dir.to_str().unwrap())).into());
        }

        if source_dir.is_dir() {
            for entry in fs::read_dir(source_dir)? {
                let entry = entry?;
                if entry.path().is_dir() {
                    try!(docset_from_rs_doc_tree(&entry.path(), &out_dir, &db_path));
                } else {
                    try!(annotate_file(&entry, &out_dir, &db_path));
                }
            }
        }
        Ok(())
    }

fn annotate_file(in_file: &DirEntry, output_prefix: &str, db_path: &Path) -> Result {
    let out_file = Path::new(output_prefix).join(in_file.path());

    if in_file.path().extension() != Some(OsStr::new("html")) {
        try!(touch(&out_file));
        try!(fs::copy(in_file.path(), &out_file));
        //println!("{:70} | ", in_file.path().display());
        print!("."); io::stdout().flush().unwrap();
    } else {
        let mut dom = parse_document(RcDom::default(), ParseOpts::default())
            .from_utf8()
            .read_from( &mut File::open(&in_file.path())? )?;

        let entries = parser::find_entry_elements(&mut dom);
        for entry in entries.iter().filter_map(|x| x.as_ref()) {
            //println!("{:70} | {}", in_file.path().display(), entry);

            let sql_cmd = format!("INSERT OR IGNORE INTO searchIndex(name, type, path) VALUES (\"{}\", \"{}\", \"{}#{}\");", entry.entry_name, entry.entry_type, in_file.path().to_str().unwrap(), entry.anchor_name);
            try!(sqlite::open(db_path).and_then(|c| c.execute(&sql_cmd)))
        }
        manipulator::add_dash_links(&mut dom, &entries);

        let mut bytes = vec![];
        try!(serialize(&mut bytes, &dom.document, SerializeOpts::default()));
        try!(touch(&out_file));

        print!("o"); io::stdout().flush().unwrap();
    }

    Ok(())
}
<commit_msg>Replace touch with mkdir_p<commit_after>extern crate rsdocs2docset;
extern crate html5ever;
#[macro_use]
extern crate quick_error;
extern crate clap;
extern crate url;
extern crate sqlite;

use clap::{Arg, App};
use html5ever::driver::{ParseOpts, parse_document};
use html5ever::rcdom::RcDom;
use html5ever::serialize::{SerializeOpts, serialize};
use html5ever::tendril::TendrilSink;

use std::ffi::OsStr;
use std::fs::{self, DirBuilder, DirEntry, File};
use std::io::{self,Write};
use std::path::Path;

use rsdocs2docset::dom::{manipulator, parser};

type Result = std::result::Result<(), RsDoc2DocsetError>;

quick_error! {
    #[derive(Debug)]
    pub enum RsDoc2DocsetError {
        Io(err: std::io::Error) {
            from()
                cause(err)
                description(err.description())
        }
        Utf8(err: std::string::FromUtf8Error) {
            from()
                cause(err)
                description(err.description())
        }
        Sqlite(err: sqlite::Error) {
            from()
                cause(err)
                description(err.description())
        }
    }
}

fn main() {
    let args = App::new("RsDoc2Docset")
        .version(include_str!("../VERSION"))
        .about("A tool that converts rust docs to Dash docset files")
        .arg(Arg::with_name("indir")
             .short("i")
             .long("rsdoc")
             .value_name("INDIR")
             .help("directory that contains rustdoc files")
             .required(true)
             .takes_value(true))
        .arg(Arg::with_name("name")
             .short("n")
             .long("name")
             .value_name("NAME")
             .help("name of the docset")
             .required(true)
             .takes_value(true))
        .get_matches();

    create_docset(args.value_of("indir").unwrap(), args.value_of("name").unwrap()).expect("error creating docset");
    println!("\n{}.docset successfully created!", args.value_of("name").unwrap())
}

fn create_docset(indir: &str, name: &str) -> Result {
    let db_filename = format!("{}.docset/Contents/Resources/docSet.dsidx", name);
    let db_path = Path::new(&db_filename);

    try!(write_file(Path::new(format!("{}.docset/Contents/Info.plist", name).as_str()), format!(include_str!("Info.plist.tmpl"), name = name, identifier = name.replace(" ", "-").to_lowercase()).as_ref()));
    try!(write_file(Path::new(format!("{}.docset/icon.png", name).as_str()), include_bytes!("icon.png")));
    try!(write_file(Path::new(format!("{}.docset/icon@2x.png", name).as_str()), include_bytes!("icon@2x.png")));

    try!(mkdir_p(db_path));
    try!(sqlite::open(db_path).and_then(|c| c.execute("CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT);")));

    try!(docset_from_rs_doc_tree(&Path::new(indir), format!("{}.docset/Contents/Resources/Documents/", name).as_str(), Path::new(db_path)));

    Ok(())
}

fn mkdir_p(path: &Path) -> Result {
    let dir = path.parent().unwrap();

    try!(DirBuilder::new()
         .recursive(true)
         .create(dir));
    Ok(())
}

fn write_file(path: &Path, data: &[u8]) -> Result {
    try!(mkdir_p(path));
    try!(File::create(path).and_then(|mut f| f.write_all(data)));
    Ok(())
}

fn docset_from_rs_doc_tree(source_dir: &Path, out_dir: &str, db_path: &Path) -> Result {
        if !source_dir.exists() {
            return Err(io::Error::new(io::ErrorKind::NotFound, format!("{} does not exist", source_dir.to_str().unwrap())).into());
        }

        if source_dir.is_dir() {
            for entry in fs::read_dir(source_dir)? {
                let entry = entry?;
                if entry.path().is_dir() {
                    try!(docset_from_rs_doc_tree(&entry.path(), &out_dir, &db_path));
                } else {
                    try!(annotate_file(&entry, &out_dir, &db_path));
                }
            }
        }
        Ok(())
    }

fn annotate_file(in_file: &DirEntry, output_prefix: &str, db_path: &Path) -> Result {
    let out_file = Path::new(output_prefix).join(in_file.path());

    if in_file.path().extension() != Some(OsStr::new("html")) {
        try!(mkdir_p(&out_file));
        try!(fs::copy(in_file.path(), &out_file));
        //println!("{:70} | ", in_file.path().display());
        print!("."); io::stdout().flush().unwrap();
    } else {
        let mut dom = parse_document(RcDom::default(), ParseOpts::default())
            .from_utf8()
            .read_from( &mut File::open(&in_file.path())? )?;

        let entries = parser::find_entry_elements(&mut dom);
        for entry in entries.iter().filter_map(|x| x.as_ref()) {
            //println!("{:70} | {}", in_file.path().display(), entry);

            let sql_cmd = format!("INSERT OR IGNORE INTO searchIndex(name, type, path) VALUES (\"{}\", \"{}\", \"{}#{}\");", entry.entry_name, entry.entry_type, in_file.path().to_str().unwrap(), entry.anchor_name);
            try!(sqlite::open(db_path).and_then(|c| c.execute(&sql_cmd)))
        }
        manipulator::add_dash_links(&mut dom, &entries);

        let mut bytes = vec![];
        try!(serialize(&mut bytes, &dom.document, SerializeOpts::default()));
        try!(mkdir_p(&out_file));

        print!("o"); io::stdout().flush().unwrap();
    }

    Ok(())
}
<|endoftext|>


<commit_before>//! Main module of way-cooler

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;

#[cfg(not(test))]
extern crate rustwlc;

extern crate getopts;

#[cfg(test)]
extern crate dummy_rustwlc as rustwlc;

#[macro_use]
extern crate log;
extern crate env_logger;

#[macro_use]
extern crate hlua;
extern crate rustc_serialize;
#[macro_use]
extern crate json_macro;

extern crate nix;

extern crate petgraph;

extern crate uuid;

#[macro_use]
extern crate wayland_client;

extern crate tempfile;

extern crate byteorder;

use std::env;
use getopts::Options;
use log::LogLevel;

use nix::sys::signal::{SigHandler, SigSet, SigAction, SaFlags};
use nix::sys::signal;

use rustwlc::types::LogType;

#[macro_use] // As it happens, it's important to declare the macros first.
mod macros;
mod convert;

mod callbacks;
mod keys;

mod lua;
mod registry;
mod commands;
mod ipc;

mod layout;
mod background;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

/// Callback to route wlc logs into env_logger
fn log_handler(level: LogType, message: &str) {
    match level {
        LogType::Info => info!("wlc: {}", message),
        LogType::Warn => warn!("wlc: {}", message),
        LogType::Error => error!("wlc: {}", message),
        LogType::Wayland => info!("wayland: {}", message)
    }
}

/// Formats the log strings properly
fn log_format(record: &log::LogRecord) -> String {
    let color = match record.level() {
        LogLevel::Info => "",
        LogLevel::Trace => "\x1B[37m",
        LogLevel::Debug => "\x1B[37m",
        LogLevel::Warn =>  "\x1B[33m",
        LogLevel::Error => "\x1B[31m",
    };
    let location = record.location();
    let file = location.file();
    let line = location.line();
    let mut module_path = location.module_path();
    if let Some(index) = module_path.find("way_cooler::") {
        let index = index + "way_cooler::".len();
        module_path = &module_path[index..];
    }
    format!("{} {} [{}] \x1B[37m{}:{}\x1B[0m{0} {} \x1B[0m",
            color, record.level(), module_path, file, line, record.args())
}

/// Initializes the logging system.
/// Can be called from within test methods.
pub fn init_logs() {
    // Prepare log builder
    let mut builder = env_logger::LogBuilder::new();
    builder.format(log_format);
    builder.filter(None, log::LogLevelFilter::Trace);
    if env::var("WAY_COOLER_LOG").is_ok() {
        builder.parse(&env::var("WAY_COOLER_LOG").expect("Asserted unwrap!"));
    }
    builder.init().expect("Unable to initialize logging!");
    info!("Logger initialized, setting wlc handlers.");
}

/// Handler for signals, should close the ipc
extern "C" fn sig_handle(_: nix::libc::c_int) {
    rustwlc::terminate();
}

fn main() {
    let args: Vec<String> = env::args().collect();

    let mut opts = Options::new();
    opts.optflag("", "version", "show version information");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("{}", f.to_string());
            std::process::exit(1);
        }
    };
    if matches.opt_present("version") {
        println!("Way Cooler {}", VERSION);
        println!("Way Cooler IPC version {}", ipc::VERSION);
        return
    }
    println!("Launching way-cooler...");

    let sig_action = SigAction::new(SigHandler::Handler(sig_handle), SaFlags::empty(), SigSet::empty());
    unsafe {signal::sigaction(signal::SIGINT, &sig_action).unwrap() };

    // Start logging first
    init_logs();

    // Initialize callbacks
    callbacks::init();

    // Handle wlc logs
    rustwlc::log_set_rust_handler(log_handler);

    // Prepare to launch wlc
    let run_wlc = rustwlc::init2().expect("Unable to initialize wlc!");

    // (Future config initialization goes here)
    // Initialize commands
    commands::init();
    // Add API to registry
    registry::init();
    // Register Alt+Esc keybinding
    keys::init();
    // Start listening for clients
    let _ipc = ipc::init();

    // Hand control over to wlc's event loop
    info!("Running wlc...");
    run_wlc();
}
<commit_msg>Added proprietary driver detection, Fixes #119<commit_after>//! Main module of way-cooler

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;

#[cfg(not(test))]
extern crate rustwlc;

extern crate getopts;

#[cfg(test)]
extern crate dummy_rustwlc as rustwlc;

#[macro_use]
extern crate log;
extern crate env_logger;

#[macro_use]
extern crate hlua;
extern crate rustc_serialize;
#[macro_use]
extern crate json_macro;

extern crate nix;

extern crate petgraph;

extern crate uuid;

#[macro_use]
extern crate wayland_client;

extern crate tempfile;

extern crate byteorder;

use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use getopts::Options;
use log::LogLevel;

use nix::sys::signal::{SigHandler, SigSet, SigAction, SaFlags};
use nix::sys::signal;

use rustwlc::types::LogType;

#[macro_use] // As it happens, it's important to declare the macros first.
mod macros;
mod convert;

mod callbacks;
mod keys;

mod lua;
mod registry;
mod commands;
mod ipc;

mod layout;
mod background;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const MODULE_PATH: &'static str = "/proc/modules";

/// Callback to route wlc logs into env_logger
fn log_handler(level: LogType, message: &str) {
    match level {
        LogType::Info => info!("wlc: {}", message),
        LogType::Warn => warn!("wlc: {}", message),
        LogType::Error => error!("wlc: {}", message),
        LogType::Wayland => info!("wayland: {}", message)
    }
}

/// Formats the log strings properly
fn log_format(record: &log::LogRecord) -> String {
    let color = match record.level() {
        LogLevel::Info => "",
        LogLevel::Trace => "\x1B[37m",
        LogLevel::Debug => "\x1B[37m",
        LogLevel::Warn =>  "\x1B[33m",
        LogLevel::Error => "\x1B[31m",
    };
    let location = record.location();
    let file = location.file();
    let line = location.line();
    let mut module_path = location.module_path();
    if let Some(index) = module_path.find("way_cooler::") {
        let index = index + "way_cooler::".len();
        module_path = &module_path[index..];
    }
    format!("{} {} [{}] \x1B[37m{}:{}\x1B[0m{0} {} \x1B[0m",
            color, record.level(), module_path, file, line, record.args())
}

/// Checks the loaded modules, and reports any problematic proprietary ones
fn detect_proprietary() {
    if env::var("DISPLAY").is_ok() {
        // If DISPLAY is present, we are running embedded
        return
    }
    match File::open(Path::new(MODULE_PATH)) {
        Ok(file) => {
            let reader = BufReader::new(&file);
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("nvidia") {
                        error!("Warning: Proprietary nvidia drivers do NOT support Wayland. Use nouveau.");
                        break;
                    } else if line.contains("fglrx") {
                        error!("Warning: Proprietary AMD drivers do NOT support Wayland. Use radeon.");
                        break;
                    }
                }
            }
        },
        Err(err) => {
            warn!("Could not read proprietary modules at \"{}\", because: {:#?}",
                  MODULE_PATH, err);
        }
    }
}

/// Initializes the logging system.
/// Can be called from within test methods.
pub fn init_logs() {
    // Prepare log builder
    let mut builder = env_logger::LogBuilder::new();
    builder.format(log_format);
    builder.filter(None, log::LogLevelFilter::Trace);
    if env::var("WAY_COOLER_LOG").is_ok() {
        builder.parse(&env::var("WAY_COOLER_LOG").expect("Asserted unwrap!"));
    }
    builder.init().expect("Unable to initialize logging!");
    info!("Logger initialized, setting wlc handlers.");
}

/// Handler for signals, should close the ipc
extern "C" fn sig_handle(_: nix::libc::c_int) {
    rustwlc::terminate();
}

fn main() {
    let args: Vec<String> = env::args().collect();

    let mut opts = Options::new();
    opts.optflag("", "version", "show version information");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("{}", f.to_string());
            std::process::exit(1);
        }
    };
    if matches.opt_present("version") {
        println!("Way Cooler {}", VERSION);
        println!("Way Cooler IPC version {}", ipc::VERSION);
        return
    }
    println!("Launching way-cooler...");

    let sig_action = SigAction::new(SigHandler::Handler(sig_handle), SaFlags::empty(), SigSet::empty());
    unsafe {signal::sigaction(signal::SIGINT, &sig_action).unwrap() };

    // Start logging first
    init_logs();
    // Detect proprietary modules loaded, and warn about them.
    detect_proprietary();

    // Initialize callbacks
    callbacks::init();

    // Handle wlc logs
    rustwlc::log_set_rust_handler(log_handler);

    // Prepare to launch wlc
    let run_wlc = rustwlc::init2().expect("Unable to initialize wlc!");

    // (Future config initialization goes here)
    // Initialize commands
    commands::init();
    // Add API to registry
    registry::init();
    // Register Alt+Esc keybinding
    keys::init();
    // Start listening for clients
    let _ipc = ipc::init();

    // Hand control over to wlc's event loop
    info!("Running wlc...");
    run_wlc();
}
<|endoftext|>


<commit_before>use std::rc::Rc;

type Error = &'static str;

#[derive(Debug,Clone)]
enum Code {
    Integer(i64),
    Rational(i64, i64),
    String(String),
    Add(Rc<Code>, Rc<Code>),
    Sub(Rc<Code>, Rc<Code>),
    Div(Rc<Code>, Rc<Code>),
    Mul(Rc<Code>, Rc<Code>),
    Neg(Rc<Code>),
}

// Calculate the greatest common divisor using Euclid's algorithm.
fn gcd(mut a: i64, mut b: i64) -> i64 {
    let mut c;
    while a != 0 {
        c = a;
        a = b % a;
        b = c;
    }
    b
}

// This normalizes inputs and sometimes even converts to integers.
fn new_rational(mut n: i64, mut d: i64) -> Code {
    let g = gcd(n, d);
    n = n / g;
    d = d / g;
    if d < 0 {
      n = -n;
      d = -d;
    }
    if d == 1 {
        Code::Integer(n)
    }
    else {
        Code::Rational(n, d)
    }
}

fn rational_add(n1: i64, d1: i64, n2: i64, d2: i64) -> Code {
  if d1 == d2 {
    // Fast path for common divisors.
    new_rational(n1 + n2, d1)
  }
  else {
    let g = gcd(d1, d2);
    new_rational(n1 * (d2 / g) + n2 * (d1 / g), d1 / g * d2)
  }

}

fn add(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Integer(a + b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(rational_add(n, d, b, 1)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(rational_add(a, 1, n, d)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(rational_add(n1, d1, n2, d2)),
        _ => Err("Add requires two numbers"),
    }
}

fn subtract(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Integer(a - b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(rational_add(n, d, -b, 1)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(rational_add(a, 1, -n, d)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(rational_add(n1, d1, -n2, d2)),
        _ => Err("Subtract requires two numbers"),
    }
}

fn multiply(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Integer(a * b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(new_rational(n * b, d)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(new_rational(a * n, d)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(new_rational(n1 * n2, d1 * d2)),
        _ => Err("Multiply requires two numbers"),
    }
}

fn divide(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Rational(a, b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(new_rational(n, d * b)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(new_rational(a * d, n)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(new_rational(n1 * d2, d1 * n2)),
        _ => Err("Divide requires two numbers"),
    }
}

fn negate(num: &Code) -> Result<Code, Error> {
    match num {
        &Code::Integer(a) => Ok(Code::Integer(-a)),
        &Code::Rational(n, d) => Ok(Code::Rational(-n, d)),
        _ => Err("Negate requires a number"),
    }
}

fn eval(expr: &Code) -> Result<Code, Error> {
    match expr {
        &Code::Add(ref left, ref right) => add(left, right),
        &Code::Sub(ref left, ref right) => subtract(left, right),
        &Code::Mul(ref left, ref right) => multiply(left, right),
        &Code::Div(ref left, ref right) => divide(left, right),
        &Code::Neg(ref num) => negate(num),
        n @ &Code::Integer(_) => Ok(n.clone()),
        n @ &Code::Rational(_, _) => Ok(n.clone()),
        n @ &Code::String(_) => Ok(n.clone()),
    }
}

fn test(left: Code, right: Code) {
    let a = Rc::new(left);
    let b = Rc::new(right);
    let mut e = Rc::new(Code::Add(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Sub(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Mul(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Div(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Neg(a.clone()));
    println!("{:?} = {:?}", e, eval(&e));
}

fn main() {
    test(Code::Integer(44), Code::Integer(14));
    test(Code::Integer(14), Code::Integer(44));
    test(Code::Integer(44), Code::Integer(-14));
    test(Code::Integer(14), Code::Integer(-44));
    test(Code::Integer(-44), Code::Integer(14));
    test(Code::Integer(-14), Code::Integer(44));
    test(Code::Integer(-44), Code::Integer(-14));
    test(Code::Integer(-14), Code::Integer(-44));
    test(new_rational(1, 2), new_rational(2, 1));
    test(new_rational(2, 1), new_rational(1, 2));
    test(new_rational(1, 2), new_rational(1, 2));
    test(new_rational(2, 2), new_rational(2, 1));
    test(Code::String(str::to_string("Input string")),
         new_rational(2, 1));
    let e = Code::Div(
        Rc::new(Code::Add(
            Rc::new(Code::Rational(1, 2)),
            Rc::new(Code::Rational(1, 3)),
        )),
        Rc::new(Code::Sub(
            Rc::new(Code::Integer(2)),
            Rc::new(Code::Integer(5)),
        )),
    );
    println!("{:?} = {:?}", e, eval(&e));

}
<commit_msg>Simplify rational on int / int<commit_after>use std::rc::Rc;

type Error = &'static str;

#[derive(Debug,Clone)]
enum Code {
    Integer(i64),
    Rational(i64, i64),
    String(String),
    Add(Rc<Code>, Rc<Code>),
    Sub(Rc<Code>, Rc<Code>),
    Div(Rc<Code>, Rc<Code>),
    Mul(Rc<Code>, Rc<Code>),
    Neg(Rc<Code>),
}

// Calculate the greatest common divisor using Euclid's algorithm.
fn gcd(mut a: i64, mut b: i64) -> i64 {
    let mut c;
    while a != 0 {
        c = a;
        a = b % a;
        b = c;
    }
    b
}

// This normalizes inputs and sometimes even converts to integers.
fn new_rational(mut n: i64, mut d: i64) -> Code {
    let g = gcd(n, d);
    n = n / g;
    d = d / g;
    if d < 0 {
      n = -n;
      d = -d;
    }
    if d == 1 {
        Code::Integer(n)
    }
    else {
        Code::Rational(n, d)
    }
}

fn rational_add(n1: i64, d1: i64, n2: i64, d2: i64) -> Code {
  if d1 == d2 {
    // Fast path for common divisors.
    new_rational(n1 + n2, d1)
  }
  else {
    let g = gcd(d1, d2);
    new_rational(n1 * (d2 / g) + n2 * (d1 / g), d1 / g * d2)
  }

}

fn add(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Integer(a + b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(rational_add(n, d, b, 1)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(rational_add(a, 1, n, d)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(rational_add(n1, d1, n2, d2)),
        _ => Err("Add requires two numbers"),
    }
}

fn subtract(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Integer(a - b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(rational_add(n, d, -b, 1)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(rational_add(a, 1, -n, d)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(rational_add(n1, d1, -n2, d2)),
        _ => Err("Subtract requires two numbers"),
    }
}

fn multiply(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(Code::Integer(a * b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(new_rational(n * b, d)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(new_rational(a * n, d)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(new_rational(n1 * n2, d1 * d2)),
        _ => Err("Multiply requires two numbers"),
    }
}

fn divide(left: &Code, right: &Code) -> Result<Code, Error> {
    match (try!(eval(left)), try!(eval(right))) {
        (Code::Integer(a), Code::Integer(b)) => Ok(new_rational(a, b)),
        (Code::Rational(n, d), Code::Integer(b)) => Ok(new_rational(n, d * b)),
        (Code::Integer(a), Code::Rational(n, d)) => Ok(new_rational(a * d, n)),
        (Code::Rational(n1, d1), Code::Rational(n2, d2)) => Ok(new_rational(n1 * d2, d1 * n2)),
        _ => Err("Divide requires two numbers"),
    }
}

fn negate(num: &Code) -> Result<Code, Error> {
    match num {
        &Code::Integer(a) => Ok(Code::Integer(-a)),
        &Code::Rational(n, d) => Ok(Code::Rational(-n, d)),
        _ => Err("Negate requires a number"),
    }
}

fn eval(expr: &Code) -> Result<Code, Error> {
    match expr {
        &Code::Add(ref left, ref right) => add(left, right),
        &Code::Sub(ref left, ref right) => subtract(left, right),
        &Code::Mul(ref left, ref right) => multiply(left, right),
        &Code::Div(ref left, ref right) => divide(left, right),
        &Code::Neg(ref num) => negate(num),
        n @ &Code::Integer(_) => Ok(n.clone()),
        n @ &Code::Rational(_, _) => Ok(n.clone()),
        n @ &Code::String(_) => Ok(n.clone()),
    }
}

fn test(left: Code, right: Code) {
    let a = Rc::new(left);
    let b = Rc::new(right);
    let mut e = Rc::new(Code::Add(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Sub(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Mul(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Div(a.clone(), b.clone()));
    println!("{:?} = {:?}", e, eval(&e));
    e = Rc::new(Code::Neg(a.clone()));
    println!("{:?} = {:?}", e, eval(&e));
}

fn main() {
    test(Code::Integer(44), Code::Integer(14));
    test(Code::Integer(14), Code::Integer(44));
    test(Code::Integer(44), Code::Integer(-14));
    test(Code::Integer(14), Code::Integer(-44));
    test(Code::Integer(-44), Code::Integer(14));
    test(Code::Integer(-14), Code::Integer(44));
    test(Code::Integer(-44), Code::Integer(-14));
    test(Code::Integer(-14), Code::Integer(-44));
    test(new_rational(1, 2), new_rational(2, 1));
    test(new_rational(2, 1), new_rational(1, 2));
    test(new_rational(1, 2), new_rational(1, 2));
    test(new_rational(2, 2), new_rational(2, 1));
    test(Code::String(str::to_string("Input string")),
         new_rational(2, 1));
    let e = Code::Div(
        Rc::new(Code::Add(
            Rc::new(Code::Rational(1, 2)),
            Rc::new(Code::Rational(1, 3)),
        )),
        Rc::new(Code::Sub(
            Rc::new(Code::Integer(2)),
            Rc::new(Code::Integer(5)),
        )),
    );
    println!("{:?} = {:?}", e, eval(&e));

}
<|endoftext|>


<commit_before>extern crate rand;

use std::cmp::{Eq, PartialEq, Ordering, PartialOrd};
use std::iter::FromIterator;
use rand::distributions::{IndependentSample, Range};

fn schwefel(solution: &Vec<f64>) -> f64 {
    418.9829_f64 * solution.len() as f64
        + solution.iter().fold(0_f64, |sum, x| sum + x * x.abs().sqrt().sin())
}

struct Individual {
    solution: Vec<f64>,
    fitness: f64,
}

impl Individual {
    fn new() -> Individual {
        let n = 50;
        let mut rng = rand::thread_rng();
        let range = Range::new(-512.03_f64, 511.97);

        let solution = Vec::from_iter((0..n).map(|_| range.ind_sample(&mut rng)));
        let fitness = schwefel(&solution);

        Individual { solution: solution, fitness: fitness }
    }
}

impl Eq for Individual {}

impl Ord for Individual {
    /// This dangerously delegates to `partial_cmp`
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialEq<Individual> for Individual {
    /// This delegates to `eq` on `fitness: f64`
    fn eq(&self, other: &Individual) -> bool {
        self.fitness.eq(&other.fitness)
    }
}

impl PartialOrd for Individual {
    /// This delegates to `partial_cmp` on `fitness: f64`
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.fitness.partial_cmp(&other.fitness)
    }
}

fn main() {
    let pop_size = 128;

    // initialize population
    let population = Vec::from_iter((0..pop_size).map(|_| Individual::new()));

    let best = population.iter().min().unwrap();
    println!("The best solution was {:?}", best.solution);
    println!("Its fitness was {}", best.fitness);
}
<commit_msg>Panic for unimplemented handling of NaN fitness<commit_after>extern crate rand;

use std::cmp::{Eq, PartialEq, Ordering, PartialOrd};
use std::iter::FromIterator;
use rand::distributions::{IndependentSample, Range};

fn schwefel(solution: &Vec<f64>) -> f64 {
    418.9829_f64 * solution.len() as f64
        + solution.iter().fold(0_f64, |sum, x| sum + x * x.abs().sqrt().sin())
}

struct Individual {
    solution: Vec<f64>,
    fitness: f64,
}

impl Individual {
    fn new() -> Individual {
        let n = 50;
        let mut rng = rand::thread_rng();
        let range = Range::new(-512.03_f64, 511.97);

        let solution = Vec::from_iter((0..n).map(|_| range.ind_sample(&mut rng)));
        let fitness = schwefel(&solution);

        Individual { solution: solution, fitness: fitness }
    }
}

impl Eq for Individual {}

impl Ord for Individual {
    /// This dangerously delegates to `partial_cmp`
    fn cmp(&self, other: &Self) -> Ordering {
        if let Some(result) = self.fitness.partial_cmp(&other.fitness) {
            return result;
        }
        unimplemented!();
    }
}

impl PartialEq<Individual> for Individual {
    /// This doesn't use `fitness.eq()` because it needs to be
    /// consistent with `Eq`
    fn eq(&self, other: &Individual) -> bool {
        if let Some(result) = self.fitness.partial_cmp(&other.fitness) {
            return result == Ordering::Equal;
        }
        unimplemented!();
    }
}

impl PartialOrd for Individual {
    /// This delegates to `fitness.partial_cmp()`
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.fitness.partial_cmp(&other.fitness)
    }
}

fn main() {
    let pop_size = 128;

    // initialize population
    let population = Vec::from_iter((0..pop_size).map(|_| Individual::new()));

    let best = population.iter().min().unwrap();
    println!("The best solution was {:?}", best.solution);
    println!("Its fitness was {}", best.fitness);
}
<|endoftext|>


<commit_before>extern crate time;
extern crate termion;

use termion::{color,style,clear,cursor};
use termion::input::{MouseTerminal};
use termion::raw::IntoRawMode;
use std::io::{Write, stdout};

const FRAME_PER_SECOND: i64 = 120;

fn timestamp() -> i64 {
    let current_time = time::get_time();
    current_time.sec*1000 + i64::from( current_time.nsec / 1_000_000 )
}

struct MainLoop {
    initial_time:        i64,
    current_time:        i64,
    current_frame:       i64,
    last_rendered_frame: i64,
    game_objects:        Vec<GameObject>
}

impl MainLoop {
    fn init() -> MainLoop {
        MainLoop {
            initial_time:        timestamp(),
            current_time:        0,
            current_frame:       0,
            last_rendered_frame: 0,
            game_objects:        vec![]
        }
    }

    fn update( &mut self ) {
        self.current_time = timestamp() - self.initial_time;
        self.current_frame = self.current_time*FRAME_PER_SECOND / 1000;

        if self.current_frame > self.last_rendered_frame {
            self.game_objects[0].charge += 100.0;

            if self.game_objects[0].charge > self.game_objects[0].threshold {
                self.game_objects[0].charge = 0.0;
            }
        }
    }

    fn render( &mut self ) {
        if self.current_frame > self.last_rendered_frame {
            println!( "{clear}", clear = clear::All );
            println!( "{goto}", goto = cursor::Goto(1, 1) );

            //
            println!( "Current time: {t}", t = ( self.current_time as f64 ) / 1000.0 );
            println!( "Neuron charge: {charge}", charge = self.game_objects[0].charge );

            //
            println!( "{reset}", reset = color::Fg( color::Reset ) );

            //
            self.last_rendered_frame = self.current_frame;
        }
    }
}

enum Cell {
    Empty,
    Wall,
    Player,
}

fn get_symbol( cell: &Cell ) -> char {
    match *cell {
        Cell::Empty => '_',
        Cell::Wall =>  '#',
        Cell::Player => '@'
    }
}

fn initialize_field( ) -> Vec<Vec<Cell>>{
    //ToDo: parse from file

    let mut result_field: Vec< Vec<Cell> > = Vec::new();

    let mut row: Vec<Cell> = Vec::new();
    row.push(Cell::Empty);
    row.push(Cell::Wall);
    result_field.push(row);

    let mut row: Vec<Cell> = Vec::new();
    row.push(Cell::Player);
    row.push(Cell::Wall);
    result_field.push(row);

    result_field
}

fn main() {
    let mut main_loop = MainLoop::init();
    let game_field = initialize_field();

    loop {
        main_loop.update();
        main_loop.render();
    }

    draw(game_field);
}

fn draw( game_field: Vec< Vec<Cell> > ) {
    let mut stdout = MouseTerminal::from(stdout().into_raw_mode().unwrap());
    writeln!(stdout, "{}", termion::clear::All);

    for (i, column) in game_field.iter().enumerate() {
        for(j, cell) in column.iter().enumerate() {
            let tmp = get_symbol( cell );
            write!(stdout, "{}{}\r\n",
                 termion::cursor::Goto((i + 1) as u16, (j + 1) as u16), tmp );
        }
    }
}<commit_msg>Added GameLoop<commit_after>extern crate time;
extern crate termion;

use termion::{color,style,clear,cursor};
use termion::input::{MouseTerminal};
use termion::raw::IntoRawMode;
use std::io::{Write, stdout};

const FRAME_PER_SECOND: i64 = 120;

fn timestamp() -> i64 {
    let current_time = time::get_time();
    current_time.sec*1000 + i64::from( current_time.nsec / 1_000_000 )
}

struct MainLoop {
    initial_time:        i64,
    current_time:        i64,
    current_frame:       i64,
    last_rendered_frame: i64
}

impl MainLoop {
    fn init() -> MainLoop {
        MainLoop {
            initial_time:        timestamp(),
            current_time:        0,
            current_frame:       0,
            last_rendered_frame: 0
        }
    }

    fn update( &mut self ) {
        self.current_time = timestamp() - self.initial_time;
        self.current_frame = self.current_time*FRAME_PER_SECOND / 1000;

        if self.current_frame > self.last_rendered_frame {
            // do calc
        }
    }

    fn render( &mut self, rendering_fn: &Fn() ) {
        if self.current_frame > self.last_rendered_frame {
            println!( "{clear}", clear = clear::All );
            println!( "{goto}", goto = cursor::Goto(1, 1) );

            //
            println!( "Current time: {t}", t = ( self.current_time as f64 ) / 1000.0 );

            rendering_fn();

            //
            println!( "{reset}", reset = color::Fg( color::Reset ) );

            //
            self.last_rendered_frame = self.current_frame;
        }
    }
}

enum Cell {
    Empty,
    Wall,
    Player,
}

fn get_symbol( cell: &Cell ) -> char {
    match *cell {
        Cell::Empty => '_',
        Cell::Wall =>  '#',
        Cell::Player => '@'
    }
}

fn initialize_field( ) -> Vec<Vec<Cell>>{
    //ToDo: parse from file

    let mut result_field: Vec< Vec<Cell> > = Vec::new();

    let mut row: Vec<Cell> = Vec::new();
    row.push(Cell::Empty);
    row.push(Cell::Wall);
    result_field.push(row);

    let mut row: Vec<Cell> = Vec::new();
    row.push(Cell::Player);
    row.push(Cell::Wall);
    result_field.push(row);

    result_field
}

fn main() {
    let mut main_loop = MainLoop::init();
    let game_field = initialize_field();

    loop {
        main_loop.update();
        main_loop.render( &|| {
            draw( &game_field );
        });
    }
}

fn draw( game_field: &Vec< Vec<Cell> > ) {
    let mut stdout = MouseTerminal::from(stdout().into_raw_mode().unwrap());
    // writeln!(stdout, "{}", termion::clear::All);

    for (i, column) in game_field.iter().enumerate() {
        for(j, cell) in column.iter().enumerate() {
            let tmp = get_symbol( cell );
            write!(stdout, "{}{}\r\n",
                 termion::cursor::Goto((i + 1) as u16, (j + 1) as u16), tmp );
        }
    }
}<|endoftext|>


<commit_before>#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(proc_macro)]
#[macro_use] extern crate diesel_codegen;
#[macro_use] extern crate diesel;
extern crate dotenv;
extern crate iron;
extern crate staticfile;
extern crate router;
extern crate rustc_serialize;

use iron::prelude::*;
use staticfile::Static;
use router::Router;
use std::path::Path;

mod api;
mod database;
mod schema;
mod models;

fn main() {
    let mut router = Router::new();

    router.get("/", Static::new(Path::new("src/frontend/")), "index");
    router.get("/api", api::index, "api");
    router.get("/api/translations", api::translations, "translations");

    Iron::new(router).http("localhost:3000").unwrap();
}
<commit_msg>Code style: regroup rust features<commit_after>#![feature(custom_attribute, custom_derive, proc_macro)]
#[macro_use] extern crate diesel_codegen;
#[macro_use] extern crate diesel;
extern crate dotenv;
extern crate iron;
extern crate staticfile;
extern crate router;
extern crate rustc_serialize;

use iron::prelude::*;
use staticfile::Static;
use router::Router;
use std::path::Path;

mod api;
mod database;
mod schema;
mod models;

fn main() {
    let mut router = Router::new();

    router.get("/", Static::new(Path::new("src/frontend/")), "index");
    router.get("/api", api::index, "api");
    router.get("/api/translations", api::translations, "translations");

    Iron::new(router).http("localhost:3000").unwrap();
}
<|endoftext|>


<commit_before>#[macro_use] extern crate serde_derive;
extern crate serde;
extern crate serde_yaml;
extern crate csv;
extern crate tina;
#[macro_use] extern crate slog;
#[macro_use] extern crate slog_scope;
extern crate slog_term;

mod config;

use std::io::stdout;
use std::env;
use std::fs::OpenOptions;
use std::sync::mpsc::sync_channel;
use std::sync::mpsc::SyncSender;
use std::thread::{spawn, JoinHandle};
use std::collections::HashMap;

use slog::{Drain, Logger, Discard, Duplicate};
use slog_scope::set_global_logger;
use slog_term::{PlainSyncDecorator, FullFormat};

use tina::*;
use config::*;

const REVISION: &'static str = env!("TINA_REVISION");
const CONF_PATH_ENV_VAR: &'static str = "TINA_CONF_PATH";
const DEFAULT_CONFIG_PATH: &'static str = "config/tina.yaml";
const SERVER_LIST_URL: &'static str = "http://lst10s-sp.wni.co.jp/server_list.txt";
const WNI_THREAD_COUNT: u32 = 4;

const EEW_HISTORY_CAPACITY: usize = 128;

fn build_specific_logger(log_path: &Option<String>, duplication: bool, default: &Logger) -> Logger
{
	if let Some(ref path) = *log_path {

		let file = OpenOptions::new().append(true).create(true).open(path).unwrap();
		let drain = FullFormat::new(PlainSyncDecorator::new(file)).build();

		if duplication {
			Logger::root(Duplicate(drain, default.clone()).fuse(), o!())
		} else {
			Logger::root(drain.fuse(), o!())
		}

	} else {

		if duplication { default.clone() } else { Logger::root(Discard, o!()) }
	}
}

fn spawn_conn_thread(thread_num: u32, wni: Wni,
	epicenter_dict: HashMap<[u8; 3], String>, area_dict: HashMap<[u8; 3], String>,
	sock: SyncSender<EEW>) -> JoinHandle<()>
{
	spawn(move || {

		let mut moderator = Moderator::new();

		loop {

			let mut connection = match wni.connect() {
				Ok(v) => v,
				Err(e) => {
					error!("Thread {} - ConnectionError: {:?}", thread_num, e);
					moderator.wait_for_retry();
					moderator.add_count();
					continue;
				}
			};

			moderator.reset();
			info!("Thread {} - Connected: WNI ({})", thread_num, connection.server());

			loop {

				let eew = match connection.wait_for_telegram(&epicenter_dict, &area_dict) {
					Err(e) => {
						error!("Thread {} - StreamingError: {:?}", thread_num, e);
						break;
					},
					Ok(eew) => eew
				};

				sock.try_send(eew).expect("should not fail");
			}
		}
	})
}

fn main()
{
	let cmd_args: Vec<String> = env::args().collect();

	match cmd_args.get(1).map(|s| s.as_str()) {
		Some("-v") | Some("--version") => {
			eprintln!("Tina - EEW Client (rev.{})", REVISION);
			return;
		},
		_ => {}
	}

	let conf_path_arg = cmd_args.get(1).map(|s| s.as_str());
	let conf_path_env_owned = env::var(CONF_PATH_ENV_VAR).ok();
	let conf_path_env = conf_path_env_owned.as_ref().map(|s| s.as_str());
	let conf_path = conf_path_arg.or(conf_path_env).unwrap_or(DEFAULT_CONFIG_PATH);

	let conf = match Config::load_config(conf_path) {
		Err(err) => {
			println!("Error while loading config from '{}' ({:?})", conf_path, err);
			return;
		},
		Ok(c) => c
	};

	let stdout_drain = FullFormat::new(PlainSyncDecorator::new(stdout())).build();
	let stdout_logger = Logger::root(stdout_drain.fuse(), o!());

	let root_drain = stdout_logger.clone().filter_level(conf.log.log_level);
	let root_logger = Logger::root(root_drain.fuse(), o!());
	set_global_logger(root_logger).cancel_reset();

	let eew_logger = build_specific_logger(&conf.log.eew_log_path, conf.log.eew_stdout_log, &stdout_logger);
	let wni_logger = build_specific_logger(&conf.log.wni_log_path, conf.log.wni_stdout_log, &stdout_logger);

	let wni = Wni::new(conf.wni.id.clone(), "40285072".to_owned(), conf.wni.password.clone(),
		SERVER_LIST_URL.to_owned(), Some(wni_logger));
	let mut socks: Vec<Box<Routing>> = Vec::new();

	socks.push(Box::new(Router::new(Logging::new(eew_logger), TRUE_CONDITION, "Log")));
	info!("Enabled: EEW Logging");

	if let Some(ref t) = conf.twitter.as_ref() {
		let tw = Twitter::new(
			t.consumer_token.clone(), t.consumer_secret.clone(),
			t.access_token.clone(), t.access_secret.clone(), t.in_reply_to_enabled, t.updown_enabled);
		if ! tw.is_valid() {
			warn!("Twitter: Invalid tokens");
		} else {
			match t.cond {
				Some(ref v) => socks.push(Box::new(Router::new(tw, build_yaml_condition(v.clone()), "Twitter"))),
				None => socks.push(Box::new(Router::new(tw, TRUE_CONDITION, "Twitter"))),
			}
			info!("Enabled: Twitter");
		}
	}

	if let Some(ref s) = conf.slack.as_ref() {
		match Slack::build(&s.webhook_url, s.updown_enabled) {
			Ok(sl) => {
				match s.cond {
					Some(ref v) => socks.push(Box::new(Router::new(sl, build_yaml_condition(v.clone()), "Slack"))),
					None => socks.push(Box::new(Router::new(sl, TRUE_CONDITION, "Slack"))),
				}
				info!("Enabled: Slack");
			},
			Err(_) => {
				warn!("Slack: Invalid webhook url");
			}
		}
	}

	let mut conn_threads = Vec::new();
	let (eew_tx, eew_rx) = sync_channel(32);

	for thread_num in 0..WNI_THREAD_COUNT {

		let t = spawn_conn_thread(thread_num, wni.clone(),
			conf.epicenter_dict.clone(), conf.area_dict.clone(), eew_tx.clone());
		conn_threads.push(t);
	}

	let mut his = EEWHistory::new(EEW_HISTORY_CAPACITY);

	loop {
		let eew = eew_rx.recv().unwrap();
		if let Some(eew) = his.append(eew) {
			for s in socks.iter_mut() {
				s.emit(&eew);
			}
		}
	}
}
<commit_msg>Append the 'dyn' keyword for clarification<commit_after>#[macro_use] extern crate serde_derive;
extern crate serde;
extern crate serde_yaml;
extern crate csv;
extern crate tina;
#[macro_use] extern crate slog;
#[macro_use] extern crate slog_scope;
extern crate slog_term;

mod config;

use std::io::stdout;
use std::env;
use std::fs::OpenOptions;
use std::sync::mpsc::sync_channel;
use std::sync::mpsc::SyncSender;
use std::thread::{spawn, JoinHandle};
use std::collections::HashMap;

use slog::{Drain, Logger, Discard, Duplicate};
use slog_scope::set_global_logger;
use slog_term::{PlainSyncDecorator, FullFormat};

use tina::*;
use config::*;

const REVISION: &'static str = env!("TINA_REVISION");
const CONF_PATH_ENV_VAR: &'static str = "TINA_CONF_PATH";
const DEFAULT_CONFIG_PATH: &'static str = "config/tina.yaml";
const SERVER_LIST_URL: &'static str = "http://lst10s-sp.wni.co.jp/server_list.txt";
const WNI_THREAD_COUNT: u32 = 4;

const EEW_HISTORY_CAPACITY: usize = 128;

fn build_specific_logger(log_path: &Option<String>, duplication: bool, default: &Logger) -> Logger
{
	if let Some(ref path) = *log_path {

		let file = OpenOptions::new().append(true).create(true).open(path).unwrap();
		let drain = FullFormat::new(PlainSyncDecorator::new(file)).build();

		if duplication {
			Logger::root(Duplicate(drain, default.clone()).fuse(), o!())
		} else {
			Logger::root(drain.fuse(), o!())
		}

	} else {

		if duplication { default.clone() } else { Logger::root(Discard, o!()) }
	}
}

fn spawn_conn_thread(thread_num: u32, wni: Wni,
	epicenter_dict: HashMap<[u8; 3], String>, area_dict: HashMap<[u8; 3], String>,
	sock: SyncSender<EEW>) -> JoinHandle<()>
{
	spawn(move || {

		let mut moderator = Moderator::new();

		loop {

			let mut connection = match wni.connect() {
				Ok(v) => v,
				Err(e) => {
					error!("Thread {} - ConnectionError: {:?}", thread_num, e);
					moderator.wait_for_retry();
					moderator.add_count();
					continue;
				}
			};

			moderator.reset();
			info!("Thread {} - Connected: WNI ({})", thread_num, connection.server());

			loop {

				let eew = match connection.wait_for_telegram(&epicenter_dict, &area_dict) {
					Err(e) => {
						error!("Thread {} - StreamingError: {:?}", thread_num, e);
						break;
					},
					Ok(eew) => eew
				};

				sock.try_send(eew).expect("should not fail");
			}
		}
	})
}

fn main()
{
	let cmd_args: Vec<String> = env::args().collect();

	match cmd_args.get(1).map(|s| s.as_str()) {
		Some("-v") | Some("--version") => {
			eprintln!("Tina - EEW Client (rev.{})", REVISION);
			return;
		},
		_ => {}
	}

	let conf_path_arg = cmd_args.get(1).map(|s| s.as_str());
	let conf_path_env_owned = env::var(CONF_PATH_ENV_VAR).ok();
	let conf_path_env = conf_path_env_owned.as_ref().map(|s| s.as_str());
	let conf_path = conf_path_arg.or(conf_path_env).unwrap_or(DEFAULT_CONFIG_PATH);

	let conf = match Config::load_config(conf_path) {
		Err(err) => {
			println!("Error while loading config from '{}' ({:?})", conf_path, err);
			return;
		},
		Ok(c) => c
	};

	let stdout_drain = FullFormat::new(PlainSyncDecorator::new(stdout())).build();
	let stdout_logger = Logger::root(stdout_drain.fuse(), o!());

	let root_drain = stdout_logger.clone().filter_level(conf.log.log_level);
	let root_logger = Logger::root(root_drain.fuse(), o!());
	set_global_logger(root_logger).cancel_reset();

	let eew_logger = build_specific_logger(&conf.log.eew_log_path, conf.log.eew_stdout_log, &stdout_logger);
	let wni_logger = build_specific_logger(&conf.log.wni_log_path, conf.log.wni_stdout_log, &stdout_logger);

	let wni = Wni::new(conf.wni.id.clone(), "40285072".to_owned(), conf.wni.password.clone(),
		SERVER_LIST_URL.to_owned(), Some(wni_logger));
	let mut socks: Vec<Box<dyn Routing>> = Vec::new();

	socks.push(Box::new(Router::new(Logging::new(eew_logger), TRUE_CONDITION, "Log")));
	info!("Enabled: EEW Logging");

	if let Some(ref t) = conf.twitter.as_ref() {
		let tw = Twitter::new(
			t.consumer_token.clone(), t.consumer_secret.clone(),
			t.access_token.clone(), t.access_secret.clone(), t.in_reply_to_enabled, t.updown_enabled);
		if ! tw.is_valid() {
			warn!("Twitter: Invalid tokens");
		} else {
			match t.cond {
				Some(ref v) => socks.push(Box::new(Router::new(tw, build_yaml_condition(v.clone()), "Twitter"))),
				None => socks.push(Box::new(Router::new(tw, TRUE_CONDITION, "Twitter"))),
			}
			info!("Enabled: Twitter");
		}
	}

	if let Some(ref s) = conf.slack.as_ref() {
		match Slack::build(&s.webhook_url, s.updown_enabled) {
			Ok(sl) => {
				match s.cond {
					Some(ref v) => socks.push(Box::new(Router::new(sl, build_yaml_condition(v.clone()), "Slack"))),
					None => socks.push(Box::new(Router::new(sl, TRUE_CONDITION, "Slack"))),
				}
				info!("Enabled: Slack");
			},
			Err(_) => {
				warn!("Slack: Invalid webhook url");
			}
		}
	}

	let mut conn_threads = Vec::new();
	let (eew_tx, eew_rx) = sync_channel(32);

	for thread_num in 0..WNI_THREAD_COUNT {

		let t = spawn_conn_thread(thread_num, wni.clone(),
			conf.epicenter_dict.clone(), conf.area_dict.clone(), eew_tx.clone());
		conn_threads.push(t);
	}

	let mut his = EEWHistory::new(EEW_HISTORY_CAPACITY);

	loop {
		let eew = eew_rx.recv().unwrap();
		if let Some(eew) = his.append(eew) {
			for s in socks.iter_mut() {
				s.emit(&eew);
			}
		}
	}
}
<|endoftext|>


<commit_before>// Genetic Algorithm for convergence to a given string
// Author: Duncan Dean
extern crate rand;
use rand::Rng;
extern crate time;
use time::PreciseTime;

fn rand_string(size: usize) -> String {
    return rand::thread_rng().gen_ascii_chars().take(size).collect();
}

fn crossover(chrome1: Chromosome, chrome2: Chromosome, cross_prob: f32, solution: &str) -> Chromosome {
    if rand::thread_rng().gen_range::<f32>(0.0, 1.0) <= cross_prob {
        let code_len = chrome1.code.len();
        let rand_index = rand::thread_rng().gen_range(0, code_len);
        let first_half = &chrome1.code[0..rand_index];
        let second_half = &chrome2.code[rand_index..code_len];
        let new_code = first_half.to_string() + second_half;
        Chromosome {
            code: new_code.to_string(),
            cost_score: cost_function(&new_code, solution),
            solution: solution.to_string(),
        }
    } else if chrome1.cost_score < chrome2.cost_score {
        chrome1.clone()
    } else {
        chrome2.clone()
    }
}

fn cost_function(code: &str, solution: &str) -> u32 {
    let chars = solution.as_bytes();
    let code_chars = code.as_bytes();
    let mut cost: u32 = 0;
    for i in 0..chars.len() {
        cost += ((chars[i] as i32) - (code_chars[i] as i32)).abs() as u32;
    }
    return cost;
}

#[derive(Clone)]
struct Chromosome {
    code: String,
    cost_score: u32,
    solution: String,
}

impl Chromosome {
    fn new(solution: String) -> Chromosome {
        let random_string = rand_string(solution.len());
        Chromosome {
            code: random_string.clone(),
            cost_score: cost_function(&random_string, &solution),
            solution: solution,
        }
    }

    fn mutate(&mut self, mut_prob:f64) -> Chromosome {
        if rand::thread_rng().gen_range::<f64>(0.0, 1.0) <= mut_prob {
            let rand_index = rand::thread_rng().gen_range(0, self.code.len());
            let mut new_code_vec: Vec<char> = self.code.chars().collect();
            new_code_vec[rand_index] = rand::thread_rng().gen_range(32, 123) as u8 as char;
            self.code = new_code_vec.iter().fold("".to_string(), |acc, s| acc + &s.to_string());
            self.cost_score = cost_function(&self.code, &self.solution);
            self.clone()

        } else {
            self.clone()
        }

    }

}

fn main() {
    let solution = "Tom looks tired".to_string();
    let pop_size = 160; // Must be greater than 1
    let max_pop = pop_size * 1;
    let mut_prob = 0.3;
    let kill_constant = 0.45;
    let cross_prob = 0.5;
    let mut population = Vec::new();

    // Initialize population
    for i in 0..pop_size {
        population.push(Chromosome::new(solution.to_string()));
        //println!("{}, cost: {}", population[i].code, population[i].cost_score);
    }

    population.sort_by(|ref a, ref b| a.cost_score.cmp(&b.cost_score));
    let mut winner: Chromosome = population[0].clone();
    // Step generation
    let mut j = 1;

    let start = PreciseTime::now();

    while  winner.cost_score != 0 {

        // Mutations
        for i in 0..population.len() {
            population[i] = population[i].mutate(mut_prob);
        }

        // Kill the weaklings
        population.sort_by(|ref a, ref b| a.cost_score.cmp(&b.cost_score));
        for _ in 0..((( population.len() as f32)*kill_constant) as u32) {
            population.pop();
        }

        // Crossovers
        if population.len() < max_pop {
            for i in 0..(population.len() - 2) {
                let chrome1 = population[i].clone();
                let chrome2 = population[i+1].clone();
                population.push(crossover(chrome1, chrome2, cross_prob, &solution));
            }
        }

        population.sort_by(|ref a, ref b| a.cost_score.cmp(&b.cost_score));
        winner = population[0].clone();
        //println!("\nGeneration: {}\nString: {}\nCost: {}\n", j, winner.code, winner.cost_score);

        j += 1;

    }

    let end = PreciseTime::now();
    println!("Benchmark Time: {}", start.to(end));

}
<commit_msg>Simplified Chromosome::mutate<commit_after>// Genetic Algorithm for convergence to a given string
// Author: Duncan Dean
extern crate rand;
use rand::Rng;
extern crate time;
use time::PreciseTime;

fn rand_string(size: usize) -> String {
    return rand::thread_rng().gen_ascii_chars().take(size).collect();
}

fn crossover(chrome1: Chromosome, chrome2: Chromosome, cross_prob: f32, solution: &str) -> Chromosome {
    if rand::thread_rng().gen_range::<f32>(0.0, 1.0) <= cross_prob {
        let code_len = chrome1.code.len();
        let rand_index = rand::thread_rng().gen_range(0, code_len);
        let first_half = &chrome1.code[0..rand_index];
        let second_half = &chrome2.code[rand_index..code_len];
        let new_code = first_half.to_string() + second_half;
        Chromosome {
            code: new_code.to_string(),
            cost_score: cost_function(&new_code, solution),
            solution: solution.to_string(),
        }
    } else if chrome1.cost_score < chrome2.cost_score {
        chrome1.clone()
    } else {
        chrome2.clone()
    }
}

fn cost_function(code: &str, solution: &str) -> u32 {
    let chars = solution.as_bytes();
    let code_chars = code.as_bytes();
    let mut cost: u32 = 0;
    for i in 0..chars.len() {
        cost += ((chars[i] as i32) - (code_chars[i] as i32)).abs() as u32;
    }
    return cost;
}

#[derive(Clone)]
struct Chromosome {
    code: String,
    cost_score: u32,
    solution: String,
}

impl Chromosome {
    fn new(solution: String) -> Chromosome {
        let random_string = rand_string(solution.len());
        Chromosome {
            code: random_string.clone(),
            cost_score: cost_function(&random_string, &solution),
            solution: solution,
        }
    }

    fn mutate(&mut self, mut_prob:f64) -> Chromosome {
        if rand::thread_rng().gen_range::<f64>(0.0, 1.0) <= mut_prob {
            let rand_index = rand::thread_rng().gen_range(0, self.code.len());
            let mut code_vec = self.code.clone().into_bytes();
            code_vec[rand_index] = rand::thread_rng().gen_range(32, 123) as u8;
            self.code = String::from_utf8(code_vec).unwrap();
            self.cost_score = cost_function(&self.code, &self.solution);
        }
        self.clone()
    }

}

fn main() {
    let solution = "Tom looks tired".to_string();
    let pop_size = 160; // Must be greater than 1
    let max_pop = pop_size * 1;
    let mut_prob = 0.3;
    let kill_constant = 0.45;
    let cross_prob = 0.5;
    let mut population = Vec::new();

    // Initialize population
    for i in 0..pop_size {
        population.push(Chromosome::new(solution.to_string()));
        //println!("{}, cost: {}", population[i].code, population[i].cost_score);
    }

    population.sort_by(|ref a, ref b| a.cost_score.cmp(&b.cost_score));
    let mut winner: Chromosome = population[0].clone();
    // Step generation
    let mut j = 1;

    let start = PreciseTime::now();

    while  winner.cost_score != 0 {

        // Mutations
        for i in 0..population.len() {
            population[i] = population[i].mutate(mut_prob);
        }

        // Kill the weaklings
        population.sort_by(|ref a, ref b| a.cost_score.cmp(&b.cost_score));
        for _ in 0..((( population.len() as f32)*kill_constant) as u32) {
            population.pop();
        }

        // Crossovers
        if population.len() < max_pop {
            for i in 0..(population.len() - 2) {
                let chrome1 = population[i].clone();
                let chrome2 = population[i+1].clone();
                population.push(crossover(chrome1, chrome2, cross_prob, &solution));
            }
        }

        population.sort_by(|ref a, ref b| a.cost_score.cmp(&b.cost_score));
        winner = population[0].clone();
        //println!("\nGeneration: {}\nString: {}\nCost: {}\n", j, winner.code, winner.cost_score);

        j += 1;

    }

    let end = PreciseTime::now();
    println!("Benchmark Time: {}", start.to(end));

}
<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;
extern crate breezyvps;
extern crate simplelog;

use simplelog::{Config, TermLogger, WriteLogger, CombinedLogger, LogLevelFilter};
use std::fs::File;
use breezyvps::command;

fn sc_doctl(doctl_matches: &clap::ArgMatches) {
    if let Some(create_droplet_matches) = doctl_matches.subcommand_matches("create_droplet") {
        if let Some(name) = create_droplet_matches.value_of("name") {
            breezyvps::digitalocean::create_droplet_by_name(name);
        } else {
            println!("Missing required name parameter!");
        }
        return;
    }
    if let Some(destroy_droplet_matches) = doctl_matches.subcommand_matches("destroy_droplet") {
        if let Some(name) = destroy_droplet_matches.value_of("name") {
            breezyvps::digitalocean::destroy_droplet_by_name(name);
        } else {
            println!("Missing required name parameter!");
        }
        return;
    }
    if let Some(create_ssh_key_matches) = doctl_matches.subcommand_matches("create_sshkey") {
        if let Some(name) = create_ssh_key_matches.value_of("name") {
            breezyvps::digitalocean::create_sshkey(name);
        } else {
            println!("Missing required sshkey name parameter!");
        }
        return;
    }
}

fn sc_configure(configure_matches: &clap::ArgMatches) {
    if let Some(nginx_matches) = configure_matches.subcommand_matches("nginx") {
        if let Some(host) = nginx_matches.value_of("host") {
            // Default 8080
            let port = nginx_matches.value_of("port").unwrap_or("8080");
            breezyvps::configure::install_nginx(host);
            breezyvps::configure::add_nginx_host(host, port);
            breezyvps::configure::install_letsencrypt_cert(host);
        } else {
            println!("Missing required host parameter!");
        }
        return;
    }
}

fn main() {
    // Configure logging with simplelogger
    CombinedLogger::init(
        vec![
            TermLogger::new(LogLevelFilter::Info, Config::default()).unwrap(),
            WriteLogger::new(LogLevelFilter::Info, Config::default(), File::create("breezyvps.log").unwrap()),
        ]
    ).unwrap();

    let matches = clap_app!(myapp =>
        (version: "0.1.3")
        (author: "Michael Xu <michaeljxu11@gmail.com>")
        (about: "One stop shop for common command line goodness")
        (@arg verbose: -v ... "Enable verbose output")
        (@subcommand doctl =>
            (about: "Doctl wrapper")
            (author: "Michael Xu <michaeljxu11@gmail.com>")
            (@arg verbose: -v --verbose "Print test information verbosely")
            (@subcommand create_droplet =>
                (about: "Create a new droplet")
                (@arg name: +required "Name of the droplet, must be unique")
                (@arg config: -c "Which configuration to use [small|medium|large]")
            )
            (@subcommand destroy_droplet =>
                (about: "Destroy a droplet by name")
                (@arg name: +required "Name of the droplet to destroy completely")
            )
            (@subcommand create_sshkey =>
                (about: "Add an ssh key, which will be added upon instance creation")
                (@arg name: +required "Name of the new ssh keys")
            )
        )
        (@subcommand configure =>
            (about: "Configure droplets / nodes")
            (@subcommand nginx =>
                (about: "Install nginx and configure for host")
                (@arg host: +required "Host name of the droplet")
                (@arg port: "Port to run webapp from (default: 8080)")
            )
        )
    ).get_matches();

//    // Vary the output based on how many times the user used the "verbose" flag
//    // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
//    match matches.occurrences_of("v") {
//        0 => println!("No verbose info"),
//        1 => println!("Some verbose info"),
//        2 => println!("Tons of verbose info"),
//        3 | _ => println!("Don't be crazy"),
//    }

    // You can handle information about subcommands by requesting their matches by name
    // (as below), requesting just the name used, or both at the same time
    if let Some(matches) = matches.subcommand_matches("doctl") {
        sc_doctl(matches);
        return;
    }
    if let Some(matches) = matches.subcommand_matches("configure") {
        sc_configure(matches);
        return;
    }

    let x = breezyvps::chain::CommandChain::new();
    x.cmd("echo hello")
        .cmd("test2")
        .cmd("test3")
        .execute();

    breezyvps::chain::CommandChain::new()
        .cmd_nonfatal("echo hello")
        .cmd_nonfatal("restinpeace")
        .cmd("echo yo")
        .execute();

    let processing_func = |res: &command::Result| -> command::Result {
        let mut extra_stdout = res.stdout.clone();
        extra_stdout.push_str(" + processing");

        command::Result {
            exit_code: res.exit_code,
            success: res.success,
            stdout: extra_stdout,
            stderr: res.stderr.clone()
        }
    };

    let res = breezyvps::chain::CommandChain::new()
        .cmd("echo hello")
        .result_proc(&processing_func)
        .execute();

    println!("{}", res.result.unwrap().stdout);
}
<commit_msg>woo for final model, where executed commands are moved to old_commands<commit_after>#[macro_use]
extern crate clap;
extern crate breezyvps;
extern crate simplelog;

use simplelog::{Config, TermLogger, WriteLogger, CombinedLogger, LogLevelFilter};
use std::fs::File;
use breezyvps::command;

fn sc_doctl(doctl_matches: &clap::ArgMatches) {
    if let Some(create_droplet_matches) = doctl_matches.subcommand_matches("create_droplet") {
        if let Some(name) = create_droplet_matches.value_of("name") {
            breezyvps::digitalocean::create_droplet_by_name(name);
        } else {
            println!("Missing required name parameter!");
        }
        return;
    }
    if let Some(destroy_droplet_matches) = doctl_matches.subcommand_matches("destroy_droplet") {
        if let Some(name) = destroy_droplet_matches.value_of("name") {
            breezyvps::digitalocean::destroy_droplet_by_name(name);
        } else {
            println!("Missing required name parameter!");
        }
        return;
    }
    if let Some(create_ssh_key_matches) = doctl_matches.subcommand_matches("create_sshkey") {
        if let Some(name) = create_ssh_key_matches.value_of("name") {
            breezyvps::digitalocean::create_sshkey(name);
        } else {
            println!("Missing required sshkey name parameter!");
        }
        return;
    }
}

fn sc_configure(configure_matches: &clap::ArgMatches) {
    if let Some(nginx_matches) = configure_matches.subcommand_matches("nginx") {
        if let Some(host) = nginx_matches.value_of("host") {
            // Default 8080
            let port = nginx_matches.value_of("port").unwrap_or("8080");
            breezyvps::configure::install_nginx(host);
            breezyvps::configure::add_nginx_host(host, port);
            breezyvps::configure::install_letsencrypt_cert(host);
        } else {
            println!("Missing required host parameter!");
        }
        return;
    }
}

fn main() {
    // Configure logging with simplelogger
    CombinedLogger::init(
        vec![
            TermLogger::new(LogLevelFilter::Info, Config::default()).unwrap(),
            WriteLogger::new(LogLevelFilter::Info, Config::default(), File::create("breezyvps.log").unwrap()),
        ]
    ).unwrap();

    let matches = clap_app!(myapp =>
        (version: "0.1.3")
        (author: "Michael Xu <michaeljxu11@gmail.com>")
        (about: "One stop shop for common command line goodness")
        (@arg verbose: -v ... "Enable verbose output")
        (@subcommand doctl =>
            (about: "Doctl wrapper")
            (author: "Michael Xu <michaeljxu11@gmail.com>")
            (@arg verbose: -v --verbose "Print test information verbosely")
            (@subcommand create_droplet =>
                (about: "Create a new droplet")
                (@arg name: +required "Name of the droplet, must be unique")
                (@arg config: -c "Which configuration to use [small|medium|large]")
            )
            (@subcommand destroy_droplet =>
                (about: "Destroy a droplet by name")
                (@arg name: +required "Name of the droplet to destroy completely")
            )
            (@subcommand create_sshkey =>
                (about: "Add an ssh key, which will be added upon instance creation")
                (@arg name: +required "Name of the new ssh keys")
            )
        )
        (@subcommand configure =>
            (about: "Configure droplets / nodes")
            (@subcommand nginx =>
                (about: "Install nginx and configure for host")
                (@arg host: +required "Host name of the droplet")
                (@arg port: "Port to run webapp from (default: 8080)")
            )
        )
    ).get_matches();

//    // Vary the output based on how many times the user used the "verbose" flag
//    // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
//    match matches.occurrences_of("v") {
//        0 => println!("No verbose info"),
//        1 => println!("Some verbose info"),
//        2 => println!("Tons of verbose info"),
//        3 | _ => println!("Don't be crazy"),
//    }

    // You can handle information about subcommands by requesting their matches by name
    // (as below), requesting just the name used, or both at the same time
    if let Some(matches) = matches.subcommand_matches("doctl") {
        sc_doctl(matches);
        return;
    }
    if let Some(matches) = matches.subcommand_matches("configure") {
        sc_configure(matches);
        return;
    }

    let x = breezyvps::chain::CommandChain::new();
    x.cmd("echo hello")
        .cmd("test2")
        .cmd("test3")
        .execute();

    breezyvps::chain::CommandChain::new()
        .cmd_nonfatal("echo hello")
        .cmd_nonfatal("restinpeace")
        .cmd("echo yo")
        .execute();

    let processing_func = |res: &command::Result| -> command::Result {
        let mut extra_stdout = res.stdout.clone();
        extra_stdout.push_str(" + processing");

        command::Result {
            exit_code: res.exit_code,
            success: res.success,
            stdout: extra_stdout,
            stderr: res.stderr.clone()
        }
    };

    let res = breezyvps::chain::CommandChain::new()
        .cmd("echo hello")
        .result_proc(&processing_func)
        .execute()
        .execute();

    println!("{}", res.result.unwrap().stdout);
}
<|endoftext|>


<commit_before>extern crate docopt;
extern crate nalgebra;
extern crate riscan_pro;
extern crate rustc_serialize;

use docopt::Docopt;
use nalgebra::{Iterable, Transpose};
use riscan_pro::{Matrix, Project, ScanPosition};
use rustc_serialize::json::{Json, ToJson};
use std::collections::HashMap;

const USAGE: &'static str = "
RiSCAN PRO utilities.

Usage:
    riscan-pro export-filters <project> [<scan-position>]
    riscan-pro socs-to-glcs <project> [<scan-position>] [<x> <y> <z>]
    riscan-pro scan-positions <project>
    riscan-pro (-h | --help)

Options:
    -h --help                       Show this screen.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    cmd_export_filters: bool,
    cmd_socs_to_glcs: bool,
    cmd_scan_positions: bool,
    arg_project: String,
    arg_scan_position: Option<String>,
    arg_x: Option<f64>,
    arg_y: Option<f64>,
    arg_z: Option<f64>,
}

fn main() {
    let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
    if args.cmd_socs_to_glcs {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let glcs = scan_position.socs_to_glcs((args.arg_x.unwrap_or(0.),
                                               args.arg_y.unwrap_or(0.),
                                               args.arg_z.unwrap_or(0.)));
        println!("{:.2}, {:.2}, {:.2}", glcs.0, glcs.1, glcs.2);
    } else if args.cmd_scan_positions {
        let project = Project::from_path(args.arg_project).unwrap();
        for scan_position in project.scan_positions() {
            println!("{}", scan_position.name());
        }
    } else if args.cmd_export_filters {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let mut filters = Vec::new();
        filters.push(filters_transformation(scan_position.sop()));
        filters.push(filters_transformation(scan_position.pop()));
        println!("{}", filters.to_json());
    }
}

fn filters_transformation(matrix: Matrix) -> Json {
    let mut filter = HashMap::new();
    filter.insert("type".to_string(), "filters.transformation".to_json());
    filter.insert("matrix".to_string(),
                  matrix.transpose()
                      .iter()
                      .map(|n| format!("{}", n))
                      .collect::<Vec<_>>()
                      .join(" ")
                      .to_json());
    filter.to_json()
}
<commit_msg>Print coordinates with scan positions<commit_after>extern crate docopt;
extern crate nalgebra;
extern crate riscan_pro;
extern crate rustc_serialize;

use docopt::Docopt;
use nalgebra::{Iterable, Transpose};
use riscan_pro::{Matrix, Project, ScanPosition};
use rustc_serialize::json::{Json, ToJson};
use std::collections::HashMap;

const USAGE: &'static str = "
RiSCAN PRO utilities.

Usage:
    riscan-pro export-filters <project> [<scan-position>]
    riscan-pro socs-to-glcs <project> [<scan-position>] [<x> <y> <z>]
    riscan-pro scan-positions <project>
    riscan-pro (-h | --help)

Options:
    -h --help                       Show this screen.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    cmd_export_filters: bool,
    cmd_socs_to_glcs: bool,
    cmd_scan_positions: bool,
    arg_project: String,
    arg_scan_position: Option<String>,
    arg_x: Option<f64>,
    arg_y: Option<f64>,
    arg_z: Option<f64>,
}

fn main() {
    let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
    if args.cmd_socs_to_glcs {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let glcs = scan_position.socs_to_glcs((args.arg_x.unwrap_or(0.),
                                               args.arg_y.unwrap_or(0.),
                                               args.arg_z.unwrap_or(0.)));
        println!("{:.2}, {:.2}, {:.2}", glcs.0, glcs.1, glcs.2);
    } else if args.cmd_scan_positions {
        let project = Project::from_path(args.arg_project).unwrap();
        for scan_position in project.scan_positions() {
            let glcs = scan_position.socs_to_glcs((0., 0., 0.));
            println!("{},{:.2},{:.2},{:.2}", scan_position.name(), glcs.0, glcs.1, glcs.2);
        }
    } else if args.cmd_export_filters {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let mut filters = Vec::new();
        filters.push(filters_transformation(scan_position.sop()));
        filters.push(filters_transformation(scan_position.pop()));
        println!("{}", filters.to_json());
    }
}

fn filters_transformation(matrix: Matrix) -> Json {
    let mut filter = HashMap::new();
    filter.insert("type".to_string(), "filters.transformation".to_json());
    filter.insert("matrix".to_string(),
                  matrix.transpose()
                      .iter()
                      .map(|n| format!("{}", n))
                      .collect::<Vec<_>>()
                      .join(" ")
                      .to_json());
    filter.to_json()
}
<|endoftext|>