<commit_before>//! Helpers for writing Alfred script filter JSON output (Alfred 3)
//!
//! # Example
//!
//! ### JSON output (Alfred 3)
//!
//! ```
//! extern crate alfred;
//!
//! use std::io::{self, Write};
//!
//! fn write_items() -> io::Result<()> {
//!     alfred::json::write_items(io::stdout(), &[
//!         alfred::Item::new("Item 1"),
//!         alfred::ItemBuilder::new("Item 2")
//!                             .subtitle("Subtitle")
//!                             .into_item(),
//!         alfred::ItemBuilder::new("Item 3")
//!                             .arg("Argument")
//!                             .subtitle("Subtitle")
//!                             .icon_filetype("public.folder")
//!                             .into_item()
//!     ])
//! }
//!
//! fn main() {
//!     match write_items() {
//!         Ok(()) => {},
//!         Err(err) => {
//!             let _ = writeln!(&mut io::stderr(), "Error writing items: {}", err);
//!         }
//!     }
//! }
//! ```

use ::{Item, ItemType, Modifier, Icon};
use serde_json as json;
use serde_json::value::{Value, ToJson};
use std::io;
use std::io::prelude::*;

/// Writes a complete JSON document representing the `Item`s to the `Write`
///
/// The `Write` is flushed after the JSON document is written.
pub fn write_items<W: Write>(w: W, items: &[Item]) -> io::Result<()> {
    let mut w = w;
    let mut root = json::Map::new();
    // We know for a fact that our implementation of ToJson cannot return an error.
    root.insert("items".to_string(), Value::Array(items.into_iter()
                                                       .map(|x| x.to_json().unwrap())
                                                       .collect()));
    try!(write!(&mut w, "{}", Value::Object(root)));
    w.flush()
}

impl<'a> ToJson for Item<'a> {
    fn to_json(&self) -> json::error::Result<Value> {
        let mut d = json::Map::new();
        d.insert("title".to_string(), json!(self.title));
        if let Some(ref subtitle) = self.subtitle {
            d.insert("subtitle".to_string(), json!(subtitle));
        }
        if let Some(ref icon) = self.icon {
            d.insert("icon".to_string(), icon.to_json()?);
        }
        if let Some(ref uid) = self.uid {
            d.insert("uid".to_string(), json!(uid));
        }
        if let Some(ref arg) = self.arg {
            d.insert("arg".to_string(), json!(arg));
        }
        match self.type_ {
            ItemType::Default => {}
            ItemType::File => {
                d.insert("type".to_string(), json!("file"));
            }
            ItemType::FileSkipCheck => {
                d.insert("type".to_string(), json!("file:skipcheck"));
            }
        }
        if !self.valid {
            d.insert("valid".to_string(), Value::Bool(false));
        }
        if let Some(ref autocomplete) = self.autocomplete {
            d.insert("autocomplete".to_string(), json!(autocomplete));
        }
        if self.text_copy.is_some() || self.text_large_type.is_some() {
            let mut text = json::Map::new();
            if let Some(ref text_copy) = self.text_copy {
                text.insert("copy".to_string(), json!(text_copy));
            }
            if let Some(ref text_large_type) = self.text_large_type {
                text.insert("largetype".to_string(), json!(text_large_type));
            }
            d.insert("text".to_string(), Value::Object(text));
        }
        if let Some(ref url) = self.quicklook_url {
            d.insert("quicklookurl".to_string(), json!(url));
        }
        if !self.modifiers.is_empty() {
            let mut mods = json::Map::new();
            for (modifier, data) in self.modifiers.iter() {
                let key = match *modifier {
                    Modifier::Command => "cmd",
                    Modifier::Option => "alt",
                    Modifier::Control => "ctrl",
                    Modifier::Shift => "shift",
                    Modifier::Fn => "fn"
                }.to_string();
                let mut mod_ = json::Map::new();
                if let Some(ref subtitle) = data.subtitle {
                    mod_.insert("subtitle".to_string(), json!(subtitle));
                }
                if let Some(ref arg) = data.arg {
                    mod_.insert("arg".to_string(), json!(arg));
                }
                if let Some(valid) = data.valid {
                    mod_.insert("valid".to_string(), json!(valid));
                }
                mods.insert(key, Value::Object(mod_));
            }
            d.insert("mods".to_string(), Value::Object(mods));
        }
        Ok(Value::Object(d))
    }
}

impl<'a> ToJson for Icon<'a> {
    fn to_json(&self) -> json::error::Result<Value> {
        Ok(match *self {
            Icon::Path(ref s) => json!({"path": s}),
            Icon::File(ref s) => json!({"type": "fileicon", "path": s}),
            Icon::FileType(ref s) => json!({"type": "filetype", "path": s})
        })
    }
}
<commit_msg>Add a basic test for JSON output<commit_after>//! Helpers for writing Alfred script filter JSON output (Alfred 3)
//!
//! # Example
//!
//! ### JSON output (Alfred 3)
//!
//! ```
//! extern crate alfred;
//!
//! use std::io::{self, Write};
//!
//! fn write_items() -> io::Result<()> {
//!     alfred::json::write_items(io::stdout(), &[
//!         alfred::Item::new("Item 1"),
//!         alfred::ItemBuilder::new("Item 2")
//!                             .subtitle("Subtitle")
//!                             .into_item(),
//!         alfred::ItemBuilder::new("Item 3")
//!                             .arg("Argument")
//!                             .subtitle("Subtitle")
//!                             .icon_filetype("public.folder")
//!                             .into_item()
//!     ])
//! }
//!
//! fn main() {
//!     match write_items() {
//!         Ok(()) => {},
//!         Err(err) => {
//!             let _ = writeln!(&mut io::stderr(), "Error writing items: {}", err);
//!         }
//!     }
//! }
//! ```

use ::{Item, ItemType, Modifier, Icon};
use serde_json as json;
use serde_json::value::{Value, ToJson};
use std::io;
use std::io::prelude::*;

/// Writes a complete JSON document representing the `Item`s to the `Write`
///
/// The `Write` is flushed after the JSON document is written.
pub fn write_items<W: Write>(w: W, items: &[Item]) -> io::Result<()> {
    let mut w = w;
    let mut root = json::Map::new();
    // We know for a fact that our implementation of ToJson cannot return an error.
    root.insert("items".to_string(), Value::Array(items.into_iter()
                                                       .map(|x| x.to_json().unwrap())
                                                       .collect()));
    try!(write!(&mut w, "{}", Value::Object(root)));
    w.flush()
}

impl<'a> ToJson for Item<'a> {
    fn to_json(&self) -> json::error::Result<Value> {
        let mut d = json::Map::new();
        d.insert("title".to_string(), json!(self.title));
        if let Some(ref subtitle) = self.subtitle {
            d.insert("subtitle".to_string(), json!(subtitle));
        }
        if let Some(ref icon) = self.icon {
            d.insert("icon".to_string(), icon.to_json()?);
        }
        if let Some(ref uid) = self.uid {
            d.insert("uid".to_string(), json!(uid));
        }
        if let Some(ref arg) = self.arg {
            d.insert("arg".to_string(), json!(arg));
        }
        match self.type_ {
            ItemType::Default => {}
            ItemType::File => {
                d.insert("type".to_string(), json!("file"));
            }
            ItemType::FileSkipCheck => {
                d.insert("type".to_string(), json!("file:skipcheck"));
            }
        }
        if !self.valid {
            d.insert("valid".to_string(), Value::Bool(false));
        }
        if let Some(ref autocomplete) = self.autocomplete {
            d.insert("autocomplete".to_string(), json!(autocomplete));
        }
        if self.text_copy.is_some() || self.text_large_type.is_some() {
            let mut text = json::Map::new();
            if let Some(ref text_copy) = self.text_copy {
                text.insert("copy".to_string(), json!(text_copy));
            }
            if let Some(ref text_large_type) = self.text_large_type {
                text.insert("largetype".to_string(), json!(text_large_type));
            }
            d.insert("text".to_string(), Value::Object(text));
        }
        if let Some(ref url) = self.quicklook_url {
            d.insert("quicklookurl".to_string(), json!(url));
        }
        if !self.modifiers.is_empty() {
            let mut mods = json::Map::new();
            for (modifier, data) in self.modifiers.iter() {
                let key = match *modifier {
                    Modifier::Command => "cmd",
                    Modifier::Option => "alt",
                    Modifier::Control => "ctrl",
                    Modifier::Shift => "shift",
                    Modifier::Fn => "fn"
                }.to_string();
                let mut mod_ = json::Map::new();
                if let Some(ref subtitle) = data.subtitle {
                    mod_.insert("subtitle".to_string(), json!(subtitle));
                }
                if let Some(ref arg) = data.arg {
                    mod_.insert("arg".to_string(), json!(arg));
                }
                if let Some(valid) = data.valid {
                    mod_.insert("valid".to_string(), json!(valid));
                }
                mods.insert(key, Value::Object(mod_));
            }
            d.insert("mods".to_string(), Value::Object(mods));
        }
        Ok(Value::Object(d))
    }
}

