<commit_before>use bifrost::raft::client::{RaftClient, SubscriptionError};
use bifrost::raft::state_machine::master::ExecError;
use bifrost_hasher::hash_str;

use std::collections::HashMap;
use parking_lot::{RwLock};

use std::sync::{Arc};
use std::string::String;
use core::borrow::Borrow;
use super::types;

pub mod sm;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Schema {
    pub id: u32,
    pub name: String,
    pub key_field: Option<Vec<u64>>,
    pub str_key_field: Option<Vec<String>>,
    pub fields: Field
}

impl Schema {
    pub fn new(name: String, key_field: Option<Vec<String>>, fields: Field) -> Schema {
        Schema {
            id: 0,
            name: name,
            key_field: match key_field {
                None => None,
                Some(ref keys) => Some(keys
                    .iter()
                    .map(|f| hash_str(f))
                    .collect())             // field list into field ids
            },
            str_key_field: key_field,
            fields: fields
        }
    }
    pub fn new_with_id(id: u32, name: String, key_field: Option<Vec<String>>, fields: Field) -> Schema {
        let mut schema = Schema::new(name, key_field, fields);
        schema.id = id;
        schema
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Field {
    pub type_id: u32,
    pub nullable: bool,
    pub is_array: bool,
    pub sub_fields: Option<Vec<Field>>,
    pub name: String,
    pub name_id: u64,
}

impl Field {
    pub fn new<'a>(
        name: & 'a str,
        type_id: u32,
        nullable: bool,
        is_array: bool,
        sub_fields: Option<Vec<Field>>)
        -> Field {
        Field {
            name: name.to_string(),
            name_id: types::key_hash(name),
            type_id: type_id,
            nullable: nullable,
            is_array: is_array,
            sub_fields: sub_fields
        }
    }
}

pub struct SchemasMap {
    schema_map: HashMap<u32, Arc<Schema>>,
    name_map: HashMap<String, u32>,
    id_counter: u32,
}

pub struct SchemasServer {
    map: Arc<RwLock<SchemasMap>>,
    sm: Option<sm::client::SMClient>,
}

impl SchemasServer {
    pub fn new(raft_client: Option<&Arc<RaftClient>>) -> Result<SchemasServer, ExecError> {
        let map = Arc::new(RwLock::new(SchemasMap::new()));
        let sm = match raft_client {
            Some(raft) => {
                let m1 = map.clone();
                let m2 = map.clone();
                let sm = sm::client::SMClient::new(sm::DEFAULT_SM_ID, raft);
                let mut sm_data = sm.get_all()?.unwrap();
                {
                    let mut map = map.write();
                    for schema in sm_data {
                        map.new_schema(schema);
                    }
                }
                let _ = sm.on_schema_added(move |r| {
                    let mut m1 = m1.write();
                    m1.new_schema(r.unwrap());
                })?;
                let _ = sm.on_schema_deleted(move |r| {
                    let mut m2 = m2.write();
                    m2.del_schema(&r.unwrap());
                })?;
                Some(sm)
            },
            None => None
        };
        let schemas = SchemasServer {
            map: map,
            sm: sm
        };
        return Ok(schemas);
    }
    pub fn get(&self, id: &u32) -> Option<Arc<Schema>> {
        let m = self.map.read();
        m.get(id)
    }
    pub fn new_schema(&self, schema: Schema) { // for debug only
        let mut m = self.map.write();
        m.new_schema(schema)
    }
}

impl SchemasMap {
    pub fn new() -> SchemasMap {
        SchemasMap {
            schema_map: HashMap::new(),
            name_map: HashMap::new(),
            id_counter: 0,
        }
    }
    pub fn new_schema(&mut self, schema: Schema) {
        let name = schema.name.clone();
        let id = schema.id;
        self.schema_map.insert(id, Arc::new(schema.clone()));
        self.name_map.insert(name, id);
    }
    pub fn del_schema<'a>(&mut self, name: & 'a str) -> Result<(), ()> {
        if let Some(id) = self.name_map.get(&name.to_string()) {
            self.schema_map.remove(&id);
        }
        self.name_map.remove(&name.to_string());
        Ok(())
    }
    pub fn get_by_name<'a>(&self, name: & 'a str) -> Option<Arc<Schema>> {
        if let Some(id) = self.name_map.get(&name.to_string()) {
            return self.get(&id)
        }
        return None;
    }
    pub fn get(&self, id: &u32) -> Option<Arc<Schema>> {
        if let Some(schema) = self.schema_map.get(id) {
            return Some(schema.clone())
        }
        return None;
    }
    fn next_id(&mut self) -> u32 {
        self.id_counter += 1;
        while self.schema_map.contains_key(&self.id_counter) {
            self.id_counter += 1;
        }
        self.id_counter
    }
    fn get_all(&self) -> Vec<Schema> {
        self.schema_map
            .values()
            .map(|s_ref| {
                let arc = s_ref.clone();
                let r: &Schema = arc.borrow();
                r.clone()
            })
            .collect()
    }
    fn load_from_list(&mut self, data: &Vec<Schema>) {
         for schema in data {
             let id = schema.id;
             self.name_map.insert(schema.name.clone(), id);
             self.schema_map.insert(id, Arc::new(schema.clone()));
         }
    }
}<commit_msg>expose name to id function for schemas<commit_after>use bifrost::raft::client::{RaftClient, SubscriptionError};
use bifrost::raft::state_machine::master::ExecError;
use bifrost_hasher::hash_str;

use std::collections::HashMap;
use parking_lot::{RwLock};

use std::sync::{Arc};
use std::string::String;
use core::borrow::Borrow;
use super::types;

pub mod sm;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Schema {
    pub id: u32,
    pub name: String,
    pub key_field: Option<Vec<u64>>,
    pub str_key_field: Option<Vec<String>>,
    pub fields: Field
}

impl Schema {
    pub fn new(name: String, key_field: Option<Vec<String>>, fields: Field) -> Schema {
        Schema {
            id: 0,
            name: name,
            key_field: match key_field {
                None => None,
                Some(ref keys) => Some(keys
                    .iter()
                    .map(|f| hash_str(f))
                    .collect())             // field list into field ids
            },
            str_key_field: key_field,
            fields: fields
        }
    }
    pub fn new_with_id(id: u32, name: String, key_field: Option<Vec<String>>, fields: Field) -> Schema {
        let mut schema = Schema::new(name, key_field, fields);
        schema.id = id;
        schema
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Field {
    pub type_id: u32,
    pub nullable: bool,
    pub is_array: bool,
    pub sub_fields: Option<Vec<Field>>,
    pub name: String,
    pub name_id: u64,
}

impl Field {
    pub fn new<'a>(
        name: & 'a str,
        type_id: u32,
        nullable: bool,
        is_array: bool,
        sub_fields: Option<Vec<Field>>)
        -> Field {
        Field {
            name: name.to_string(),
            name_id: types::key_hash(name),
            type_id: type_id,
            nullable: nullable,
            is_array: is_array,
            sub_fields: sub_fields
        }
    }
}

pub struct SchemasMap {
    schema_map: HashMap<u32, Arc<Schema>>,
    name_map: HashMap<String, u32>,
    id_counter: u32,
}

pub struct SchemasServer {
    map: Arc<RwLock<SchemasMap>>,
    sm: Option<sm::client::SMClient>,
}

impl SchemasServer {
    pub fn new(raft_client: Option<&Arc<RaftClient>>) -> Result<SchemasServer, ExecError> {
        let map = Arc::new(RwLock::new(SchemasMap::new()));
        let sm = match raft_client {
            Some(raft) => {
                let m1 = map.clone();
                let m2 = map.clone();
                let sm = sm::client::SMClient::new(sm::DEFAULT_SM_ID, raft);
                let mut sm_data = sm.get_all()?.unwrap();
                {
                    let mut map = map.write();
                    for schema in sm_data {
                        map.new_schema(schema);
                    }
                }
                let _ = sm.on_schema_added(move |r| {
                    let mut m1 = m1.write();
                    m1.new_schema(r.unwrap());
                })?;
                let _ = sm.on_schema_deleted(move |r| {
                    let mut m2 = m2.write();
                    m2.del_schema(&r.unwrap());
                })?;
                Some(sm)
            },
            None => None
        };
        let schemas = SchemasServer {
            map: map,
            sm: sm
        };
        return Ok(schemas);
    }
    pub fn get(&self, id: &u32) -> Option<Arc<Schema>> {
        let m = self.map.read();
        m.get(id)
    }
    pub fn new_schema(&self, schema: Schema) { // for debug only
        let mut m = self.map.write();
        m.new_schema(schema)
    }
    pub fn name_to_id<'a>(&self, name: &'a str) -> Option<u32> {
        let m = self.map.read();
        m.name_to_id(name)
    }
}

impl SchemasMap {
    pub fn new() -> SchemasMap {
        SchemasMap {
            schema_map: HashMap::new(),
            name_map: HashMap::new(),
            id_counter: 0,
        }
    }
    pub fn new_schema(&mut self, schema: Schema) {
        let name = schema.name.clone();
        let id = schema.id;
        self.schema_map.insert(id, Arc::new(schema.clone()));
        self.name_map.insert(name, id);
    }
    pub fn del_schema<'a>(&mut self, name: & 'a str) -> Result<(), ()> {
        if let Some(id) =self.name_to_id(name) {
            self.schema_map.remove(&id);
        }
        self.name_map.remove(&name.to_string());
        Ok(())
    }
    pub fn get_by_name<'a>(&self, name: & 'a str) -> Option<Arc<Schema>> {
        if let Some(id) = self.name_to_id(name) {
            return self.get(&id)
        }
        return None;
    }
    pub fn get(&self, id: &u32) -> Option<Arc<Schema>> {
        if let Some(schema) = self.schema_map.get(id) {
            return Some(schema.clone())
        }
        return None;
    }
    pub fn name_to_id<'a>(&self, name: &'a str) -> Option<u32> {
        self.name_map.get(&name.to_string()).cloned()
    }
    fn next_id(&mut self) -> u32 {
        self.id_counter += 1;
        while self.schema_map.contains_key(&self.id_counter) {
            self.id_counter += 1;
        }
        self.id_counter
    }
    fn get_all(&self) -> Vec<Schema> {
        self.schema_map
            .values()
            .map(|s_ref| {
                let arc = s_ref.clone();
                let r: &Schema = arc.borrow();
                r.clone()
            })
            .collect()
    }
    fn load_from_list(&mut self, data: &Vec<Schema>) {
         for schema in data {
             let id = schema.id;
             self.name_map.insert(schema.name.clone(), id);
             self.schema_map.insert(id, Arc::new(schema.clone()));
         }
    }
}<|endoftext|>


<commit_before>#![feature(async_await)]

use std::{convert::TryFrom, env, process::exit};

use ruma_client::{self, Client};
use ruma_client_api::r0;
use ruma_events::{
    room::message::{MessageEventContent, MessageType, TextMessageEventContent},
    EventType,
};
use ruma_identifiers::RoomAliasId;
use url::Url;

async fn hello_world(homeserver_url: Url, room: String) -> Result<(), ruma_client::Error> {
    let client = Client::new(homeserver_url, None);

    client.register_guest().await?;
    let response = client
        .request::<r0::alias::get_alias::Endpoint>(r0::alias::get_alias::Request {
            room_alias: RoomAliasId::try_from(&room[..]).unwrap(),
        })
        .await?;

    let room_id = response.room_id;

    client
        .request::<r0::membership::join_room_by_id::Endpoint>(
            r0::membership::join_room_by_id::Request {
                room_id: room_id.clone(),
                third_party_signed: None,
            },
        )
        .await?;

    client.request::<r0::send::send_message_event::Endpoint>(
        r0::send::send_message_event::Request {
            room_id: room_id,
            event_type: EventType::RoomMessage,
            txn_id: "1".to_owned(),
            data: MessageEventContent::Text(TextMessageEventContent {
                msgtype: MessageType::Text,
                body: "Hello World!".to_owned(),
                format: None,
                formatted_body: None,
                relates_to: None,
            }),
        },
    ).await?;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), ruma_client::Error> {
    let (homeserver_url, room) = match (env::args().nth(1), env::args().nth(2)) {
        (Some(a), Some(b)) => (a, b),
        _ => {
            eprintln!(
                "Usage: {} <homeserver_url> <room>",
                env::args().next().unwrap()
            );
            exit(1)
        }
    };

    hello_world(homeserver_url.parse().unwrap(), room).await
}
<commit_msg>Rerun rustfmt<commit_after>#![feature(async_await)]

use std::{convert::TryFrom, env, process::exit};

use ruma_client::{self, Client};
use ruma_client_api::r0;
use ruma_events::{
    room::message::{MessageEventContent, MessageType, TextMessageEventContent},
    EventType,
};
use ruma_identifiers::RoomAliasId;
use url::Url;

async fn hello_world(homeserver_url: Url, room: String) -> Result<(), ruma_client::Error> {
    let client = Client::new(homeserver_url, None);

    client.register_guest().await?;
    let response = client
        .request::<r0::alias::get_alias::Endpoint>(r0::alias::get_alias::Request {
            room_alias: RoomAliasId::try_from(&room[..]).unwrap(),
        })
        .await?;

    let room_id = response.room_id;

    client
        .request::<r0::membership::join_room_by_id::Endpoint>(
            r0::membership::join_room_by_id::Request {
                room_id: room_id.clone(),
                third_party_signed: None,
            },
        )
        .await?;

    client
        .request::<r0::send::send_message_event::Endpoint>(r0::send::send_message_event::Request {
            room_id: room_id,
            event_type: EventType::RoomMessage,
            txn_id: "1".to_owned(),
            data: MessageEventContent::Text(TextMessageEventContent {
                msgtype: MessageType::Text,
                body: "Hello World!".to_owned(),
                format: None,
                formatted_body: None,
                relates_to: None,
            }),
        })
        .await?;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), ruma_client::Error> {
    let (homeserver_url, room) = match (env::args().nth(1), env::args().nth(2)) {
        (Some(a), Some(b)) => (a, b),
        _ => {
            eprintln!(
                "Usage: {} <homeserver_url> <room>",
                env::args().next().unwrap()
            );
            exit(1)
        }
    };

    hello_world(homeserver_url.parse().unwrap(), room).await
}
<|endoftext|>


<commit_before>
extern crate gitlab_api as gitlab;

use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;

use gitlab::GitLab;
// use gitlab::Pagination;
use gitlab::issues;

fn main() {
    env_logger::init().unwrap();
    info!("starting up");

    let hostname = match env::var("GITLAB_HOSTNAME") {
        Ok(val) => val,
        Err(_) => {
            let default = String::from("gitlab.com");
            println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
                     default);
            default
        }
    };

    let token = match env::var("GITLAB_TOKEN") {
        Ok(val) => val,
        Err(_) => {
            panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \
                    http://{}/profile/account",
                   hostname);
        }
    };

    let gl = GitLab::new_https(&hostname, &token);

    let issues = gl.issues(issues::Listing::new()).unwrap();
    println!("issues: {:?}", issues);

    let listing = issues::Listing::new().state(issues::ListingState::Opened).clone();
    let opened_issues = gl.issues(listing).unwrap();
    println!("opened_issues: {:?}", opened_issues);

    let listing = issues::Listing::new().state(issues::ListingState::Closed).clone();
    let closed_issues = gl.issues(listing).unwrap();
    println!("closed_issues: {:?}", closed_issues);

    let listing = issues::single::Listing::new(142, 739);
    let issue = gl.issue(listing).unwrap();
    println!("issue: {:?}", issue);
}
<commit_msg>Add example to list groups issues<commit_after>
extern crate gitlab_api as gitlab;

use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;

use gitlab::GitLab;
// use gitlab::Pagination;
use gitlab::issues;

fn main() {
    env_logger::init().unwrap();
    info!("starting up");

    let hostname = match env::var("GITLAB_HOSTNAME") {
        Ok(val) => val,
        Err(_) => {
            let default = String::from("gitlab.com");
            println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
                     default);
            default
        }
    };

    let token = match env::var("GITLAB_TOKEN") {
        Ok(val) => val,
        Err(_) => {
            panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \
                    http://{}/profile/account",
                   hostname);
        }
    };

    let gl = GitLab::new_https(&hostname, &token);

    let issues = gl.issues(issues::Listing::new()).unwrap();
    println!("issues: {:?}", issues);

    let listing = issues::Listing::new().state(issues::ListingState::Opened).clone();
    let opened_issues = gl.issues(listing).unwrap();
    println!("opened_issues: {:?}", opened_issues);

    let listing = issues::Listing::new().state(issues::ListingState::Closed).clone();
    let closed_issues = gl.issues(listing).unwrap();
    println!("closed_issues: {:?}", closed_issues);

    let listing = issues::single::Listing::new(142, 739);
    let issue = gl.issue(listing).unwrap();
    println!("issue: {:?}", issue);

    let listing = issues::group::Listing::new(21).state(issues::group::ListingState::Closed).clone();
    let group_issues = gl.group_issues(listing).unwrap();
    println!("group_issues: {:?}", group_issues);
}
<|endoftext|>


<commit_before>#![feature(test)]
#![feature(core)]

#![allow(dead_code)]

extern crate core;
extern crate test;
extern crate columnar;
extern crate byteorder;
extern crate timely;

extern crate docopt;
use docopt::Docopt;

use test::Bencher;
use std::thread;
use std::hash::Hash;
use core::fmt::Debug;

use columnar::Columnar;

use timely::progress::Scope;
use timely::progress::nested::Summary::Local;
use timely::progress::nested::product::Product;
use timely::communication::{ThreadCommunicator, ProcessCommunicator, Communicator};
use timely::communication::channels::Data;
use timely::networking::initialize_networking;

use timely::example_static::builder::{GraphBuilder, GraphRoot};
use timely::example_static::stream::Stream;
use timely::example_static::enterleave::*;
use timely::example_static::distinct::*;
use timely::example_static::input::*;
use timely::example_static::feedback::*;
use timely::example_static::concat::*;