impl<'a> ToJson for Icon<'a> {
    fn to_json(&self) -> json::error::Result<Value> {
        Ok(match *self {
            Icon::Path(ref s) => json!({"path": s}),
            Icon::File(ref s) => json!({"type": "fileicon", "path": s}),
            Icon::FileType(ref s) => json!({"type": "filetype", "path": s})
        })
    }
}

#[test]
fn test_to_json() {
    let item1 = Item::new("Item 1");
    assert_eq!(item1.to_json().unwrap(), json!({"title": "Item 1"}));
    let item2 = ::ItemBuilder::new("Item 2")
                               .subtitle("Subtitle")
                               .into_item();
    assert_eq!(item2.to_json().unwrap(),
              json!({
                  "title": "Item 2",
                  "subtitle": "Subtitle"
              }));
    let item3 = ::ItemBuilder::new("Item 3")
                               .arg("Argument")
                               .subtitle("Subtitle")
                               .icon_filetype("public.folder")
                               .into_item();
    assert_eq!(item3.to_json().unwrap(),
               json!({
                   "title": "Item 3",
                   "subtitle": "Subtitle",
                   "arg": "Argument",
                   "icon": { "type": "filetype", "path": "public.folder" }
               }));
}
<|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;

#[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 unix_socket;

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 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 compositor;
mod background;

/// 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 mut location = record.location().module_path();
    if let Some(index) = location.find("way_cooler::") {
        let index = index + "way_cooler::".len();
        location = &location[index..];
    }
    format!("{} {} [{}] {} \x1B[0m", color, record.level(), location, 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() {
    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>Add filename and line number to log output<commit_after>//! Main module of way-cooler

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

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

#[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 unix_socket;

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 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 compositor;
mod background;

/// 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() {
    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();
}
<|endoftext|>


<commit_before>#![feature(old_io)]
extern crate sysly;

use sysly::Syslog;
use std::old_io::net::ip::{ Ipv4Addr, SocketAddr };

fn main() {
  let host = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 514 };
  let mut syslog = Syslog::udp(host);
  match syslog.info("Hello syslog. I'm rust.") {
    Err(e) => panic!("error sending -- {}", e),
    Ok(_) => println!("sent")
  };
}
<commit_msg>main updates<commit_after>#![feature(old_io)]
extern crate sysly;

use sysly::{ Facility, Syslog };
use std::old_io::net::ip::{ Ipv4Addr, SocketAddr };

fn main() {
  let host = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 514 };
  let mut syslog = Syslog::udp(host).facility(Facility::LOCAL3).tag("test");
  match syslog.info("Hello syslog. I'm rust.") {
    Err(e) => panic!("error sending -- {}", e),
    Ok(_) => println!("sent")
  };
}
<|endoftext|>


<commit_before>extern crate byteorder;
extern crate rand;
extern crate sdl2;
extern crate time;

use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;

mod cpu;
mod graphics;
mod input;
mod interconnect;
mod memory;
mod sound;
mod vm;

fn main() {
    // TODO: Use an actual argument parser when adding options in the future.
    if let Some(rom_file_name) = env::args().nth(1) {
        let rom = read_bin(rom_file_name);

        let mut vm = vm::VirtualMachine::new(rom);
        vm.run();
    } else {
        print_usage();
        std::process::exit(1);
    }
}

/// Prints the application name alongside the cargo version.
fn print_version() {
    println!("notch {}", env!("CARGO_PKG_VERSION"));
}

/// Prints usage information.
fn print_usage() {
    println!("Notch is a CHIP-8 virtual machine written in Rust.");
    println!("");
    println!("Usage: notch [ROM]");
    println!("");
    println!("To contribute or report bugs, please see:");
    println!("<https://github.com/Reshurum/notch>");
}

/// Reads a file into a vector of unsigned bytes.
fn read_bin<P: AsRef<Path>>(path: P) -> Vec<u8> {
    let mut buffer: Vec<u8> = Vec::new();
    let filename = format!("{}", path.as_ref().display());

    // Open and read the file if it exists.
    let mut file = match File::open(path) {
        Ok(ref mut file) => {
            file.read_to_end(&mut buffer).unwrap();
        },
        Err(why) => {
            println!("notch: cannot open '{}': {}", filename, why);
            std::process::exit(2);
        },
    };

    buffer
}
<commit_msg>Fix compiler warnings<commit_after>extern crate byteorder;
extern crate rand;
extern crate sdl2;
extern crate time;

use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;

mod cpu;
mod graphics;
mod input;
mod interconnect;
mod memory;
mod sound;
mod vm;

fn main() {
    // TODO: Use an actual argument parser when adding options in the future.
    if let Some(rom_file_name) = env::args().nth(1) {
        let rom = read_bin(rom_file_name);

        let mut vm = vm::VirtualMachine::new(rom);
        vm.run();
    } else {
        print_usage();
        std::process::exit(1);
    }
}

/// Prints the application name alongside the cargo version.
fn print_version() {
    println!("notch {}", env!("CARGO_PKG_VERSION"));
}

/// Prints usage information.
fn print_usage() {
    println!("Notch is a CHIP-8 virtual machine written in Rust.");
    println!("");
    println!("Usage: notch [ROM]");
    println!("");
    println!("To contribute or report bugs, please see:");
    println!("<https://github.com/Reshurum/notch>");
}

/// Reads a file into a vector of unsigned bytes.
fn read_bin<P: AsRef<Path>>(path: P) -> Vec<u8> {
    let mut buffer: Vec<u8> = Vec::new();
    let filename = format!("{}", path.as_ref().display());

    // Open and read the file if it exists.
    match File::open(path) {
        Ok(ref mut file) => {
            file.read_to_end(&mut buffer).unwrap();
        },
        Err(why) => {
            println!("notch: cannot open '{}': {}", filename, why);
            std::process::exit(2);
        },
    };

    buffer
}
<|endoftext|>


<commit_before>extern crate piston_window;
extern crate find_folder;
extern crate gfx_device_gl;
extern crate gfx_graphics;
extern crate gfx;
extern crate vecmath;
extern crate image as im;
extern crate time;
extern crate rand;

use piston_window::*;
use time::{Duration, PreciseTime};

mod player;
mod io;
mod level;
mod inventory;
mod item;
mod actor;
mod field;
mod interactable;
mod coord;
mod camera;
mod bot;

use camera::Cam;
use player::{Player, LastKey};
use bot::Bot;
use io::render_tile;
use io::tileset::{TILE_HEIGHT, TILE_WIDTH, Tileset};
use level::Level;
use actor::Actor;
use interactable::Interactable;
use interactable::InteractableType;
use io::sprite::Sprite;

//EINGABEN
const TWO_PLAYER: bool = true;
const SPRITE_P_1: &'static str = "warrior2.png";
const SPRITE_P_2: &'static str = "paladin.png";
const CAMERA_BUF_X: u64 = 4;
const CAMERA_BUF_Y: u64 = 4;

const WIDTH: i64 = 586;
const HEIGHT: i64 = 586;

const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

pub struct App {
    player_one: Player,
    player_two: Option<Player>,
    bots: Vec<Bot>,
    cam: Cam,
}

impl App {
    fn new(two_player: bool) -> Self {
        App {
            // 0,0 Dummy-Value
            player_one: Player::new(1, 1, 1),
            player_two: if two_player {
                // 0,0 Dummy-Value
                Some(Player::new(1, 2, 2))
            } else {
                None
            },
            bots: vec![Bot::new(2, 2, 1), Bot::new(4, 4, 2), Bot::new(6, 6, 3), Bot::new(8, 6, 4), Bot::new(18, 18, 5), Bot::new(18, 18, 6), Bot::new(18, 18, 7), Bot::new(18, 18, 8), Bot::new(18, 18, 9), Bot::new(18, 18, 10)],
            cam: Cam::new(CAMERA_BUF_X, CAMERA_BUF_Y),
        }
    }