static USAGE: &'static str = "
Usage: timely distinct [options] [<arguments>...]
       timely barrier [options] [<arguments>...]
       timely command [options] [<arguments>...]

Options:
    -w <arg>, --workers <arg>    number of workers per process [default: 1]
    -p <arg>, --processid <arg>  identity of this process      [default: 0]
    -n <arg>, --processes <arg>  number of processes involved  [default: 1]
";

fn main() {
    let args = Docopt::new(USAGE).and_then(|dopt| dopt.parse()).unwrap_or_else(|e| e.exit());

    let workers: u64 = if let Ok(threads) = args.get_str("-w").parse() { threads }
                       else { panic!("invalid setting for --workers: {}", args.get_str("-t")) };
    let process_id: u64 = if let Ok(proc_id) = args.get_str("-p").parse() { proc_id }
                          else { panic!("invalid setting for --processid: {}", args.get_str("-p")) };
    let processes: u64 = if let Ok(processes) = args.get_str("-n").parse() { processes }
                         else { panic!("invalid setting for --processes: {}", args.get_str("-n")) };

    println!("Hello, world!");
    println!("Starting timely with");
    println!("\tworkers:\t{}", workers);
    println!("\tprocesses:\t{}", processes);
    println!("\tprocessid:\t{}", process_id);

    // vector holding communicators to use; one per local worker.
    if processes > 1 {
        println!("Initializing BinaryCommunicator");
        let addresses = (0..processes).map(|index| format!("localhost:{}", 2101 + index).to_string()).collect();
        let communicators = initialize_networking(addresses, process_id, workers).ok().expect("error initializing networking");
        if args.get_bool("distinct") { _distinct_multi(communicators); }
        else if args.get_bool("barrier") { _barrier_multi(communicators); }
        else if args.get_bool("command") { _command_multi(communicators); }
    }
    else if workers > 1 {
        println!("Initializing ProcessCommunicator");
        let communicators = ProcessCommunicator::new_vector(workers);
        if args.get_bool("distinct") { _distinct_multi(communicators); }
        else if args.get_bool("barrier") { _barrier_multi(communicators); }
        else if args.get_bool("command") { _command_multi(communicators); }
    }
    else {
        println!("Initializing ThreadCommunicator");
        let communicators = vec![ThreadCommunicator];
        if args.get_bool("distinct") { _distinct_multi(communicators); }
        else if args.get_bool("barrier") { _barrier_multi(communicators); }
        else if args.get_bool("command") { _command_multi(communicators); }
    };
}

#[bench]
fn distinct_bench(bencher: &mut Bencher) { _distinct(ProcessCommunicator::new_vector(1).swap_remove(0), Some(bencher)); }
fn _distinct_multi<C: Communicator+Send>(communicators: Vec<C>) {
    let mut guards = Vec::new();
    for communicator in communicators.into_iter() {
        guards.push(thread::Builder::new().name(format!("worker thread {}", communicator.index()))
                                          .scoped(move || _distinct(communicator, None))
                                          .unwrap());
    }
}

// #[bench]
// fn command_bench(bencher: &mut Bencher) { _command(ProcessCommunicator::new_vector(1).swap_remove(0).unwrap(), Some(bencher)); }
fn _command_multi<C: Communicator+Send>(_communicators: Vec<C>) {
    println!("command currently disabled awaiting io reform");
    // let mut guards = Vec::new();
    // for communicator in communicators.into_iter() {
    //     guards.push(thread::scoped(move || _command(communicator, None)));
    // }
}

#[bench]
fn barrier_bench(bencher: &mut Bencher) { _barrier(ProcessCommunicator::new_vector(1).swap_remove(0), Some(bencher)); }
fn _barrier_multi<C: Communicator+Send>(communicators: Vec<C>) {
    let mut guards = Vec::new();
    for communicator in communicators.into_iter() {
        guards.push(thread::scoped(move || _barrier(communicator, None)));
    }
}

fn create_subgraph<G: GraphBuilder, D>(builder: &mut G,
                                        source1: &Stream<G::Timestamp, D>,
                                        source2: &Stream<G::Timestamp, D>) ->
                                            (Stream<G::Timestamp, D>, Stream<G::Timestamp, D>)
where D: Data+Hash+Eq+Debug+Columnar {

    let mut subgraph = builder.new_subgraph::<u64>();

    (subgraph.enter(source1).distinct().leave(),
     subgraph.enter(source2).leave())
}

fn _distinct<C: Communicator>(communicator: C, bencher: Option<&mut Bencher>) {

    let mut root = GraphRoot::new(communicator);

    let (mut input1, mut input2) = {

        // allocate a new graph builder
        let mut graph = root.new_subgraph();

        // try building some input scopes
        let (input1, stream1) = graph.new_input::<u64>();
        let (input2, stream2) = graph.new_input::<u64>();

        // prepare some feedback edges
        let (mut feedback1, feedback1_output) = graph.feedback(Product::new((), 100), Local(1));
        let (mut feedback2, feedback2_output) = graph.feedback(Product::new((), 100), Local(1));

        let concat1 = graph.concatenate(vec![&stream1, &feedback1_output]).disable();
        let concat2 = graph.concatenate(vec![&stream2, &feedback2_output]).disable();

        // build up a subgraph using the concatenated inputs/feedbacks
        let (egress1, egress2) = create_subgraph(&mut graph, &concat1, &concat2);

        // connect feedback sources. notice that we have swapped indices ...
        feedback1.connect_input(&egress2, &mut graph);
        feedback2.connect_input(&egress1, &mut graph);

        (input1, input2)
    };

    root.step();

    // move some data into the dataflow graph.
    input1.send_messages(&Product::new((), 0), vec![1u64]);
    input2.send_messages(&Product::new((), 0), vec![2u64]);

    // see what everyone thinks about that ...
    root.step();

    input1.advance(&Product::new((), 0), &Product::new((), 1000000));
    input2.advance(&Product::new((), 0), &Product::new((), 1000000));
    input1.close_at(&Product::new((), 1000000));
    input2.close_at(&Product::new((), 1000000));

    // spin
    match bencher {
        Some(b) => b.iter(|| { root.step(); }),
        None    => while root.step() { }
    }
}

// fn _command<C: Communicator>(communicator: C, bencher: Option<&mut Bencher>) {
//     let communicator = Rc::new(RefCell::new(communicator));
//
//     // no "base scopes" yet, so the root pretends to be a subscope of some parent with a () timestamp type.
//     let mut graph = new_graph(Progcaster::new(&mut (*communicator.borrow_mut())));
//     let mut input = graph.new_input::<u64>(communicator);
//     let mut feedback = input.1.feedback(((), 1000), Local(1));
//     let mut result: Stream<_, u64, _> = input.1.concat(&mut feedback.1)
//                                                .command("./target/release/command".to_string());
//
//     feedback.0.connect_input(&mut result);
//
//     // start things up!
//     graph.borrow_mut().get_internal_summary();
//     graph.borrow_mut().set_external_summary(Vec::new(), &mut []);
//     graph.borrow_mut().push_external_progress(&mut []);
//
//     input.0.close_at(&((), 0));
//
//     // spin
//     match bencher {
//         Some(b) => b.iter(|| { graph.borrow_mut().pull_internal_progress(&mut [], &mut [], &mut []); }),
//         None    => while graph.borrow_mut().pull_internal_progress(&mut [], &mut [], &mut []) { },
//     }
// }

fn _barrier<C: Communicator>(communicator: C, bencher: Option<&mut Bencher>) {

    let mut root = GraphRoot::new(communicator);
    //
    // {
    //     let borrow = root.builder();
    //     let mut graph = SubgraphBuilder::new(&borrow);
    //
    //     let peers = graph.with_communicator(|x| x.peers());
    //     {
    //         let builder = &graph.builder();
    //
    //         builder.borrow_mut().add_scope(BarrierScope { epoch: 0, ready: true, degree: peers, ttl: 1000000 });
    //         builder.borrow_mut().connect(ScopeOutput(0, 0), ScopeInput(0, 0));
    //     }
    //
    //     graph.seal();
    // }
    //
    // // spin
    match bencher {
        Some(b) => b.iter(|| { root.step(); }),
        None    => while root.step() { },
    }
}
<commit_msg>Fixed examples/main_static.rs<commit_after>#![feature(test)]
#![feature(core)]
#![feature(scoped)]

#![allow(dead_code)]

extern crate core;
extern crate test;
extern crate columnar;
extern crate byteorder;
extern crate timely;

extern crate docopt;
use docopt::Docopt;

use test::Bencher;
use std::thread;
use std::hash::Hash;
use core::fmt::Debug;

use columnar::Columnar;

use timely::progress::Scope;
use timely::progress::nested::Summary::Local;
use timely::progress::nested::product::Product;
use timely::communication::{ThreadCommunicator, ProcessCommunicator, Communicator};
use timely::communication::channels::Data;
use timely::networking::initialize_networking;

use timely::example_static::builder::{GraphBuilder, GraphRoot};
use timely::example_static::stream::Stream;
use timely::example_static::enterleave::*;
use timely::example_static::distinct::*;
use timely::example_static::input::*;
use timely::example_static::feedback::*;
use timely::example_static::concat::*;