    fn on_draw(&mut self,
               mut w: &mut PistonWindow,
               e: &Event,
               tileset: &Tileset,
               level: &mut Level,
               state: usize) {
        let range = self.cam.get_range();

        w.draw_2d(e, |c, gl| {
            let player_one = &self.player_one.sprite;
            let player_two = &self.player_two;

            // Clear the screen.
            clear(BLACK, gl);

            let center_lv = c.transform.trans(0.0, 0.0);

            //render_level(&tileset, gl, center_lv, &mut level);
            for (h, j) in (range.x_min..range.x_max).enumerate() {
                for (w, i) in (range.y_min..range.y_max).enumerate() {
                    let tile = match tileset.get_texture(level.get_data()[i as usize][j as usize].get_id()) {
                    Some(x) => x,
                    None => panic!("No texture found."),
                    };
                    // DEBUG
                    //println!("{} {}", i, j);
                    render_tile(&tile, gl, center_lv,  h as u32 * TILE_HEIGHT,
                            w as u32 * TILE_WIDTH,
                            w as u32,
                            h as u32);
                }
            }
            if let Some(ref p1) = *player_one {
                let center_p1 = c.transform.trans(((self.player_one.coord.get_x() - range.x_min )* 65) as f64,
                                              ((self.player_one.coord.get_y() - range.y_min)* 65) as f64);

                p1.render(gl, center_p1, state as u64);
            }

            if let Some(ref p2) = *player_two {
                if let Some (ref x) =p2.sprite {

                let center_p2 = c.transform.trans(((p2.coord.get_x() - range.x_min) * 65) as f64,

                                              ((p2.coord.get_y() - range.y_min )* 65) as f64);
                 x.render(gl, center_p2, state as u64);
                 }

            }

            for b in &mut self.bots {

                if let Some(ref br) = b.sprite {
                    if b.coord.get_x() >= range.x_min &&  b.coord.get_x() < range.x_max &&
                        b.coord.get_y() >= range.y_min && b.coord.get_y() < range.y_max {

                        let center_b1 = c.transform.trans(((b.coord.get_x() - range.x_min )* 65) as f64,
                                                          ((b.coord.get_y() - range.y_min)* 65) as f64);
                        br.render(gl, center_b1, state as u64);
                    }
                }

            }
        });
    }

    fn on_update(&mut self,
                 args: &UpdateArgs,
                 level: &mut Level,
                 state: usize)
    {
        let coord1 = self.player_one.coord.clone();
        let mut coord2 = coord1.clone();

        if let Some(ref p2) = self.player_two {
            coord2 = p2.coord.clone();
        }

        let range = self.cam.get_range_update();

        self.player_one.on_update(args, range, level, InteractableType::Player(1));

        if let Some(ref mut x) = self.player_two {
            x.on_update(args, range, level, InteractableType::Player(2));
        }

        for b in &mut self.bots {
            b.on_update(args, range, level, state);
        }

        self.cam.calc_coordinates(coord1, coord2, level);
    }

    fn on_input(&mut self, inp: Button, pressed: bool) {

        match inp {
            Button::Keyboard(Key::Up) => {
                if pressed {
                    self.player_one.last = LastKey::Up;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::Down) => {
                if pressed {
                    self.player_one.last = LastKey::Down;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::Left) => {
                if pressed {
                    self.player_one.last = LastKey::Left;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::Right) => {
                if pressed {
                    self.player_one.last = LastKey::Right;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::W) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Up;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::S) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Down;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::A) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Left;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::D) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Right;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::Space) => {
                if pressed {
                    println!("Space!!!");
                }
            }
            _ => {}

        }
    }
}

fn main() {
    let mut window: PistonWindow = WindowSettings::new("chicken_fight_3000_ultimate_tournament",
                                                       [WIDTH as u32, HEIGHT as u32])
        .exit_on_esc(true)
        .fullscreen(false)
        .resizable(false)
        .build()
        .unwrap();

    // Create a new game and run it.

    let mut app = App::new(TWO_PLAYER);

    let mut events = window.events();

    let tiles = match find_folder::Search::Kids(1).for_folder("tiles") {
        Ok(res) => res.join("tileset-pokemon_dawn.png"),
        Err(_) => panic!("Folder 'tiles' not found!"),
    };

    let file_path = match tiles.to_str() {
        Some(res) => res,
        None => panic!("Tileset not found!"),
    };

    let folder_level = match find_folder::Search::Kids(0).for_folder("src") {
        Ok(res) => res.join("level1.lvl"),
        Err(_) => panic!("Folder 'src' not found!"),
    };

    let level_path = match folder_level.to_str() {
        Some(res) => res,
        None => panic!("Level not found!"),
    };

    let tileset = io::read_tileset(file_path, &mut window);

    let mut level = io::read_level(level_path);

    // insert players in level
    level.get_data()[app.player_one.coord.get_x() as usize][app.player_one.coord.get_y() as usize].set_fieldstatus(InteractableType::Player(1));
    if let Some(ref p2) = app.player_two {
        level.get_data()[p2.coord.get_x() as usize][p2.coord.get_y() as usize].set_fieldstatus(InteractableType::Player(2));
    }

    let mut start = PreciseTime::now();
    app.cam.set_borders((level.get_width() as u64, level.get_height()as u64));
    app.player_one.set_sprite(Sprite::fill_sprite("knight.png",2,1,64,64,&mut window));

    if let Some(ref mut p2) = app.player_two {
        p2.set_borders((level.get_width() as u64, level.get_height() as u64));
        p2.set_sprite(Sprite::fill_sprite("paladin.png", 2, 1, 64, 64, &mut window));
    }
    let mut i = 0;
    for b in &mut app.bots {

        let file = if i %3 == 0 {"chicken_pink.png"} else if i% 3 == 1 {"chicken_brown.png"} else {"chicken_white.png"};
        b.set_sprite(Sprite::fill_sprite(file,2,1,64,64,&mut window));
        b.set_borders((level.get_width() as u64, level.get_height()as u64));
        i = i +1;
    }

    while let Some(e) = events.next(&mut window) {
        let now = start.to(PreciseTime::now()).num_milliseconds();
        if now > 1000 {
            start = PreciseTime::now();
        }
        let state = if now <= 500 { 0 } else { 1 };

        if let Some(_) = e.render_args() {
            app.on_draw(&mut window, &e, &tileset, &mut level, state);
        }
        if let Some(i) = e.release_args() {
            app.on_input(i, false);
        }
        if let Some(i) = e.press_args() {
            app.on_input(i, true);
        }

        if let Some(u) = e.update_args() {
            app.on_update(&u, &mut level, state);
        }
    }
}
<commit_msg>Update main.rs<commit_after>extern crate piston_window;
extern crate find_folder;
extern crate gfx_device_gl;
extern crate gfx_graphics;
extern crate gfx;
extern crate vecmath;
extern crate image as im;
extern crate time;
extern crate rand;

use piston_window::*;
use time::{Duration, PreciseTime};

mod player;
mod io;
mod level;
mod inventory;
mod item;
mod actor;
mod field;
mod interactable;
mod coord;
mod camera;
mod bot;

use camera::Cam;
use player::{Player, LastKey};
use bot::Bot;
use io::render_tile;
use io::tileset::{TILE_HEIGHT, TILE_WIDTH, Tileset};
use level::Level;
use actor::Actor;
use interactable::Interactable;
use interactable::InteractableType;
use io::sprite::Sprite;

//EINGABEN
const TWO_PLAYER: bool = true;
const SPRITE_P_1: &'static str = "warrior2.png";
const SPRITE_P_2: &'static str = "paladin.png";
const CAMERA_BUF_X: u64 = 4;
const CAMERA_BUF_Y: u64 = 4;

const WIDTH: i64 = 586;
const HEIGHT: i64 = 586;

const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

pub struct App {
    player_one: Player,
    player_two: Option<Player>,
    bots: Vec<Bot>,
    cam: Cam,
}

impl App {
    fn new(two_player: bool) -> Self {
        App {
            // 0,0 Dummy-Value
            player_one: Player::new(1, 1, 1),
            player_two: if two_player {
                // 0,0 Dummy-Value
                Some(Player::new(1, 2, 2))
            } else {
                None
            },
            bots: vec![Bot::new(2, 2, 1), Bot::new(4, 4, 2), Bot::new(6, 6, 3), Bot::new(8, 6, 4), Bot::new(18, 18, 5), Bot::new(18, 18, 6), Bot::new(18, 18, 7), Bot::new(18, 18, 8), Bot::new(18, 18, 9), Bot::new(18, 18, 10)],
            cam: Cam::new(CAMERA_BUF_X, CAMERA_BUF_Y),
        }
    }

    fn on_draw(&mut self,
               mut w: &mut PistonWindow,
               e: &Event,
               tileset: &Tileset,
               level: &mut Level,
               state: usize) {
        let range = self.cam.get_range();

        w.draw_2d(e, |c, gl| {
            let player_one = &self.player_one.sprite;
            let player_two = &self.player_two;

            // Clear the screen.
            clear(BLACK, gl);

            let center_lv = c.transform.trans(0.0, 0.0);

            //render_level(&tileset, gl, center_lv, &mut level);
            for (h, j) in (range.x_min..range.x_max).enumerate() {
                for (w, i) in (range.y_min..range.y_max).enumerate() {
                    let tile = match tileset.get_texture(level.get_data()[i as usize][j as usize].get_id()) {
                    Some(x) => x,
                    None => panic!("No texture found."),
                    };
                    // DEBUG
                    //println!("{} {}", i, j);
                    render_tile(&tile, gl, center_lv,  h as u32 * TILE_HEIGHT,
                            w as u32 * TILE_WIDTH,
                            w as u32,
                            h as u32);
                }
            }
            if let Some(ref p1) = *player_one {
                let center_p1 = c.transform.trans(((self.player_one.coord.get_x() - range.x_min )* 65) as f64,
                                              ((self.player_one.coord.get_y() - range.y_min)* 65) as f64);

                p1.render(gl, center_p1, state as u64);
            }

            if let Some(ref p2) = *player_two {
                if let Some (ref x) =p2.sprite {

                let center_p2 = c.transform.trans(((p2.coord.get_x() - range.x_min) * 65) as f64,

                                              ((p2.coord.get_y() - range.y_min )* 65) as f64);
                 x.render(gl, center_p2, state as u64);
                 }

            }

            for b in &mut self.bots {

                if let Some(ref br) = b.sprite {
                    if b.coord.get_x() >= range.x_min &&  b.coord.get_x() < range.x_max &&
                        b.coord.get_y() >= range.y_min && b.coord.get_y() < range.y_max {

                        let center_b1 = c.transform.trans(((b.coord.get_x() - range.x_min )* 65) as f64,
                                                          ((b.coord.get_y() - range.y_min)* 65) as f64);
                        br.render(gl, center_b1, state as u64);
                    }
                }

            }
        });
    }