static USAGE: &'static str = "
Usage: timely distinct [options] [<arguments>...]
       timely barrier [options] [<arguments>...]
       timely command [options] [<arguments>...]

Options:
    -w <arg>, --workers <arg>    number of workers per process [default: 1]
    -p <arg>, --processid <arg>  identity of this process      [default: 0]
    -n <arg>, --processes <arg>  number of processes involved  [default: 1]
";

fn main() {
    let args = Docopt::new(USAGE).and_then(|dopt| dopt.parse()).unwrap_or_else(|e| e.exit());

    let workers: u64 = if let Ok(threads) = args.get_str("-w").parse() { threads }
                       else { panic!("invalid setting for --workers: {}", args.get_str("-t")) };
    let process_id: u64 = if let Ok(proc_id) = args.get_str("-p").parse() { proc_id }
                          else { panic!("invalid setting for --processid: {}", args.get_str("-p")) };
    let processes: u64 = if let Ok(processes) = args.get_str("-n").parse() { processes }
                         else { panic!("invalid setting for --processes: {}", args.get_str("-n")) };

    println!("Hello, world!");
    println!("Starting timely with");
    println!("\tworkers:\t{}", workers);
    println!("\tprocesses:\t{}", processes);
    println!("\tprocessid:\t{}", process_id);

    // vector holding communicators to use; one per local worker.
    if processes > 1 {
        println!("Initializing BinaryCommunicator");
        let addresses = (0..processes).map(|index| format!("localhost:{}", 2101 + index).to_string()).collect();
        let communicators = initialize_networking(addresses, process_id, workers).ok().expect("error initializing networking");
        if args.get_bool("distinct") { _distinct_multi(communicators); }
        else if args.get_bool("barrier") { _barrier_multi(communicators); }
        else if args.get_bool("command") { _command_multi(communicators); }
    }
    else if workers > 1 {
        println!("Initializing ProcessCommunicator");
        let communicators = ProcessCommunicator::new_vector(workers);
        if args.get_bool("distinct") { _distinct_multi(communicators); }
        else if args.get_bool("barrier") { _barrier_multi(communicators); }
        else if args.get_bool("command") { _command_multi(communicators); }
    }
    else {
        println!("Initializing ThreadCommunicator");
        let communicators = vec![ThreadCommunicator];
        if args.get_bool("distinct") { _distinct_multi(communicators); }
        else if args.get_bool("barrier") { _barrier_multi(communicators); }
        else if args.get_bool("command") { _command_multi(communicators); }
    };
}

#[bench]
fn distinct_bench(bencher: &mut Bencher) { _distinct(ProcessCommunicator::new_vector(1).swap_remove(0), Some(bencher)); }
fn _distinct_multi<C: Communicator+Send>(communicators: Vec<C>) {
    let mut guards = Vec::new();
    for communicator in communicators.into_iter() {
        guards.push(thread::Builder::new().name(format!("worker thread {}", communicator.index()))
                                          .scoped(move || _distinct(communicator, None))
                                          .unwrap());
    }
}

// #[bench]
// fn command_bench(bencher: &mut Bencher) { _command(ProcessCommunicator::new_vector(1).swap_remove(0).unwrap(), Some(bencher)); }
fn _command_multi<C: Communicator+Send>(_communicators: Vec<C>) {
    println!("command currently disabled awaiting io reform");
    // let mut guards = Vec::new();
    // for communicator in communicators.into_iter() {
    //     guards.push(thread::scoped(move || _command(communicator, None)));
    // }
}

#[bench]
fn barrier_bench(bencher: &mut Bencher) { _barrier(ProcessCommunicator::new_vector(1).swap_remove(0), Some(bencher)); }
fn _barrier_multi<C: Communicator+Send>(communicators: Vec<C>) {
    let mut guards = Vec::new();
    for communicator in communicators.into_iter() {
        guards.push(thread::scoped(move || _barrier(communicator, None)));
    }
}

fn create_subgraph<G: GraphBuilder, D>(builder: &mut G,
                                        source1: &Stream<G::Timestamp, D>,
                                        source2: &Stream<G::Timestamp, D>) ->
                                            (Stream<G::Timestamp, D>, Stream<G::Timestamp, D>)
where D: Data+Hash+Eq+Debug+Columnar {

    let mut subgraph = builder.new_subgraph::<u64>();

    ((&mut subgraph).enter(source1).distinct().leave(),
     (&mut subgraph).enter(source2).leave())
}

fn _distinct<C: Communicator>(communicator: C, bencher: Option<&mut Bencher>) {

    let mut root = GraphRoot::new(communicator);

    let (mut input1, mut input2) = {

        // allocate a new graph builder
        let mut graph = root.new_subgraph();

        // try building some input scopes
        let (input1, stream1) = graph.new_input::<u64>();
        let (input2, stream2) = graph.new_input::<u64>();

        // prepare some feedback edges
        let (mut feedback1, feedback1_output) = graph.feedback(Product::new((), 100), Local(1));
        let (mut feedback2, feedback2_output) = graph.feedback(Product::new((), 100), Local(1));

        let concat1 = (&mut graph).concatenate(vec![stream1, feedback1_output]).disable();
        let concat2 = (&mut graph).concatenate(vec![stream2, feedback2_output]).disable();

        // build up a subgraph using the concatenated inputs/feedbacks
        let (egress1, egress2) = create_subgraph(&mut graph, &concat1, &concat2);

        // connect feedback sources. notice that we have swapped indices ...
        feedback1.connect_input(&egress2, &mut graph);
        feedback2.connect_input(&egress1, &mut graph);

        (input1, input2)
    };

    root.step();

    // move some data into the dataflow graph.
    input1.send_messages(&Product::new((), 0), vec![1u64]);
    input2.send_messages(&Product::new((), 0), vec![2u64]);

    // see what everyone thinks about that ...
    root.step();

    input1.advance(&Product::new((), 0), &Product::new((), 1000000));
    input2.advance(&Product::new((), 0), &Product::new((), 1000000));
    input1.close_at(&Product::new((), 1000000));
    input2.close_at(&Product::new((), 1000000));

    // spin
    match bencher {
        Some(b) => b.iter(|| { root.step(); }),
        None    => while root.step() { }
    }
}

// fn _command<C: Communicator>(communicator: C, bencher: Option<&mut Bencher>) {
//     let communicator = Rc::new(RefCell::new(communicator));
//
//     // no "base scopes" yet, so the root pretends to be a subscope of some parent with a () timestamp type.
//     let mut graph = new_graph(Progcaster::new(&mut (*communicator.borrow_mut())));
//     let mut input = graph.new_input::<u64>(communicator);
//     let mut feedback = input.1.feedback(((), 1000), Local(1));
//     let mut result: Stream<_, u64, _> = input.1.concat(&mut feedback.1)
//                                                .command("./target/release/command".to_string());
//
//     feedback.0.connect_input(&mut result);
//
//     // start things up!
//     graph.borrow_mut().get_internal_summary();
//     graph.borrow_mut().set_external_summary(Vec::new(), &mut []);
//     graph.borrow_mut().push_external_progress(&mut []);
//
//     input.0.close_at(&((), 0));
//
//     // spin
//     match bencher {
//         Some(b) => b.iter(|| { graph.borrow_mut().pull_internal_progress(&mut [], &mut [], &mut []); }),
//         None    => while graph.borrow_mut().pull_internal_progress(&mut [], &mut [], &mut []) { },
//     }
// }

fn _barrier<C: Communicator>(communicator: C, bencher: Option<&mut Bencher>) {

    let mut root = GraphRoot::new(communicator);
    //
    // {
    //     let borrow = root.builder();
    //     let mut graph = SubgraphBuilder::new(&borrow);
    //
    //     let peers = graph.with_communicator(|x| x.peers());
    //     {
    //         let builder = &graph.builder();
    //
    //         builder.borrow_mut().add_scope(BarrierScope { epoch: 0, ready: true, degree: peers, ttl: 1000000 });
    //         builder.borrow_mut().connect(ScopeOutput(0, 0), ScopeInput(0, 0));
    //     }
    //
    //     graph.seal();
    // }
    //
    // // spin
    match bencher {
        Some(b) => b.iter(|| { root.step(); }),
        None    => while root.step() { },
    }
}
<|endoftext|>


<commit_before>extern mod glfw;

fn main() {
    // Run this task on the main thread. Unlike C or C++, a Rust program
    // automatically starts a new thread, so this line is _essential_ to ensure
    // that the OS is able to update the window and recieve events from the user.
    do task::task().sched_mode(task::PlatformThread).spawn  {
        use core::private::finally::Finally;

        do (|| {
            glfw::set_error_callback(error_callback);

            if !glfw::init() { die!(~"Failed to initialize GLFW\n"); }

            let window =
                match glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed) {
                    Some(w) => w,
                    None    => die!(~"Failed to open GLFW window")
                };

            window.make_context_current();

            let mut done = false;

            while !done {
                glfw::poll_events();

                // Check if the window should close
                done = window.get_param(glfw::SHOULD_CLOSE) == glfw::TRUE
                    || window.get_key(glfw::KEY_ESC)        == glfw::PRESS;
            }

            window.destroy();

        }).finally {
            glfw::terminate();    // terminate glfw on completion
        }
    }
}

fn error_callback(_error: libc::c_int, description: ~str) {
    io::println(fmt!("GLFW Error: %s", description));
}<commit_msg>Another die! -> fail! conversion<commit_after>extern mod glfw;

fn main() {
    // Run this task on the main thread. Unlike C or C++, a Rust program
    // automatically starts a new thread, so this line is _essential_ to ensure
    // that the OS is able to update the window and recieve events from the user.
    do task::task().sched_mode(task::PlatformThread).spawn  {
        use core::private::finally::Finally;

        do (|| {
            glfw::set_error_callback(error_callback);

            if !glfw::init() { fail!(~"Failed to initialize GLFW\n"); }

            let window =
                match glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed) {
                    Some(w) => w,
                    None    => fail!(~"Failed to open GLFW window")
                };

            window.make_context_current();

            let mut done = false;

            while !done {
                glfw::poll_events();

                // Check if the window should close
                done = window.get_param(glfw::SHOULD_CLOSE) == glfw::TRUE
                    || window.get_key(glfw::KEY_ESC)        == glfw::PRESS;
            }

            window.destroy();

        }).finally {
            glfw::terminate();    // terminate glfw on completion
        }
    }
}

fn error_callback(_error: libc::c_int, description: ~str) {
    io::println(fmt!("GLFW Error: %s", description));
}
<|endoftext|>


<commit_before>#![feature(collections, core, path, io)]

extern crate image;
extern crate texture_packer;

use std::old_io::File;

use texture_packer::texture::Texture;
use texture_packer::{
    TexturePacker,
    TexturePackerConfig,
};
use texture_packer::importer::{
    ImageImporter,
};
use texture_packer::exporter::{
    ImageExporter,
};

static MAX_IMAGE_WIDTH: u32 = 400;
static MAX_IMAGE_HEIGHT: u32 = 400;

fn main() {
    let mut config = TexturePackerConfig::default();
    config.max_width = MAX_IMAGE_WIDTH;
    config.max_height = MAX_IMAGE_HEIGHT;
    config.allow_rotation = false;
    config.texture_outlines = true;
    config.border_padding = 2;

    let mut texture_packer = TexturePacker::new_skyline(config);

    for i in 1..11 {
        let mut path = "./examples/assets/".to_string();
        let filename = format!("{}.png", i);
        path.push_str(filename.as_slice());
        let texture = ImageImporter::import_from_file(&Path::new(path)).unwrap();

        texture_packer.pack_own(filename.clone(), texture);
    }

    let image = ImageExporter::export(&texture_packer).unwrap();
    let output_filename = "examples/output/skyline-packer-output.png";
    let fout = File::create(&Path::new(output_filename)).unwrap();
    println!("{} x {}", texture_packer.width(), texture_packer.height());
    let _ = image.save(fout, image::PNG);
}

<commit_msg>Upgrade example to latest rust<commit_after>extern crate image;
extern crate texture_packer;

use std::path::Path;
use std::fs::File;

use texture_packer::texture::Texture;
use texture_packer::{ TexturePacker, TexturePackerConfig };
use texture_packer::importer::ImageImporter;
use texture_packer::exporter::ImageExporter;

const MAX_IMAGE_WIDTH: u32 = 400;
const MAX_IMAGE_HEIGHT: u32 = 400;

fn main() {
    let mut config = TexturePackerConfig::default();
    config.max_width = MAX_IMAGE_WIDTH;
    config.max_height = MAX_IMAGE_HEIGHT;
    config.allow_rotation = false;
    config.texture_outlines = true;
    config.border_padding = 2;

    let ref mut texture_packer = TexturePacker::new_skyline(config);

    for i in 1 .. 11 {
        let file = format!("{}.png", i);
        let ref path = ["./examples/assets/", &file[..]].concat();
        let ref path = Path::new(path);
        let texture = ImageImporter::import_from_file(path).unwrap();

        texture_packer.pack_own(file, texture);
    }

    let image = ImageExporter::export(texture_packer).unwrap();
    let path = "./examples/output/skyline-packer-output.png";
    let ref path = Path::new(path);
    let ref mut file = File::create(path).unwrap();

    println!("{} x {}", texture_packer.width(), texture_packer.height());
    image.save(file, image::PNG).unwrap();
}
<|endoftext|>


<commit_before>//
// Sysinfo
//
// Copyright (c) 2015 Guillaume Gomez
//

use sys::component::Component;
use sys::process::*;
use sys::processor::*;
use sys::Disk;
use sys::Networks;
use Pid;
use {RefreshKind, SystemExt};

use std::collections::HashMap;

/// Structs containing system's information.
pub struct System {
    processes_list: HashMap<Pid, Process>,
    networks: Networks,
    global_processor: Processor,
}

impl SystemExt for System {
    fn new_with_specifics(_: RefreshKind) -> System {
        System {
            processes_list: Default::default(),
            networks: Networks::new(),
            global_processor: Processor::new {},
        }
    }

    fn refresh_memory(&mut self) {}

    fn refresh_cpu(&mut self) {}

    fn refresh_components_list(&mut self) {}

    fn refresh_processes(&mut self) {}

    fn refresh_process(&mut self, _pid: Pid) -> bool {
        false
    }

    fn refresh_disks_list(&mut self) {}

    fn refresh_network(&mut self) {}

    // COMMON PART
    //
    // Need to be moved into a "common" file to avoid duplication.

    fn get_processes(&self) -> &HashMap<Pid, Process> {
        &self.processes_list
    }

    fn get_process(&self, _pid: Pid) -> Option<&Process> {
        None
    }

    fn get_networks(&self) -> &Networks {
        &self.networks
    }

    fn get_networks_mut(&mut self) -> &mut Networks {
        &mut self.networks
    }

    fn get_global_processor_info(&self) -> &Processor {
        &self.global_processor
    }

    fn get_processors(&self) -> &[Processor] {
        &[]
    }

    fn get_total_memory(&self) -> u64 {
        0
    }

    fn get_free_memory(&self) -> u64 {
        0
    }

    fn get_used_memory(&self) -> u64 {
        0
    }

    fn get_total_swap(&self) -> u64 {
        0
    }

    fn get_free_swap(&self) -> u64 {
        0
    }

    fn get_used_swap(&self) -> u64 {
        0
    }

    fn get_components(&self) -> &[Component] {
        &[]
    }

    fn get_components_mut(&self) -> &[Component] {
        &[]
    }

    fn get_disks(&self) -> &[Disk] {
        &[]
    }

    fn get_disks_mut(&self) -> &mut [Disk] {
        &mut []
    }

    fn get_uptime(&self) -> u64 {
        0
    }

    fn get_load_average(&self) -> LoadAvg {
        LoadAvg {
            one: 0.,
            five: 0.,
            fifteen: 0.,
        }
    }
}

impl Default for System {
    fn default() -> System {
        System::new()
    }
}
<commit_msg>Add users for unknown targets<commit_after>//
// Sysinfo
//
// Copyright (c) 2015 Guillaume Gomez
//

use sys::component::Component;
use sys::process::*;
use sys::processor::*;
use sys::Disk;
use sys::Networks;
use Pid;
use User;
use {RefreshKind, SystemExt};

use std::collections::HashMap;

/// Structs containing system's information.
pub struct System {
    processes_list: HashMap<Pid, Process>,
    networks: Networks,
    global_processor: Processor,
}

impl SystemExt for System {
    fn new_with_specifics(_: RefreshKind) -> System {
        System {
            processes_list: Default::default(),
            networks: Networks::new(),
            global_processor: Processor::new {},
        }
    }

    fn refresh_memory(&mut self) {}

    fn refresh_cpu(&mut self) {}

    fn refresh_components_list(&mut self) {}

    fn refresh_processes(&mut self) {}

    fn refresh_process(&mut self, _pid: Pid) -> bool {
        false
    }

    fn refresh_disks_list(&mut self) {}

    fn refresh_users_list(&mut self) {}

    fn refresh_network(&mut self) {}

    // COMMON PART
    //
    // Need to be moved into a "common" file to avoid duplication.

    fn get_processes(&self) -> &HashMap<Pid, Process> {
        &self.processes_list
    }

    fn get_process(&self, _pid: Pid) -> Option<&Process> {
        None
    }

    fn get_networks(&self) -> &Networks {
        &self.networks
    }

    fn get_networks_mut(&mut self) -> &mut Networks {
        &mut self.networks
    }

    fn get_global_processor_info(&self) -> &Processor {
        &self.global_processor
    }

    fn get_processors(&self) -> &[Processor] {
        &[]
    }

    fn get_total_memory(&self) -> u64 {
        0
    }

    fn get_free_memory(&self) -> u64 {
        0
    }

    fn get_used_memory(&self) -> u64 {
        0
    }

    fn get_total_swap(&self) -> u64 {
        0
    }

    fn get_free_swap(&self) -> u64 {
        0
    }

    fn get_used_swap(&self) -> u64 {
        0
    }

    fn get_components(&self) -> &[Component] {
        &[]
    }

    fn get_components_mut(&self) -> &[Component] {
        &[]
    }