    fn on_update(&mut self,
                 args: &UpdateArgs,
                 level: &mut Level,
                 state: usize)
    {
        let coord1 = self.player_one.coord.clone();
        let mut coord2 = coord1.clone();

        if let Some(ref p2) = self.player_two {
            coord2 = p2.coord.clone();
        }

        let range = self.cam.get_range_update();

        self.player_one.on_update(args, range, level, InteractableType::Player(1));

        if let Some(ref mut x) = self.player_two {
            x.on_update(args, range, level, InteractableType::Player(2));
        }

        for b in &mut self.bots {
            b.on_update(args, range, level, state);
        }

        self.cam.calc_coordinates(coord1, coord2, level);
    }

    fn on_input(&mut self, inp: Button, pressed: bool) {

        match inp {
            Button::Keyboard(Key::Up) => {
                if pressed {
                    self.player_one.last = LastKey::Up;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::Down) => {
                if pressed {
                    self.player_one.last = LastKey::Down;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::Left) => {
                if pressed {
                    self.player_one.last = LastKey::Left;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::Right) => {
                if pressed {
                    self.player_one.last = LastKey::Right;
                }
                self.player_one.pressed = pressed;
            }
            Button::Keyboard(Key::W) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Up;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::S) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Down;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::A) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Left;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::D) => {
                if let Some(ref mut x) = self.player_two {
                    if pressed {
                        x.last = LastKey::Right;
                    }
                    x.pressed = pressed;
                }
            }
            Button::Keyboard(Key::Space) => {
                if pressed {
                    println!("Space!!!");
                }
            }
            _ => {}

        }
    }
}

fn main() {
    let mut window: PistonWindow = WindowSettings::new("Chicken Fight 3000 Ultimate Tournament",
                                                       [WIDTH as u32, HEIGHT as u32])
        .exit_on_esc(true)
        .fullscreen(false)
        .resizable(false)
        .build()
        .unwrap();

    // Create a new game and run it.

    let mut app = App::new(TWO_PLAYER);

    let mut events = window.events();

    let tiles = match find_folder::Search::Kids(1).for_folder("tiles") {
        Ok(res) => res.join("tileset-pokemon_dawn.png"),
        Err(_) => panic!("Folder 'tiles' not found!"),
    };

    let file_path = match tiles.to_str() {
        Some(res) => res,
        None => panic!("Tileset not found!"),
    };

    let folder_level = match find_folder::Search::Kids(0).for_folder("src") {
        Ok(res) => res.join("level1.lvl"),
        Err(_) => panic!("Folder 'src' not found!"),
    };

    let level_path = match folder_level.to_str() {
        Some(res) => res,
        None => panic!("Level not found!"),
    };

    let tileset = io::read_tileset(file_path, &mut window);

    let mut level = io::read_level(level_path);

    // insert players in level
    level.get_data()[app.player_one.coord.get_x() as usize][app.player_one.coord.get_y() as usize].set_fieldstatus(InteractableType::Player(1));
    if let Some(ref p2) = app.player_two {
        level.get_data()[p2.coord.get_x() as usize][p2.coord.get_y() as usize].set_fieldstatus(InteractableType::Player(2));
    }

    let mut start = PreciseTime::now();
    app.cam.set_borders((level.get_width() as u64, level.get_height()as u64));
    app.player_one.set_sprite(Sprite::fill_sprite("knight.png",2,1,64,64,&mut window));

    if let Some(ref mut p2) = app.player_two {
        p2.set_borders((level.get_width() as u64, level.get_height() as u64));
        p2.set_sprite(Sprite::fill_sprite("paladin.png", 2, 1, 64, 64, &mut window));
    }
    let mut i = 0;
    for b in &mut app.bots {

        let file = if i %3 == 0 {"chicken_pink.png"} else if i% 3 == 1 {"chicken_brown.png"} else {"chicken_white.png"};
        b.set_sprite(Sprite::fill_sprite(file,2,1,64,64,&mut window));
        b.set_borders((level.get_width() as u64, level.get_height()as u64));
        i = i +1;
    }

    while let Some(e) = events.next(&mut window) {
        let now = start.to(PreciseTime::now()).num_milliseconds();
        if now > 1000 {
            start = PreciseTime::now();
        }
        let state = if now <= 500 { 0 } else { 1 };

        if let Some(_) = e.render_args() {
            app.on_draw(&mut window, &e, &tileset, &mut level, state);
        }
        if let Some(i) = e.release_args() {
            app.on_input(i, false);
        }
        if let Some(i) = e.press_args() {
            app.on_input(i, true);
        }

        if let Some(u) = e.update_args() {
            app.on_update(&u, &mut level, state);
        }
    }
}
<|endoftext|>


<commit_before>#![feature(net)]
#![feature(path)]
#![feature(fs)]
#![feature(io)]

extern crate nickel;
#[macro_use] extern crate nickel_macros;
extern crate mustache;

use std::collections::HashMap;
use std::net::IpAddr;
use nickel::*;
use std::path::PathBuf;
use std::fs::File;
use std::io::Read;
use mustache::*;

fn main() {

   let mut nickel = Nickel::new();

   nickel.utilize(StaticFilesHandler::new("public/"));

   nickel.utilize(middleware! { |request|
     println!("Request: {:?}", request.origin.uri);
     });

   nickel.utilize(router!(

   get "**" => |request, response| {
      let mut data = HashMap::new();
      data.insert("title".to_string(), StrVal("nickel-bootstrap".to_string()));
      data.insert("message".to_string(), StrVal("hello from nickel bootstrap!".to_string()));

      let template_file = "templates/all_for_one.mustache";

      let mut file = File::open(&PathBuf::new(template_file))
                          .ok()
                          .expect(&*format!("Couldn't open template: {}", template_file));

      let mut raw_template = String::new();
      file.read_to_string(&mut raw_template)
          .ok()
          .expect(&*format!("Couldn't read template file: {}", template_file));

      let template = mustache::compile_str(&*raw_template);

      let mut resp = vec![];
      template.render_data(&mut resp, &Map(data));
      String::from_utf8(resp).unwrap()
   }

   ));

   nickel.listen(IpAddr::new_v4(127,0,0,1), 6767);
}
<commit_msg>changed welcome message. Still.. nerd alert<commit_after>#![feature(net)]
#![feature(path)]
#![feature(fs)]
#![feature(io)]

extern crate nickel;
#[macro_use] extern crate nickel_macros;
extern crate mustache;

use std::collections::HashMap;
use std::net::IpAddr;
use nickel::*;
use std::path::PathBuf;
use std::fs::File;
use std::io::Read;
use mustache::*;

fn main() {

   let mut nickel = Nickel::new();

   nickel.utilize(StaticFilesHandler::new("public/"));

   nickel.utilize(middleware! { |request|
     println!("Request: {:?}", request.origin.uri);
     });

   nickel.utilize(router!(

   get "**" => |request, response| {
      let mut data = HashMap::new();
      data.insert("title".to_string(), StrVal("nickel-bootstrap".to_string()));
      data.insert("message".to_string(), StrVal("Welcome to nickel-bootstrap!".to_string()));

      let template_file = "templates/all_for_one.mustache";

      let mut file = File::open(&PathBuf::new(template_file))
                          .ok()
                          .expect(&*format!("Couldn't open template: {}", template_file));

      let mut raw_template = String::new();
      file.read_to_string(&mut raw_template)
          .ok()
          .expect(&*format!("Couldn't read template file: {}", template_file));

      let template = mustache::compile_str(&*raw_template);

      let mut resp = vec![];
      template.render_data(&mut resp, &Map(data));
      String::from_utf8(resp).unwrap()
   }

   ));

   nickel.listen(IpAddr::new_v4(127,0,0,1), 6767);
}
<|endoftext|>