    fn get_disks(&self) -> &[Disk] {
        &[]
    }

    fn get_disks_mut(&self) -> &mut [Disk] {
        &mut []
    }

    fn get_uptime(&self) -> u64 {
        0
    }

    fn get_load_average(&self) -> LoadAvg {
        LoadAvg {
            one: 0.,
            five: 0.,
            fifteen: 0.,
        }
    }

    fn get_users(&self) -> &[User] {
        &[]
    }
}

impl Default for System {
    fn default() -> System {
        System::new()
    }
}
<|endoftext|>


<commit_before>use reqwest::{ self, header };
use std::fs::File;
use std::io::{ BufWriter, Read, Write };
use std::path::Path;

use config::Config;
use error::PackageError;

fn get_content_length(url: &str) -> Result<u64, PackageError> {
    // GET the URL, returning an error if necessary.
    let response = reqwest::get(url)?;

    // Try to retrieve the content length, and return it.
    Ok(response
    .headers()
    .get::<header::ContentLength>()
    // If the Response contains no content-length, default to 0.
    .map_or(0u64, |x| {
        let header::ContentLength(len) = *x;
        len
    }))
}

pub fn download_file<F, P>(url: &str, to_path: P, callback: F) -> Result<u64, PackageError>
    where F: Fn(u64, u64), P: AsRef<Path>
{

    // GET the URL, returning an error if necessary.
    let response = reqwest::get(url)?;

    // Try to retrieve the content length.
    let content_length = get_content_length(url)?;

    // For every `buffer_size` bytes, call the callback once.
    // `buffer_size` decides how frequent the function calls the callback by
    // checking whether (downloaded bytes) % `buffer_size` is 0.
    let Config { buffer_size: buffer_size, .. } = Config::default();
    let buffer_size = buffer_size.unwrap_or(65536);

    // Obviously, the target file to be written to by the BufWriter.
    let mut target = BufWriter::new(File::create(to_path)?);

    for (index, byte) in response.bytes().enumerate() {
        // Write to the target, returns an error if necessary.
        target.write(&[byte?])?;

        // Checks whether it's time to call the callback, and call it if it is.
        // Plus one to `index` as `index` itself is zero-indexed.
        if index as u64 % buffer_size == 0 {
            callback((index + 1) as u64, content_length);
        };
    }

    // In case the callback never got a chance to be called due to the package
    // itself being too small.
    callback(content_length, content_length);

    Ok(content_length)
}

pub fn download_buf(url: &str) -> Result<Vec<u8>, PackageError> {
    // GET the URL, returning an error if necessary.
    let mut response = reqwest::get(url)?;

    // Try to read the Response into memory
    let mut content = Vec::new();
    response.read_to_end(&mut content)?;

    Ok(content)
}<commit_msg>Remove redundant patterns<commit_after>use reqwest::{ self, header };
use std::fs::File;
use std::io::{ BufWriter, Read, Write };
use std::path::Path;

use config::Config;
use error::PackageError;

fn get_content_length(url: &str) -> Result<u64, PackageError> {
    // GET the URL, returning an error if necessary.
    let response = reqwest::get(url)?;

    // Try to retrieve the content length, and return it.
    Ok(response
    .headers()
    .get::<header::ContentLength>()
    // If the Response contains no content-length, default to 0.
    .map_or(0u64, |x| {
        let header::ContentLength(len) = *x;
        len
    }))
}

pub fn download_file<F, P>(url: &str, to_path: P, callback: F) -> Result<u64, PackageError>
    where F: Fn(u64, u64), P: AsRef<Path>
{

    // GET the URL, returning an error if necessary.
    let response = reqwest::get(url)?;

    // Try to retrieve the content length.
    let content_length = get_content_length(url)?;

    // For every `buffer_size` bytes, call the callback once.
    // `buffer_size` decides how frequent the function calls the callback by
    // checking whether (downloaded bytes) % `buffer_size` is 0.
    let Config { buffer_size, .. } = Config::default();
    let buffer_size = buffer_size.unwrap_or(65536);

    // Obviously, the target file to be written to by the BufWriter.
    let mut target = BufWriter::new(File::create(to_path)?);

    for (index, byte) in response.bytes().enumerate() {
        // Write to the target, returns an error if necessary.
        target.write(&[byte?])?;

        // Checks whether it's time to call the callback, and call it if it is.
        // Plus one to `index` as `index` itself is zero-indexed.
        if index as u64 % buffer_size == 0 {
            callback((index + 1) as u64, content_length);
        };
    }

    // In case the callback never got a chance to be called due to the package
    // itself being too small.
    callback(content_length, content_length);

    Ok(content_length)
}

pub fn download_buf(url: &str) -> Result<Vec<u8>, PackageError> {
    // GET the URL, returning an error if necessary.
    let mut response = reqwest::get(url)?;

    // Try to read the Response into memory
    let mut content = Vec::new();
    response.read_to_end(&mut content)?;

    Ok(content)
}<|endoftext|>


<commit_before>use wpilib::wpilib_hal::*;
use wpilib::digital_input::DigitalInput;
use std::ptr;
use std::mem;

pub enum IndexingType {
    ResetWhileHigh,
    ResetWhileLow,
    ResetOnFallingEdge,
    ResetOnRisingEdge,
}

pub struct Encoder {
    source_a: DigitalInput,
    source_b: DigitalInput,
    source_index: Option<DigitalInput>,
    encoder: HAL_EncoderHandle,
}

impl Encoder {
    pub fn new(channel_a: i32, channel_b: i32, encoding: HAL_EncoderEncodingType) -> Result<Encoder, i32> {
        let source_a = DigitalInput::new(channel_a)?;
        let source_b = DigitalInput::new(channel_b)?;

        let handle = hal_call!(HAL_InitializeEncoder(source_a.get_handle(),
                                                     mem::transmute(0),
                                                     source_b.get_handle(),
                                                     mem::transmute(0),
                                                     false as i32,
                                                     encoding))?;
        let encoder = Encoder {
            source_a: source_a,
            source_b: source_b,
            source_index: None,
            encoder: handle,
        };
        unsafe {
            HAL_Report(18, encoder.get_fpga_index()?, encoding as i32, ptr::null());
        }
        Ok(encoder)
    }

    pub fn get_fpga_index(&self) -> Result<i32, i32> {
        hal_call!(HAL_GetEncoderFPGAIndex(self.encoder))
    }

    pub fn get(&self) -> Result<i32, i32> {
        hal_call!(HAL_GetEncoder(self.encoder))
    }

    pub fn get_rate(&self) -> Result<f64, i32> {
        hal_call!(HAL_GetEncoderRate(self.encoder))
    }

    pub fn set_min_rate(&mut self, min_rate: f64) -> Result<(), i32> {
        hal_call!(HAL_SetEncoderMinRate(self.encoder, min_rate))
    }
}

impl Drop for Encoder {
    fn drop(&mut self) {
        hal_call!(HAL_FreeEncoder(self.encoder)).unwrap();
    }
}
<commit_msg>Implement more functions on Encoder<commit_after>use wpilib::wpilib_hal::*;
use wpilib::digital_input::DigitalInput;
use std::ptr;
use std::mem;

pub enum IndexingType {
    ResetWhileHigh,
    ResetWhileLow,
    ResetOnFallingEdge,
    ResetOnRisingEdge,
}

pub struct Encoder {
    source_a: DigitalInput,
    source_b: DigitalInput,
    source_index: Option<DigitalInput>,
    encoder: HAL_EncoderHandle,
}

impl Encoder {
    pub fn new(channel_a: i32,
               channel_b: i32,
               encoding: HAL_EncoderEncodingType)
               -> Result<Encoder, i32> {
        let source_a = DigitalInput::new(channel_a)?;
        let source_b = DigitalInput::new(channel_b)?;

        let handle = hal_call!(HAL_InitializeEncoder(source_a.get_handle(),
                                                     mem::transmute(0),
                                                     source_b.get_handle(),
                                                     mem::transmute(0),
                                                     false as i32,
                                                     encoding))?;
        let encoder = Encoder {
            source_a: source_a,
            source_b: source_b,
            source_index: None,
            encoder: handle,
        };
        unsafe {
            HAL_Report(18, encoder.get_fpga_index()?, encoding as i32, ptr::null());
        }
        Ok(encoder)
    }

    pub fn get_fpga_index(&self) -> Result<i32, i32> {
        hal_call!(HAL_GetEncoderFPGAIndex(self.encoder))
    }

    pub fn get(&self) -> Result<i32, i32> {
        hal_call!(HAL_GetEncoder(self.encoder))
    }

    pub fn get_raw(&self) -> Result<i32, i32> {
        hal_call!(HAL_GetEncoderRaw(self.encoder))
    }

    pub fn get_encoding_scale(&self) -> Result<i32, i32> {
        hal_call!(HAL_GetEncoderEncodingScale(self.encoder))
    }

    pub fn get_rate(&self) -> Result<f64, i32> {
        hal_call!(HAL_GetEncoderRate(self.encoder))
    }

    pub fn set_min_rate(&mut self, min_rate: f64) -> Result<(), i32> {
        hal_call!(HAL_SetEncoderMinRate(self.encoder, min_rate))
    }