<commit_before>use std::io::{self, BufReader};
use std::io::BufRead;
use std::fs::File;
extern crate time;
use time::Tm;
use time::strptime;
use time::Duration;
extern crate stats;
use stats::median;
extern crate clap;
use clap::{Arg, App};

mod percentile;
use percentile::percentile;

mod http_status;
use http_status::HttpStatus;

#[derive(Eq, PartialEq, Clone)]
#[derive(Debug)]
pub struct Request {
    id: i32,
    time: Tm,
    url: String,
}

impl Request {
    fn new_from_log_line(log_line: &String) -> Result<Request, io::Error> {
        let parts: Vec<&str> = log_line.split(" ").collect();

        let id = parts[2];
        let url = parts[5];

        Ok(Request {
            id: id[1..id.len()-1].parse().unwrap(),
            time: strptime(parts[0], "%d/%b/%Y:%H:%M:%S").unwrap(),
            url: url.to_string()
        })
    }

    fn get_matching_response<'a>(&'a self, responses: &'a Vec<Response>) -> Option<&Response> {
        for response in responses {
            if self.id == response.id {
                return Some(response)
            }
        }

        None
    }
}

#[derive(Eq, PartialEq, Clone)]
#[derive(Debug)]
pub struct Response {
    id: i32,
    time: Tm,
    mime_type: String,
    response_time: Duration,
    http_status: HttpStatus,
}

impl Response {
    fn new_from_log_line(log_line: &String) -> Result<Response, io::Error> {
        let parts: Vec<&str> = log_line.split(" ").collect();

        let id = parts[2];
        let response_time = parts[parts.len()-1];
        let mime_type = parts[5];
        let status_code = parts[4];

        Ok(Response {
            id: id[1..id.len()-1].parse().unwrap(),
            time: strptime(parts[0], "%d/%b/%Y:%H:%M:%S").unwrap(),
            response_time: Duration::milliseconds(response_time[0..response_time.len()-2].parse().unwrap()),
            mime_type: mime_type.to_string(),
            http_status: HttpStatus::from_code(status_code.parse().unwrap()),
        })
    }
}

pub fn open_logfile(path: &str) -> Result<(Vec<Request>,Vec<Response>), io::Error> {
    let f = try!(File::open(path));

    let f = BufReader::new(f);

    let mut requests: Vec<Request> = Vec::new();
    let mut responses: Vec<Response> = Vec::new();

    for line in f.lines() {
        let line_value = &line.unwrap();

        if line_value.contains("->") {
            let r = try!(Request::new_from_log_line(&line_value));
            requests.push(r)
        }

        if line_value.contains("<-") {
            let r = try!(Response::new_from_log_line(&line_value));
            responses.push(r)
        }

    }

    Ok((requests, responses))
}

pub struct RequestResponsePair {
    request: Request,
    response: Response
}

pub fn pair_requests_responses(requests:Vec<Request>, responses: Vec<Response>) -> Vec<RequestResponsePair> {
    let mut request_response_pairs: Vec<RequestResponsePair> = Vec::new();

    for request in requests  {
        match request.get_matching_response(&responses) {
            Some(response) => request_response_pairs.push(RequestResponsePair{
                request: request.clone(),
                response: response.clone()
            }),
            None => println!("none"),
        }
    }

    request_response_pairs
}

#[derive(Eq, PartialEq)]
#[derive(Debug)]
pub struct RequestLogAnalyzerResult {
    count: usize,
    max: usize,
    min: usize,
    avg: usize,
    median: usize,
    percentile90: usize,
}

pub fn analyze(request_response_pairs: &Vec<RequestResponsePair>) -> RequestLogAnalyzerResult {
    let times: Vec<i64> = request_response_pairs.iter()
        .map(|rr: &RequestResponsePair| -> i64 {rr.response.response_time.num_milliseconds() })
        .collect();

    let sum: usize = times.iter().sum::<i64>() as usize;
    let avg: usize = sum / times.len();

    let max: usize = *times.iter().max().unwrap() as usize;
    let min: usize = *times.iter().min().unwrap() as usize;

    let percentile90: usize = percentile(&times, 0.9) as usize;

    let median = median(times.into_iter()).unwrap() as usize;

    RequestLogAnalyzerResult {
        count: request_response_pairs.len().into(),
        max: max,
        min: min,
        avg: avg,
        median: median,
        percentile90: percentile90,
    }
}

fn render_terminal(result: RequestLogAnalyzerResult) {
    println!("count:\t{}", result.count);
    println!("time.avg:\t{}", result.avg);
    println!("time.min:\t{}", result.min);
    println!("time.median:\t{}", result.median);
    println!("time.90percent:\t{}", result.percentile90);
    println!("time.max:\t{}", result.max);
}

fn main() {
    let matches = App::new("Request.log Analyzer")
        .arg(Arg::with_name("filename")
            .index(1)
            .value_name("FILE")
            .help("Log file to analyze")
            .takes_value(true))
            .get_matches();

    let filename = matches.value_of("filename").unwrap();

    let lines = open_logfile(filename);
    let (requests, responses) = lines.unwrap();

    let pairs: Vec<RequestResponsePair> = pair_requests_responses(requests, responses);

    let result: RequestLogAnalyzerResult = analyze(&pairs);

    render_terminal(result);
}

#[cfg(test)]
mod tests {
	use super::*;
    extern crate time;
    use time::strptime;
    use::time::Duration;
    use http_status::HttpStatus;