    pub fn reset(&mut self) -> Result<(), i32> {
        hal_call!(HAL_ResetEncoder(self.encoder))
    }
}

impl Drop for Encoder {
    fn drop(&mut self) {
        hal_call!(HAL_FreeEncoder(self.encoder)).unwrap();
    }
}
<|endoftext|>


<commit_before>extern crate cairo;

use self::cairo::MatrixTrait;

/* Keep this in sync with ../../rsvg-private.h:RsvgBbox */
#[repr(C)]
pub struct RsvgBbox {
    pub rect:   cairo::Rectangle,
    pub affine: cairo::Matrix,
    pub virgin: bool
}

#[no_mangle]
pub extern fn rsvg_bbox_init (raw_bbox: *mut RsvgBbox, raw_matrix: *const cairo::Matrix) {
    assert! (!raw_bbox.is_null ());
    assert! (!raw_matrix.is_null ());

    let bbox: &mut RsvgBbox = unsafe { &mut (*raw_bbox) };

    bbox.virgin = true;
    bbox.affine = unsafe { *raw_matrix };
}

#[no_mangle]
pub extern fn rsvg_bbox_insert (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
    assert! (!raw_dst.is_null ());
    assert! (!raw_src.is_null ());

    let dst: &mut RsvgBbox = unsafe { &mut (*raw_dst) };
    let src: &RsvgBbox = unsafe { &*raw_src };

    if src.virgin {
        return;
    }

    let mut xmin: f64;
    let mut ymin: f64;
    let mut xmax: f64;
    let mut ymax: f64;

    if !dst.virgin {
        xmin = dst.rect.x;
        ymin = dst.rect.y;
        xmax = dst.rect.x + dst.rect.width;
        ymax = dst.rect.y + dst.rect.height;
    } else {
        xmin = 0.0;
        ymin = 0.0;
        xmax = 0.0;
        ymax = 0.0;
    }

    let mut affine = dst.affine;

    affine.invert (); // this will panic!() if it's not invertible... should we check on our own?
    affine = cairo::Matrix::multiply (&src.affine, &affine);

    /* This is a trick.  We want to transform each of the corners of
     * the rectangle defined by src.rect with the affine
     * transformation, and get the bounding box of all the four
     * resulting points.  The modulus and division accomplish this by
     * running through all the combinations of adding or not adding
     * the width/height to the first point src.rect.(x, y).
     */
    for i in 0..4 {
        let rx: f64 = src.rect.x + src.rect.width * (i % 2) as f64;
        let ry: f64 = src.rect.y + src.rect.height * (i / 2) as f64;
        let x: f64  = affine.xx * rx + affine.xy * ry + affine.x0;
        let y: f64  = affine.yx * rx + affine.yy * ry + affine.y0;

        if dst.virgin {
            xmin = x;
            xmax = x;
            ymin = y;
            ymax = y;
            dst.virgin = false;
        } else {
            if x < xmin { xmin = x; }
            if x > xmax { xmax = x; }
            if y < ymin { ymin = y; }
            if y > ymax { ymax = y; }
        }
    }

    dst.rect.x = xmin;
    dst.rect.y = ymin;
    dst.rect.width = xmax - xmin;
    dst.rect.height = ymax - ymin;
}

#[no_mangle]
pub extern fn rsvg_bbox_clip (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
    assert! (!raw_dst.is_null ());
    assert! (!raw_src.is_null ());

    let dst: &mut RsvgBbox = unsafe { &mut (*raw_dst) };
    let src: &RsvgBbox = unsafe { &*raw_src };

    if src.virgin {
        return;
    }

    let mut xmin: f64;
    let mut ymin: f64;
    let mut xmax: f64;
    let mut ymax: f64;

    if !dst.virgin {
        xmin = dst.rect.x + dst.rect.width;
        ymin = dst.rect.y + dst.rect.height;
        xmax = dst.rect.x;
        ymax = dst.rect.y;
    } else {
        xmin = 0.0;
        ymin = 0.0;
        xmax = 0.0;
        ymax = 0.0;
    }

    let mut affine = dst.affine;

    affine.invert ();
    affine = cairo::Matrix::multiply (&src.affine, &affine);

    /* This is a trick.  See rsvg_bbox_insert() for a description of how it works. */
    for i in 0..4 {
        let rx: f64 = src.rect.x + src.rect.width * (i % 2) as f64;
        let ry: f64 = src.rect.y + src.rect.height * (i / 2) as f64;
        let x = affine.xx * rx + affine.xy * ry + affine.x0;
        let y = affine.yx * rx + affine.yy * ry + affine.y0;

        if dst.virgin {
            xmin = x;
            xmax = x;
            ymin = y;
            ymax = y;
            dst.virgin = false;
        } else {
            if x < xmin { xmin = x; }
            if x > xmax { xmax = x; }
            if y < ymin { ymin = y; }
            if y > ymax { ymax = y; }
        }
    }

    if xmin < dst.rect.x { xmin = dst.rect.x; }
    if ymin < dst.rect.y { ymin = dst.rect.y; }

    if xmax > dst.rect.x + dst.rect.width { xmax = dst.rect.x + dst.rect.width; }
    if ymax > dst.rect.y + dst.rect.height { ymax = dst.rect.y + dst.rect.height; }

    dst.rect.x = xmin;
    dst.rect.width = xmax - xmin;
    dst.rect.y = ymin;
    dst.rect.y = ymax - ymin;
}
<commit_msg>bbox.rs: Oops, return the correct dst.rect.height<commit_after>extern crate cairo;

use self::cairo::MatrixTrait;

/* Keep this in sync with ../../rsvg-private.h:RsvgBbox */
#[repr(C)]
pub struct RsvgBbox {
    pub rect:   cairo::Rectangle,
    pub affine: cairo::Matrix,
    pub virgin: bool
}

#[no_mangle]
pub extern fn rsvg_bbox_init (raw_bbox: *mut RsvgBbox, raw_matrix: *const cairo::Matrix) {
    assert! (!raw_bbox.is_null ());
    assert! (!raw_matrix.is_null ());

    let bbox: &mut RsvgBbox = unsafe { &mut (*raw_bbox) };

    bbox.virgin = true;
    bbox.affine = unsafe { *raw_matrix };
}

#[no_mangle]
pub extern fn rsvg_bbox_insert (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
    assert! (!raw_dst.is_null ());
    assert! (!raw_src.is_null ());

    let dst: &mut RsvgBbox = unsafe { &mut (*raw_dst) };
    let src: &RsvgBbox = unsafe { &*raw_src };

    if src.virgin {
        return;
    }

    let mut xmin: f64;
    let mut ymin: f64;
    let mut xmax: f64;
    let mut ymax: f64;

    if !dst.virgin {
        xmin = dst.rect.x;
        ymin = dst.rect.y;
        xmax = dst.rect.x + dst.rect.width;
        ymax = dst.rect.y + dst.rect.height;
    } else {
        xmin = 0.0;
        ymin = 0.0;
        xmax = 0.0;
        ymax = 0.0;
    }

    let mut affine = dst.affine;

    affine.invert (); // this will panic!() if it's not invertible... should we check on our own?
    affine = cairo::Matrix::multiply (&src.affine, &affine);

    /* This is a trick.  We want to transform each of the corners of
     * the rectangle defined by src.rect with the affine
     * transformation, and get the bounding box of all the four
     * resulting points.  The modulus and division accomplish this by
     * running through all the combinations of adding or not adding
     * the width/height to the first point src.rect.(x, y).
     */
    for i in 0..4 {
        let rx: f64 = src.rect.x + src.rect.width * (i % 2) as f64;
        let ry: f64 = src.rect.y + src.rect.height * (i / 2) as f64;
        let x: f64  = affine.xx * rx + affine.xy * ry + affine.x0;
        let y: f64  = affine.yx * rx + affine.yy * ry + affine.y0;

        if dst.virgin {
            xmin = x;
            xmax = x;
            ymin = y;
            ymax = y;
            dst.virgin = false;
        } else {
            if x < xmin { xmin = x; }
            if x > xmax { xmax = x; }
            if y < ymin { ymin = y; }
            if y > ymax { ymax = y; }
        }
    }

    dst.rect.x = xmin;
    dst.rect.y = ymin;
    dst.rect.width = xmax - xmin;
    dst.rect.height = ymax - ymin;
}