    #[test]
    fn test_parse_request_line() {
        let line = "08/Apr/2016:09:58:47 +0200 [02] -> GET /content/some/other.html HTTP/1.1".to_string();

        let expected = Request {
            id: 2,
            time: strptime("08/Apr/2016:09:58:47 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            url: "/content/some/other.html".to_string()
        };

        let result = Request::new_from_log_line(&line);

        assert_eq!(result.unwrap(), expected)
    }

    #[test]
    fn test_parse_response_line() {
        let line = "08/Apr/2016:09:58:48 +0200 [02] <- 200 text/html 10ms".to_string();

        let expected = Response {
            id: 2,
            time: strptime("08/Apr/2016:09:58:48 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            mime_type: "text/html".to_string(),
            response_time: Duration::milliseconds(10),
            http_status: HttpStatus::OK,
        };

        let result = Response::new_from_log_line(&line);

        assert_eq!(result.unwrap(), expected)
    }

    #[test]
    fn test_open_logfile() {
        let lines = open_logfile("src/test/simple-1.log");
        let (requests, responses) = lines.unwrap();

        assert_eq!(requests.len(), 2);
        assert_eq!(responses.len(), 2);
    }

    #[test]
    fn test_get_matching_response() {
        let lines = open_logfile("src/test/simple-1.log");
        let (requests, responses) = lines.unwrap();

        let result = requests[0].get_matching_response(&responses);

        let expected = Response {
            id: 1,
            time: strptime("08/Apr/2016:09:57:47 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            mime_type: "text/html".to_string(),
            response_time: Duration::milliseconds(7),
            http_status: HttpStatus::OK,
        };

        assert_eq!(*result.unwrap(), expected);
    }

    #[test]
    fn test_get_matching_response_none_found() {
        let lines = open_logfile("src/test/simple-1.log");
        let (_, responses) = lines.unwrap();

        let request_without_matching = Request {
            id: 999,
            time: strptime("08/Apr/2016:09:58:47 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            url: "/content/some/other.html".to_string()
        };

        let result = request_without_matching.get_matching_response(&responses);

        assert!(result.is_none());
    }

    #[test]
    fn test_pair_requests_resonses() {
        let lines = open_logfile("src/test/simple-1.log");
        let (requests, responses) = lines.unwrap();

        let result = pair_requests_responses(requests, responses);

        assert_eq!(result.len(), 2);

        assert_eq!(result[0].request.id, result[0].response.id);
        assert_eq!(result[1].request.id, result[1].response.id);
    }

    #[test]
    fn test_request_log_analyzer_result() {
        let lines = open_logfile("src/test/response-time-calculations.log");
        let (requests, responses) = lines.unwrap();

        let request_response_pairs = pair_requests_responses(requests, responses);

        let result: RequestLogAnalyzerResult = analyze(&request_response_pairs);

        let expected = RequestLogAnalyzerResult {
            count: 3,
            max: 100,
            min: 1,
            avg: 37,
            median: 10,
            percentile90: 100,
        };

        assert_eq!(result, expected);
    }

    #[test]
    fn test_90_percentile_calculation() {
        let lines = open_logfile("src/test/percentile.log");
        let (requests, responses) = lines.unwrap();

        let request_response_pairs = pair_requests_responses(requests, responses);

        let result: RequestLogAnalyzerResult = analyze(&request_response_pairs);

        assert_eq!(result.percentile90, 9);
    }
}
<commit_msg>No need to print info about the unmatched lines<commit_after>use std::io::{self, BufReader};
use std::io::BufRead;
use std::fs::File;
extern crate time;
use time::Tm;
use time::strptime;
use time::Duration;
extern crate stats;
use stats::median;
extern crate clap;
use clap::{Arg, App};

mod percentile;
use percentile::percentile;

mod http_status;
use http_status::HttpStatus;

#[derive(Eq, PartialEq, Clone)]
#[derive(Debug)]
pub struct Request {
    id: i32,
    time: Tm,
    url: String,
}

impl Request {
    fn new_from_log_line(log_line: &String) -> Result<Request, io::Error> {
        let parts: Vec<&str> = log_line.split(" ").collect();

        let id = parts[2];
        let url = parts[5];

        Ok(Request {
            id: id[1..id.len()-1].parse().unwrap(),
            time: strptime(parts[0], "%d/%b/%Y:%H:%M:%S").unwrap(),
            url: url.to_string()
        })
    }

    fn get_matching_response<'a>(&'a self, responses: &'a Vec<Response>) -> Option<&Response> {
        for response in responses {
            if self.id == response.id {
                return Some(response)
            }
        }

        None
    }
}

#[derive(Eq, PartialEq, Clone)]
#[derive(Debug)]
pub struct Response {
    id: i32,
    time: Tm,
    mime_type: String,
    response_time: Duration,
    http_status: HttpStatus,
}

impl Response {
    fn new_from_log_line(log_line: &String) -> Result<Response, io::Error> {
        let parts: Vec<&str> = log_line.split(" ").collect();

        let id = parts[2];
        let response_time = parts[parts.len()-1];
        let mime_type = parts[5];
        let status_code = parts[4];

        Ok(Response {
            id: id[1..id.len()-1].parse().unwrap(),
            time: strptime(parts[0], "%d/%b/%Y:%H:%M:%S").unwrap(),
            response_time: Duration::milliseconds(response_time[0..response_time.len()-2].parse().unwrap()),
            mime_type: mime_type.to_string(),
            http_status: HttpStatus::from_code(status_code.parse().unwrap()),
        })
    }
}

pub fn open_logfile(path: &str) -> Result<(Vec<Request>,Vec<Response>), io::Error> {
    let f = try!(File::open(path));

    let f = BufReader::new(f);

    let mut requests: Vec<Request> = Vec::new();
    let mut responses: Vec<Response> = Vec::new();

    for line in f.lines() {
        let line_value = &line.unwrap();

        if line_value.contains("->") {
            let r = try!(Request::new_from_log_line(&line_value));
            requests.push(r)
        }

        if line_value.contains("<-") {
            let r = try!(Response::new_from_log_line(&line_value));
            responses.push(r)
        }

    }

    Ok((requests, responses))
}

pub struct RequestResponsePair {
    request: Request,
    response: Response
}

pub fn pair_requests_responses(requests:Vec<Request>, responses: Vec<Response>) -> Vec<RequestResponsePair> {
    let mut request_response_pairs: Vec<RequestResponsePair> = Vec::new();

    for request in requests  {
        if let Some(response) = request.get_matching_response(&responses) {
            request_response_pairs.push(RequestResponsePair{
                request: request.clone(),
                response: response.clone()
            })
        }
    }

    request_response_pairs
}

#[derive(Eq, PartialEq)]
#[derive(Debug)]
pub struct RequestLogAnalyzerResult {
    count: usize,
    max: usize,
    min: usize,
    avg: usize,
    median: usize,
    percentile90: usize,
}

pub fn analyze(request_response_pairs: &Vec<RequestResponsePair>) -> RequestLogAnalyzerResult {
    let times: Vec<i64> = request_response_pairs.iter()
        .map(|rr: &RequestResponsePair| -> i64 {rr.response.response_time.num_milliseconds() })
        .collect();

    let sum: usize = times.iter().sum::<i64>() as usize;
    let avg: usize = sum / times.len();

    let max: usize = *times.iter().max().unwrap() as usize;
    let min: usize = *times.iter().min().unwrap() as usize;

    let percentile90: usize = percentile(&times, 0.9) as usize;

    let median = median(times.into_iter()).unwrap() as usize;

    RequestLogAnalyzerResult {
        count: request_response_pairs.len().into(),
        max: max,
        min: min,
        avg: avg,
        median: median,
        percentile90: percentile90,
    }
}

fn render_terminal(result: RequestLogAnalyzerResult) {
    println!("count:\t{}", result.count);
    println!("time.avg:\t{}", result.avg);
    println!("time.min:\t{}", result.min);
    println!("time.median:\t{}", result.median);
    println!("time.90percent:\t{}", result.percentile90);
    println!("time.max:\t{}", result.max);
}

fn main() {
    let matches = App::new("Request.log Analyzer")
        .arg(Arg::with_name("filename")
            .index(1)
            .value_name("FILE")
            .help("Log file to analyze")
            .takes_value(true))
            .get_matches();

    let filename = matches.value_of("filename").unwrap();

    let lines = open_logfile(filename);
    let (requests, responses) = lines.unwrap();

    let pairs: Vec<RequestResponsePair> = pair_requests_responses(requests, responses);

    let result: RequestLogAnalyzerResult = analyze(&pairs);

    render_terminal(result);
}

#[cfg(test)]
mod tests {
	use super::*;
    extern crate time;
    use time::strptime;
    use::time::Duration;
    use http_status::HttpStatus;

    #[test]
    fn test_parse_request_line() {
        let line = "08/Apr/2016:09:58:47 +0200 [02] -> GET /content/some/other.html HTTP/1.1".to_string();

        let expected = Request {
            id: 2,
            time: strptime("08/Apr/2016:09:58:47 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            url: "/content/some/other.html".to_string()
        };

        let result = Request::new_from_log_line(&line);

        assert_eq!(result.unwrap(), expected)
    }

    #[test]
    fn test_parse_response_line() {
        let line = "08/Apr/2016:09:58:48 +0200 [02] <- 200 text/html 10ms".to_string();

        let expected = Response {
            id: 2,
            time: strptime("08/Apr/2016:09:58:48 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            mime_type: "text/html".to_string(),
            response_time: Duration::milliseconds(10),
            http_status: HttpStatus::OK,
        };

        let result = Response::new_from_log_line(&line);

        assert_eq!(result.unwrap(), expected)
    }

    #[test]
    fn test_open_logfile() {
        let lines = open_logfile("src/test/simple-1.log");
        let (requests, responses) = lines.unwrap();

        assert_eq!(requests.len(), 2);
        assert_eq!(responses.len(), 2);
    }

    #[test]
    fn test_get_matching_response() {
        let lines = open_logfile("src/test/simple-1.log");
        let (requests, responses) = lines.unwrap();

        let result = requests[0].get_matching_response(&responses);

        let expected = Response {
            id: 1,
            time: strptime("08/Apr/2016:09:57:47 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            mime_type: "text/html".to_string(),
            response_time: Duration::milliseconds(7),
            http_status: HttpStatus::OK,
        };

        assert_eq!(*result.unwrap(), expected);
    }

    #[test]
    fn test_get_matching_response_none_found() {
        let lines = open_logfile("src/test/simple-1.log");
        let (_, responses) = lines.unwrap();

        let request_without_matching = Request {
            id: 999,
            time: strptime("08/Apr/2016:09:58:47 +0200", "%d/%b/%Y:%H:%M:%S").unwrap(),
            url: "/content/some/other.html".to_string()
        };

        let result = request_without_matching.get_matching_response(&responses);

        assert!(result.is_none());
    }

    #[test]
    fn test_pair_requests_resonses() {
        let lines = open_logfile("src/test/simple-1.log");
        let (requests, responses) = lines.unwrap();

        let result = pair_requests_responses(requests, responses);

        assert_eq!(result.len(), 2);

        assert_eq!(result[0].request.id, result[0].response.id);
        assert_eq!(result[1].request.id, result[1].response.id);
    }

    #[test]
    fn test_request_log_analyzer_result() {
        let lines = open_logfile("src/test/response-time-calculations.log");
        let (requests, responses) = lines.unwrap();

        let request_response_pairs = pair_requests_responses(requests, responses);

        let result: RequestLogAnalyzerResult = analyze(&request_response_pairs);

        let expected = RequestLogAnalyzerResult {
            count: 3,
            max: 100,
            min: 1,
            avg: 37,
            median: 10,
            percentile90: 100,
        };

        assert_eq!(result, expected);
    }

    #[test]
    fn test_90_percentile_calculation() {
        let lines = open_logfile("src/test/percentile.log");
        let (requests, responses) = lines.unwrap();

        let request_response_pairs = pair_requests_responses(requests, responses);

        let result: RequestLogAnalyzerResult = analyze(&request_response_pairs);

        assert_eq!(result.percentile90, 9);
    }
}
<|endoftext|>


<commit_before>mod element;

use element::*;

fn main() {
    // init hardcoded NAND component
    let nand = Block::init_nand();
    // init user NOT component (composit)
    let mut not = Block::init("NOT", 1, 1);
    // push NAND component into NOT
    let nand_id = not.push_element(nand);
    // connect all wires
    not.connect_wire(Wire::InputSelf(0), Wire::Input(nand_id, 0));
    not.connect_wire(Wire::InputSelf(0), Wire::Input(nand_id, 1));
    not.connect_wire(Wire::Output(nand_id, 0), Wire::OutputSelf(0));
    for input in 0..2 {
        // set value for input wire
        not.set_input_wire(0, input);
        // calculating
        not.execute();
        println!("NOT: {:?}", not);
    }
}<commit_msg>[add] AND & OR components<commit_after>mod element;

use element::*;

// NOT X = X NAND X
fn init_not() -> Block {
    // init hardcoded NAND component
    let nand = Block::init_nand();
    // init user NOT component (composit)
    let mut not = Block::init("NOT", 1, 1);
    // push NAND component into NOT
    let nand_id = not.push_element(nand);
    // connect all wires
    not.connect_wire(Wire::InputSelf(0), Wire::Input(nand_id, 0));
    not.connect_wire(Wire::InputSelf(0), Wire::Input(nand_id, 1));
    not.connect_wire(Wire::Output(nand_id, 0), Wire::OutputSelf(0));
    not
}

//              A     B     C
// X AND Y = (NOT X) NOR (NOT Y)
fn init_and() -> Block {
    let not_a = init_not();
    let not_b = init_not();
    let nor = Block::init_nor();
    // init user AND component
    let mut and = Block::init("AND", 2, 1);
    // push all components
    let nid = and.push_element(nor);
    let aid = and.push_element(not_a);
    let bid = and.push_element(not_b);
    // connect A
    and.connect_wire(Wire::InputSelf(0), Wire::Input(aid, 0));
    // connect C
    and.connect_wire(Wire::InputSelf(1), Wire::Input(bid, 0));
    // connect B
    and.connect_wire(Wire::Output(aid, 0), Wire::Input(nid, 0));
    and.connect_wire(Wire::Output(bid, 0), Wire::Input(nid, 1));
    // result to output
    and.connect_wire(Wire::Output(nid, 0), Wire::OutputSelf(0));
    and
}

//             A     B      C
// X OR Y = (NOT X) NAND (NOT Y)
fn init_or() -> Block {
    let not_a = init_not();
    let not_b = init_not();
    let nand = Block::init_nand();
    // init user OR component
    let mut or = Block::init("OR", 2, 1);
    // push all components
    let nid = or.push_element(nand);
    let aid = or.push_element(not_a);
    let bid = or.push_element(not_b);
    // connect A
    or.connect_wire(Wire::InputSelf(0), Wire::Input(aid, 0));
    // connect C
    or.connect_wire(Wire::InputSelf(1), Wire::Input(bid, 0));
    // connect B
    or.connect_wire(Wire::Output(aid, 0), Wire::Input(nid, 0));
    or.connect_wire(Wire::Output(bid, 0), Wire::Input(nid, 1));
    // result to output
    or.connect_wire(Wire::Output(nid, 0), Wire::OutputSelf(0));
    or
}

fn main() {
    let mut and = init_and();
    println!("AND component:");
    for (w1, w2) in vec![(0, 0), (0, 1), (1, 0), (1, 1)] {
        and.set_input_wire(0, w1);
        and.set_input_wire(1, w2);
        and.execute();
        println!("{:?}", and);
    }
    let mut or = init_or();
    println!("OR component:");
    for (w1, w2) in vec![(0, 0), (0, 1), (1, 0), (1, 1)] {
        or.set_input_wire(0, w1);
        or.set_input_wire(1, w2);
        or.execute();
        println!("{:?}", or);
    }
}<|endoftext|>


<commit_before>use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::fs::File;

extern crate chrono;
use chrono::*;

extern crate stats;

extern crate clap;
use clap::{Arg, App, ArgMatches};

mod http_status;
mod log_parser;
use log_parser::log_events::*;
mod request_response_matcher;
use request_response_matcher::*;
mod filter;
mod analyzer;
mod render;

// http://stackoverflow.com/a/27590832/376138
macro_rules! println_stderr(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

fn parse_args<'a>() -> ArgMatches<'a> {
    App::new("Request.log Analyzer")
        .arg(Arg::with_name("filename")
            .index(1)
            .value_name("FILE")
            .required(false)
            .help("Log file to analyze, defaults to stdin")
            .takes_value(true))
        .arg(Arg::with_name("time_filter_minutes")
            .value_name("MINUTES")
            .short("t")
            .help("Limit to the last n minutes")
            .takes_value(true))
        .arg(Arg::with_name("include_term")
            .value_name("TERM")
            .long("include")
            .help("Only includes lines that contain this term")
            .takes_value(true))
        .arg(Arg::with_name("exclude_term")
            .value_name("TERM")
            .long("exclude")
            .help("Excludes lines that contain this term")
            .takes_value(true))
        .arg(Arg::with_name("graphite-server")
            .value_name("GRAPHITE_SERVER")
            .long("graphite-server")
            .help("Send values to this Graphite server instead of stdout")
            .takes_value(true))
        .arg(Arg::with_name("graphite-port")
            .value_name("GRAPHITE_PORT")
            .long("graphite-port")
            .takes_value(true)
            .default_value("2003"))
        .arg(Arg::with_name("graphite-prefix")
            .value_name("GRAPHITE_PREFIX")
            .long("graphite-prefix")
            .help("Prefix for Graphite key, e.g. 'servers.prod.publisher1'")
            .takes_value(true))
        .get_matches()
}

fn main() {
    let args = parse_args();

    let filename = args.value_of("filename").unwrap_or("-");

    let time_filter = match args.value_of("time_filter_minutes") {
        Some(minutes) => Some(Duration::minutes(minutes.parse().unwrap())),
        None => None
    };

    let conditions = filter::FilterConditions {
        include_terms: match args.value_of("include_term") {
            Some(value) => Some(vec![value.to_string()]),
            None => None
        },
        exclude_terms: match args.value_of("exclude_term") {
            Some(value) => Some(vec![value.to_string()]),
            None => None
        },
        latest_time: time_filter,
    };

    let mut input: Box<io::Read> = match filename {
        "-" => Box::new(io::stdin()),
        _ => Box::new(File::open(filename).unwrap())
    };

    let reader = io::BufReader::new(input);
    let lines = reader.lines();

    let mut requests: Vec<Request> = Vec::new();
    let mut responses: Vec<Response> = Vec::new();
    let mut times: Vec<i64> = Vec::new();

    // We need to store 1 Request in order to determine the timezone later
    let mut first_request: Option<Request> = None;

    for line in lines {
        let line_value = &line.unwrap();

        if line_value.contains("->") {
            match Request::new_from_log_line(&line_value) {
                Ok(r) => {
                    if first_request.is_none() {
                        first_request = Some(r.clone());
                    }
                    requests.push(r);
                },
                Err(err) => println_stderr!("Skipped a line: {}", err)
            }
        }

        if line_value.contains("<-") {
            match Response::new_from_log_line(&line_value) {
                Ok(r) => responses.push(r),
                Err(err) => println_stderr!("Skipped a line: {}", err)
            }
        }

        let pairs = extract_matching_request_response_pairs(&mut requests, &mut responses);

        let mut new_times: Vec<i64> = pairs.iter()
            .filter(|pair| filter::matches_filter(&pair, &conditions) )
            .map(|pair| pair.response.response_time.num_milliseconds())
            .collect();

        times.append(&mut new_times);
    }

    let result = analyzer::analyze(&times);

    match result {
        Some(result) => {
            if args.is_present("graphite-server") {
                let stream = TcpStream::connect(
                    (
                        args.value_of("graphite-server").unwrap(),
                        args.value_of("graphite-port").unwrap().parse().unwrap()
                    )
                ).expect("Could not connect to the Graphite server");

                let timezone = first_request.unwrap().time.timezone();

                render::render_graphite(result, UTC::now().with_timezone(&timezone), args.value_of("graphite-prefix"), stream);
            } else {
                render::render_terminal(result);
            }
        },
        None => println_stderr!("No matching log lines in file.")
    }
}
<commit_msg>Variable does not need to be mutable<commit_after>use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::fs::File;

extern crate chrono;
use chrono::*;

extern crate stats;

extern crate clap;
use clap::{Arg, App, ArgMatches};

mod http_status;
mod log_parser;
use log_parser::log_events::*;
mod request_response_matcher;
use request_response_matcher::*;
mod filter;
mod analyzer;
mod render;

// http://stackoverflow.com/a/27590832/376138
macro_rules! println_stderr(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

fn parse_args<'a>() -> ArgMatches<'a> {
    App::new("Request.log Analyzer")
        .arg(Arg::with_name("filename")
            .index(1)
            .value_name("FILE")
            .required(false)
            .help("Log file to analyze, defaults to stdin")
            .takes_value(true))
        .arg(Arg::with_name("time_filter_minutes")
            .value_name("MINUTES")
            .short("t")
            .help("Limit to the last n minutes")
            .takes_value(true))
        .arg(Arg::with_name("include_term")
            .value_name("TERM")
            .long("include")
            .help("Only includes lines that contain this term")
            .takes_value(true))
        .arg(Arg::with_name("exclude_term")
            .value_name("TERM")
            .long("exclude")
            .help("Excludes lines that contain this term")
            .takes_value(true))
        .arg(Arg::with_name("graphite-server")
            .value_name("GRAPHITE_SERVER")
            .long("graphite-server")
            .help("Send values to this Graphite server instead of stdout")
            .takes_value(true))
        .arg(Arg::with_name("graphite-port")
            .value_name("GRAPHITE_PORT")
            .long("graphite-port")
            .takes_value(true)
            .default_value("2003"))
        .arg(Arg::with_name("graphite-prefix")
            .value_name("GRAPHITE_PREFIX")
            .long("graphite-prefix")
            .help("Prefix for Graphite key, e.g. 'servers.prod.publisher1'")
            .takes_value(true))
        .get_matches()
}

fn main() {
    let args = parse_args();

    let filename = args.value_of("filename").unwrap_or("-");

    let time_filter = match args.value_of("time_filter_minutes") {
        Some(minutes) => Some(Duration::minutes(minutes.parse().unwrap())),
        None => None
    };

    let conditions = filter::FilterConditions {
        include_terms: match args.value_of("include_term") {
            Some(value) => Some(vec![value.to_string()]),
            None => None
        },
        exclude_terms: match args.value_of("exclude_term") {
            Some(value) => Some(vec![value.to_string()]),
            None => None
        },
        latest_time: time_filter,
    };

    let input: Box<io::Read> = match filename {
        "-" => Box::new(io::stdin()),
        _ => Box::new(File::open(filename).unwrap())
    };

    let reader = io::BufReader::new(input);
    let lines = reader.lines();

    let mut requests: Vec<Request> = Vec::new();
    let mut responses: Vec<Response> = Vec::new();
    let mut times: Vec<i64> = Vec::new();

    // We need to store 1 Request in order to determine the timezone later
    let mut first_request: Option<Request> = None;

    for line in lines {
        let line_value = &line.unwrap();

        if line_value.contains("->") {
            match Request::new_from_log_line(&line_value) {
                Ok(r) => {
                    if first_request.is_none() {
                        first_request = Some(r.clone());
                    }
                    requests.push(r);
                },
                Err(err) => println_stderr!("Skipped a line: {}", err)
            }
        }

        if line_value.contains("<-") {
            match Response::new_from_log_line(&line_value) {
                Ok(r) => responses.push(r),
                Err(err) => println_stderr!("Skipped a line: {}", err)
            }
        }

        let pairs = extract_matching_request_response_pairs(&mut requests, &mut responses);

        let mut new_times: Vec<i64> = pairs.iter()
            .filter(|pair| filter::matches_filter(&pair, &conditions) )
            .map(|pair| pair.response.response_time.num_milliseconds())
            .collect();

        times.append(&mut new_times);
    }

    let result = analyzer::analyze(&times);

    match result {
        Some(result) => {
            if args.is_present("graphite-server") {
                let stream = TcpStream::connect(
                    (
                        args.value_of("graphite-server").unwrap(),
                        args.value_of("graphite-port").unwrap().parse().unwrap()
                    )
                ).expect("Could not connect to the Graphite server");

                let timezone = first_request.unwrap().time.timezone();

                render::render_graphite(result, UTC::now().with_timezone(&timezone), args.value_of("graphite-prefix"), stream);
            } else {
                render::render_terminal(result);
            }
        },
        None => println_stderr!("No matching log lines in file.")
    }
}
<|endoftext|>


<commit_before>fn main() {
    let player = Player {name: "DragonMaster385", ..Default::default()};
    player.display_stats();
    player.level_up();
}

struct Player<'a> {
    name: &'a str,
    health: u8,
    attack: u8,
    stamina: u8,
    dexterity: u8,
    mana: u8,
    vitality: u8,
    defense: u8,
    points: u8,
}

impl<'a> Default for Player<'a> {
    fn default () -> Player<'a> {
      Player {
          name: "Player",
          health: 100,
          attack: 5,
          stamina: 100,
          dexterity: 100,
          mana: 100,
          vitality: 100,
          defense: 100,
          points: 8}
    }
}

trait PlayerFunctionality {
    fn display_stats(&self);
    fn level_up(&self);
}

impl<'a> PlayerFunctionality for Player<'a> {
    fn display_stats(&self) {
        println!("Name:      {}", &self.name);
        println!("Health:    {}", &self.health);
        println!("Attack:    {}", &self.attack);
        println!("Stamina:   {}", &self.stamina);
        println!("Dexterity: {}", &self.dexterity);
        println!("Mana:      {}", &self.mana);
        println!("Vitality:  {}", &self.vitality);
        println!("Defense    {}", &self.defense);
        println!("Points:    {}", &self.points);
    }
    fn level_up(&self) {
        println!("Level up points to spend: {}", &self.points)
    }
}
<commit_msg>Added level_up() functionality<commit_after>use std::io;

fn main() {
    let mut player = Player {name: "DragonMaster385", ..Default::default()};
    player.level_up();
    player.display_all_stats();
}

struct Player<'a> {
    name: &'a str,
    health: i8,
    attack: i8,
    stamina: i8,
    dexterity: i8,
    mana: i8,
    vitality: i8,
    defense: i8,
    points: i8,
}

impl<'a> Default for Player<'a> {
    fn default () -> Player<'a> {
      Player {
          name: "Player",
          health: 100,
          attack: 5,
          stamina: 100,
          dexterity: 100,
          mana: 100,
          vitality: 100,
          defense: 100,
          points: 8}
    }
}

trait PlayerFunctionality {
    fn display_all_stats(&self);
    fn display_core_stats(&self);
    fn level_up(&mut self);
}

impl<'a> PlayerFunctionality for Player<'a> {
    fn display_all_stats(&self) {
        println!("Name:      {}", &self.name);
        println!("Health:    {}", &self.health);
        println!("Attack:    {}", &self.attack);
        println!("Stamina:   {}", &self.stamina);
        println!("Dexterity: {}", &self.dexterity);
        println!("Mana:      {}", &self.mana);
        println!("Vitality:  {}", &self.vitality);
        println!("Defense    {}", &self.defense);
        println!("Points:    {}", &self.points);
    }
    fn display_core_stats(&self) {
        println!("1. Health:    {}", &self.health);
        println!("2. Attack:    {}", &self.attack);
        println!("3. Stamina:   {}", &self.stamina);
        println!("4. Dexterity: {}", &self.dexterity);
        println!("5. Mana:      {}", &self.mana);
        println!("6. Vitality:  {}", &self.vitality);
        println!("7. Defense    {}", &self.defense);
    }
    fn level_up(&mut self) {
        if &self.points == &0 {
            println!("You don't have any point's to spend leveling up.");
        } else {
            println!("Level up points to spend: {}", &self.points);
            &self.display_core_stats();
            println!("Stat to level up? (1-7)");
            loop {
            let mut input = String::new();
                match io::stdin().read_line(&mut input) {
                      Ok(_)   => {
                          let input: i8 = match input.trim().parse() {
                              Ok(i)  => i,
                              Err(_) => {
                                  println!("Can't parse {}", &input);
                                  continue;
                              }
                          };
                          match input {

                              1 => {
                                  println!("Increase Health stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.health = &self.health + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }

                              2 => {
                                  println!("Increase Attack stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.attack = &self.attack + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }

                              3 => {
                                  println!("Increase Stamina stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.stamina = &self.stamina + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }

                              4 => {
                                  println!("Increase Dexterity stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.dexterity = &self.dexterity + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }

                              5 => {
                                  println!("Increase Mana stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.mana = &self.mana + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }

                              6 => {
                                  println!("Increase Vitality stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.vitality = &self.vitality + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }

                              7 => {
                                  println!("Increase Defense stat by how much?");
                                  loop {
                                      let mut input = String::new();
                                          match io::stdin().read_line(&mut input) {
                                                Ok(_)   => {
                                                    let input: i8 = match input.trim().parse() {
                                                        Ok(i)  => i,
                                                        Err(_) => {
                                                            println!("Can't parse {}", &input);
                                                            continue;
                                                        }
                                                    };
                                                    if &input <= &self.points {
                                                        self.defense = &self.defense + &input;
                                                        self.points = &self.points - &input;
                                                        break;
                                                    } else {
                                                        println!("You can't spend points that you don't have.")
                                                    }
                                                }
                                          Err(_) => {
                                            println!("Can't parse {}", &input);
                                            continue;
                                          }
                                      }
                                  }
                                  break;
                              }
                              _ => {
                                  println!("{} is not a valid number (1-7)", &input);
                                  continue;
                              }
                          }
                      }

                      Err(_) => {
                        println!("Can't parse {}", &input);
                        continue;
                      }
                };
            }
        }
    }
}
<|endoftext|>