#[no_mangle]
pub extern fn rsvg_bbox_clip (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
    assert! (!raw_dst.is_null ());
    assert! (!raw_src.is_null ());

    let dst: &mut RsvgBbox = unsafe { &mut (*raw_dst) };
    let src: &RsvgBbox = unsafe { &*raw_src };

    if src.virgin {
        return;
    }

    let mut xmin: f64;
    let mut ymin: f64;
    let mut xmax: f64;
    let mut ymax: f64;

    if !dst.virgin {
        xmin = dst.rect.x + dst.rect.width;
        ymin = dst.rect.y + dst.rect.height;
        xmax = dst.rect.x;
        ymax = dst.rect.y;
    } else {
        xmin = 0.0;
        ymin = 0.0;
        xmax = 0.0;
        ymax = 0.0;
    }

    let mut affine = dst.affine;

    affine.invert ();
    affine = cairo::Matrix::multiply (&src.affine, &affine);

    /* This is a trick.  See rsvg_bbox_insert() for a description of how it works. */
    for i in 0..4 {
        let rx: f64 = src.rect.x + src.rect.width * (i % 2) as f64;
        let ry: f64 = src.rect.y + src.rect.height * (i / 2) as f64;
        let x = affine.xx * rx + affine.xy * ry + affine.x0;
        let y = affine.yx * rx + affine.yy * ry + affine.y0;

        if dst.virgin {
            xmin = x;
            xmax = x;
            ymin = y;
            ymax = y;
            dst.virgin = false;
        } else {
            if x < xmin { xmin = x; }
            if x > xmax { xmax = x; }
            if y < ymin { ymin = y; }
            if y > ymax { ymax = y; }
        }
    }

    if xmin < dst.rect.x { xmin = dst.rect.x; }
    if ymin < dst.rect.y { ymin = dst.rect.y; }

    if xmax > dst.rect.x + dst.rect.width { xmax = dst.rect.x + dst.rect.width; }
    if ymax > dst.rect.y + dst.rect.height { ymax = dst.rect.y + dst.rect.height; }

    dst.rect.x = xmin;
    dst.rect.width = xmax - xmin;
    dst.rect.y = ymin;
    dst.rect.height = ymax - ymin;
}
<|endoftext|>


<commit_before>use std::io::stdio;
use std::io::Process;
use std::io::process;
use std::path::posix::Path;

struct Shell {
    cmd_prompt: ~str,
    cwd: Path
}

impl Shell {
    fn new(prompt_str: &str, cwd: Path) -> Shell {
        Shell {
            cmd_prompt: prompt_str.to_owned(),
            cwd: cwd
        }
    }

    fn start(&mut self) {
        let mut stdin = stdio::stdin();
        loop {
            stdio::print(self.cmd_prompt);
            stdio::flush();

            let line = stdin.read_line().unwrap();
            let cmd_line = line.trim().to_owned();
            let program = cmd_line.splitn(' ', 1).nth(0).expect("no program");

            match program {
                ""      =>  { continue; }
                "\u274c"  =>  { return; }
                _       =>  { self.cmd(cmd_line.clone()); }
                // _ => { println!("You just ran {}", cmd_line) }
            }
        }
    }

    fn cmd(&mut self, cmd_line: ~str) {
        let mut arg_vec = ~[];
        let mut cmd = ~"";
        for (index, raw_s) in cmd_line.split_str("\U0001F345").enumerate() {
            let s = raw_s.trim();
            if s == "" { continue; }
            if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); }
        }
        self.run_cmd(cmd, arg_vec);
    }

    fn run_cmd(&mut self, cmd: ~str, argv: ~[~str]) {
        match cmd.as_slice() {
            &"\U0001F697" => self.cd(argv),
            &"\U0001F4CD" => self.pwd(),
            &"\U0001F50E" => self.execute_program(~"ls", argv),
            &"\U0001F431" => self.execute_program(~"cat", argv),
            &"cat" => self.reject("cat"),
            &"ls" => self.reject("ls"),
            &"pwd" => self.reject("pwd"),
            _ => self.execute_program(cmd, argv)
        }
    }

    fn reject(&mut self, attempted_command: &str) {
        println!("Please do not use {}, it is offensive", attempted_command);
    }

    fn execute_program(&mut self, cmd: ~str, argv: ~[~str]) {
        if self.cmd_exists(cmd) {
            println!("\U0001F3C3  {}", cmd);
            let config = process::ProcessConfig {
                program: cmd,
                args: argv,
                cwd: Some(&self.cwd),
                stdin: process::InheritFd(0),
                stdout: process::InheritFd(1),
                stderr: process::InheritFd(2),
                .. process::ProcessConfig::new()
            };

            let p = Process::configure(config);
            let status = p.unwrap().wait();
            match status {
                process::ExitSignal(st) => println!("\U0001F6B7  {} \u27A1  {}", cmd, st),
                process::ExitStatus(st) => println!("\U0001F6B7  {} \u27A1  {}", cmd, st)
            }
        }
        else {
            println!("Command {} not found.", cmd)
        }
    }

    fn cd(&mut self, path: ~[~str]) {
        if path.len() == 0 {
            println!("Please specify a path to \U0001F697  to.");
            return;
        }
        let p = Path::new(path[0]);
        if !p.is_dir() {
            println!("\U0001F697  could not find that, \U0001F62D  ")
        }
        self.cwd = p;
    }

    fn pwd(&mut self) {
        println!("\u27A1 {} \u2B05  \U0001F4CD", self.cwd.as_str().unwrap());
    }

    fn cmd_exists(&mut self, cmd: &str) -> bool {
        let p = Process::new("which", [cmd.to_owned()]);
        let status = p.unwrap().wait();
        match status {
            process::ExitSignal(st) => st == 0,
            process::ExitStatus(st) => st == 0
        }
    }
}

fn main() {
    println!("\x1bc");
    Shell::new("\U0001f41a  ", std::os::getcwd()).start();
}
<commit_msg>Get shell to compile on latest rust version<commit_after>use std::env;
use std::io::stdin;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

struct Shell {
    cmd_prompt: String,
    cwd: PathBuf
}

impl Shell {
    fn new(prompt_str: &str, cwd: PathBuf) -> Shell {
        Shell {
            cmd_prompt: prompt_str.to_owned(),
            cwd: cwd
        }
    }

    fn start(&mut self) {
        let stdin = stdin();
        loop {
            println!("{}", self.cmd_prompt);

            let mut line = String::new();
            stdin.read_line(&mut line).unwrap();
            let cmd_line = line.trim().to_owned();
            let program = cmd_line.splitn(1, ' ').nth(0).expect("no program");

            match program {
                ""      =>  { continue; }
                "\u{274c}"  =>  { return; }
                _       =>  { self.cmd(cmd_line.clone()); }
                // _ => { println!("You just ran {}", cmd_line) }
            }
        }
    }

    fn cmd(&mut self, cmd_line: String) {
        let mut arg_vec = Vec::new();
        let mut cmd = String::new();
        for (index, raw_s) in cmd_line.split("\u{1F345}").enumerate() {
            let s = raw_s.trim();
            if s == "" { continue; }
            if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); }
        }
        self.run_cmd(cmd, arg_vec);
    }

    fn run_cmd(&mut self, cmd: String, argv: Vec<String>) {
        match &*cmd {
            "\u{1F697}" => self.cd(argv),
            "\u{1F4CD}" => self.pwd(),
            "\u{1F50D}" => self.execute_program("ls".to_string(), argv),
            "\u{1F431}" => self.execute_program("cat".to_string(), argv),
            "cat" => self.reject("cat"),
            "ls" => self.reject("ls"),
            "pwd" => self.reject("pwd"),
            _ => self.execute_program(cmd, argv)
        }
    }

    fn reject(&mut self, attempted_command: &str) {
        println!("Please do not use {}, it is offensive", attempted_command);
    }

    fn execute_program(&mut self, cmd: String, argv: Vec<String>) {
        if self.cmd_exists(&cmd) {
            println!("\u{1F3C3}  {}", cmd);

            let status = Command::new(cmd.clone())
                .args(argv)
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .current_dir(&self.cwd)
                .status()
                .expect("Command not found.");

            println!("\u{1F6B7}  {} \u{27A1}  {}", cmd, status);
        }
        else {
            println!("Command {} not found.", cmd);
        }
    }

    fn cd(&mut self, path: Vec<String>) {
        if path.len() == 0 {
            println!("Please specify a path to \u{1F697}  to.");
            return;
        }
        let p = Path::new(&path[0]);
        if !p.is_dir() {
            println!("\u{1F697}  could not find that, \u{1F62D}  ")
        }
        self.cwd = p.to_path_buf();
    }

    fn pwd(&mut self) {
        println!("\u{27A1} {} \u{2B05}  \u{1F4CD}", self.cwd.display());
    }

    fn cmd_exists(&mut self, cmd: &str) -> bool {
        let p = Command::new("which")
            .arg(cmd.to_owned())
            .output()
            .expect("failed to execute process");
        p.status.success()
    }
}

fn main() {
    println!("\x1bc");
    let path = env::current_dir().unwrap();
    Shell::new("\u{1f41a}  ", path).start();
}
<|endoftext|>


<commit_before><commit_msg>Add PONG method<commit_after><|endoftext|>


<commit_before><commit_msg>Eliminated a call to encoded_size function<commit_after><|endoftext|>


<commit_before><commit_msg>Enforce frame cadence in game loop<commit_after><|endoftext|>


<commit_before><commit_msg>Revert Frames::push_frames() to 1.8 non-async version, avoids sequencing issue<commit_after><|endoftext|>


<commit_before><commit_msg>this log has been disqualified<commit_after><|endoftext|>


<commit_before><commit_msg>minor code format<commit_after><|endoftext|>


<commit_before><commit_msg>Update test<commit_after><|endoftext|>


<commit_before><commit_msg>Document `t_test` module<commit_after><|endoftext|>