<commit_before><commit_msg>added weaver example<commit_after>extern crate rand;
extern crate timely;
extern crate timely_sort;
extern crate differential_dataflow;
extern crate vec_map;
extern crate graph_map;

use rand::{Rng, SeedableRng, StdRng};

use timely::dataflow::*;
use timely::dataflow::operators::*;

use differential_dataflow::{Collection, AsCollection, Data};
use differential_dataflow::operators::*;
use differential_dataflow::collection::LeastUpperBound;

use graph_map::GraphMMap;

type Node = u32;
type Edge = (Node, Node);

fn main() {

    // define a new computational scope, in which to run reach
    timely::execute_from_args(std::env::args(), move |computation| {

        // contruct iterative transaction dataflow, attach reachability query to graph.
        let (mut raw, mut trans, mut query, mut roots, query_probe, roots_probe) = computation.scoped(|scope| {

            // transactional updates to edge collection.
            let (raw_input, raw) = scope.new_input();
            let raw = raw.as_collection();

            // transactional updates to edge collection.
            let (trans_input, trans) = scope.new_input();
            let trans = trans.as_collection();

            // graph contains committed edges, will persist across epochs.
            let (handle, graph) = scope.loop_variable(u64::max_value(), 1);
            let graph = graph.as_collection();

            let aborts = transactional(&trans, &graph);

            // restrict writes to those that commit.
            let writes = trans.filter(|x| !x.1)
                              .map(|x| (x.0, x.2))
                              .antijoin(&aborts)
                              .map(|(_,edge)| edge);

            // define the graph as itself plus any committed changes.
            let graph = raw.concat(&writes);

            graph.inner.connect_loop(handle);

            // read queries against edge collection
            let (query_input, query) = scope.new_input();
            let query = query.as_collection();

            // query the graph, return a probe.
            let query_probe = graph.semijoin_u(&query)
                                   .probe().0;

            // issue reachability queries from various roots
            let (roots_input, roots) = scope.new_input();
            let roots = roots.as_collection();

            // do reach on the graph from the roots, report counts at each distance.
            let result = reach(&graph, &roots);
            let roots_probe = result//.map(|(_,l)| l)
                                    //.consolidate_by(|&x| x)
                                    .probe().0;

            (raw_input, trans_input, query_input, roots_input, query_probe, roots_probe)
        });

        let filename = std::env::args().nth(1).unwrap();
        let graph = GraphMMap::new(&filename);

        if computation.index() == 0 {
            for node in 0 .. graph.nodes() {
                for &edge in graph.edges(node) {
                    raw.send(((node as u32, edge as u32), 1));
                }
            }
        }
        raw.close();

        let next = trans.epoch() + 2;
        trans.advance_to(next);
        query.advance_to(next);
        roots.advance_to(next);

        // do computation for a bit, until we see outputs from each.
        while query_probe.lt(&trans.time()) || roots_probe.lt(&trans.time()) {
            computation.step();
        }

        let seed: &[_] = &[1, 2, 3, 4];
        let mut rng: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions

        let block: u32 = std::env::args().nth(2).unwrap().parse().unwrap();

        let mut reads = Vec::with_capacity(1000);
        while reads.len() < reads.capacity() {
            let mut buffer = vec![];
            for i in 0 .. block as usize {
                let key = rng.gen_range(0, graph.nodes() as u32);
                if i % computation.peers() == computation.index() {
                    buffer.push(key);
                }
            }
            reads.push(buffer);
        }

        let timer = ::std::time::Instant::now();

        for buffer in &reads {
            for &entry in buffer {
                query.send((entry, 1));
            }

            let next = trans.epoch() + 1;
            trans.advance_to(next);
            query.advance_to(next);
            roots.advance_to(next);

            // do computation for a bit, until we see outputs from each.
            while query_probe.lt(&trans.time()) || roots_probe.lt(&trans.time()) {
                computation.step();
            }
        }

        query.close();
        println!("query elapsed: {:?} for 1,000 x {}", timer.elapsed(), block);

        let mut travs = Vec::with_capacity(100);
        while travs.len() < travs.capacity() {
            let mut temp = vec![];
            for _ in 0 .. block {
                temp.push(rng.gen_range(0, graph.nodes() as u32));
            }
            travs.push(temp);
        }

        let mut latencies = vec![];

        let timer = ::std::time::Instant::now();

        for buffer in &travs {
            let inner_timer = ::std::time::Instant::now();
            for &src in buffer {
                roots.send((src, 1));
            }

            let next = trans.epoch() + 1;
            trans.advance_to(next);
            // query.advance_to(next);
            roots.advance_to(next);

            // do computation for a bit, until we see outputs from each.
            while query_probe.lt(&trans.time()) || roots_probe.lt(&trans.time()) {
                computation.step();
            }

            let elapsed = inner_timer.elapsed();
            latencies.push(elapsed.as_secs() * 1000000000 + elapsed.subsec_nanos() as u64);
        }

        roots.close();
        println!("travs elapsed: {:?} for 1,000 x {}", timer.elapsed(), block);

        if computation.index() == 0 {
            latencies[50 ..].sort();
            for &x in latencies[50..].iter() {
                println!("{}", (x as f64) / 1000000000.0f64);
            }
        }

        let mut writes = Vec::with_capacity(1000);
        let index = computation.index();
        let peers = computation.peers();
        let mut t_id = index;

        while writes.len() < writes.capacity() {
            let mut edge_set = vec![];
            for _ in 0 .. block {
                edge_set.push((rng.gen_range(0, graph.nodes() as u32), rng.gen_range(0, graph.nodes() as u32)));
            }
            let mut buffer = vec![];
            for i in 0 .. block as usize {
                let edge1 = edge_set[rng.gen_range(0, edge_set.len())];
                let edge2 = edge_set[rng.gen_range(0, edge_set.len())];
                if i % computation.peers() == computation.index() {
                    buffer.push((t_id, true, edge1));
                    buffer.push((t_id, false, edge2));
                }
                t_id += peers;
            }
            writes.push(buffer);
        }

        let timer = ::std::time::Instant::now();

        for buffer in &writes {
            for &entry in buffer {
                trans.send((entry, 1));
            }

            let next = trans.epoch() + 1;
            trans.advance_to(next);
            // query.advance_to(next);
            // roots.advance_to(next);

            // do computation for a bit, until we see outputs from each.
            while query_probe.lt(&trans.time()) || roots_probe.lt(&trans.time()) {
                computation.step();
            }
        }

        println!("trans elapsed: {:?} for 1,000 x {}", timer.elapsed(), block);

    }).unwrap();
}

// returns pairs (n, s) indicating node n can be reached from node s.
fn reach<G>(edges: &Collection<G, Edge>, roots: &Collection<G, Node>) -> Collection<G, (Node, Node)>
where G: Scope, G::Timestamp: LeastUpperBound {

    // initialize roots as reaching themselves
    let nodes = roots.map(|x| (x, x));

    // repeatedly update reachable nodes
    nodes.iterate(|inner| {

        let edges = edges.enter(&inner.scope());
        let nodes = nodes.enter(&inner.scope());

        inner.join_map(&edges, |_k,&s,&d| (d, s))
             .concat(&nodes)
             .distinct()
     })
}

fn transactional<G, D>(trans: &Collection<G, (usize, bool, D)>, state: &Collection<G, D>) -> Collection<G, usize>
where G: Scope, D: Data+Default, G::Timestamp: LeastUpperBound {

    // we develop the set of transaction ids that must abort,
    // starting from the optimistic assumption that none must.

    trans.filter(|_| false)
         .map(|_| 0)
         .iterate(|abort| {

            // bring in transactions and initial state.
            let trans = trans.enter(&abort.scope());
            let state = state.enter(&abort.scope())
                             .map(|x| (x, 0));

            // reads -> (location, trans_id)
            let reads = trans.filter(|x| x.1 == true)
                             .map(|x| (x.2, x.0));

            // writes -> (location, trans_id), filtered by aborts
            let writes = trans.filter(|x| x.1 == false)
                              .map(|x| (x.0, x.2))
                              .antijoin_u(&abort)
                              .map(|x| (x.1, x.0));

            // cogroup may be the right way to do this,
            // but we can do a join for now.
            let lookup = writes.concat(&state)
                               .join_map(&reads, |key, &tid1, &tid2| (key.clone(), tid1, tid2))
                               .filter(|&(_, tid1, tid2)| tid1 < tid2)
                               .map(|(k, _, tid2)| (k, tid2))
                               .distinct();

            reads.map(|x| (x,()))
                 .antijoin(&lookup)
                 .map(|((_,t),())| t)
                 .distinct_u()
        })

}
<|endoftext|>


<commit_before><commit_msg>Correct precent/percent misspelling<commit_after><|endoftext|>


<commit_before>#![deny(warnings)]
#![deny(missing_docs)]

//! # reqwest
//!
//! The `reqwest` crate provides a convenient, higher-level HTTP Client.
//!
//! It handles many of the things that most people just expect an HTTP client
//! to do for them.
//!
//! - Uses system-native TLS
//! - Plain bodies, JSON, urlencoded, (TODO: multipart)
//! - Customizable redirect policy
//! - (TODO: Cookies)
//!
//! The `reqwest::Client` is synchronous, making it a great fit for
//! applications that only require a few HTTP requests, and wish to handle
//! them synchronously. When [hyper][] releases with asynchronous support,
//! `reqwest` will be updated to use it internally, but still provide a
//! synchronous Client, for convenience. A `reqwest::async::Client` will also
//! be added.
//!
//! ## Making a GET request
//!
//! For a single request, you can use the `get` shortcut method.
//!
//!
//! ```no_run
//! let resp = reqwest::get("https://www.rust-lang.org").unwrap();
//! assert!(resp.status().is_success());
//! ```
//!
//! If you plan to perform multiple requests, it is best to create a [`Client`][client]
//! and reuse it, taking advantage of keep-alive connection pooling.
//!
//! ## Making POST requests (or setting request bodies)
//!
//! There are several ways you can set the body of a request. The basic one is
//! by using the `body()` method of a [`RequestBuilder`][builder]. This lets you set the
//! exact raw bytes of what the body should be. It accepts various types,
//! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom
//! Reader, you can use the `reqwest::Body::new()` constructor.
//!
//! ```no_run
//! let client = reqwest::Client::new().unwrap();
//! let res = client.post("http://httpbin.org/post")
//!     .body("the exact body that is sent")
//!     .send();
//! ```
//!
//! ### Forms
//!
//! It's very common to want to send form data in a request body. This can be
//! done with any type that can be serialized into form data.
//!
//! This can be an array of tuples, or a `HashMap`, or a custom type that
//! implements [`Serialize`][serde].
//!
//! ```no_run
//! // This will POST a body of `foo=bar&baz=quux`
//! let params = [("foo", "bar"), ("baz", "quux")];
//! let client = reqwest::Client::new().unwrap();
//! let res = client.post("http://httpbin.org/post")
//!     .form(&params)
//!     .send();
//! ```
//!
//! ### JSON
//!
//! There is also a `json` method helper on the [`RequestBuilder`][builder] that works in
//! a similar fashion the `form` method. It can take any value that can be
//! serialized into JSON.
//!
//! ```no_run
//! # use std::collections::HashMap;
//! // This will POST a body of `{"lang":"rust","body":"json"}`
//! let mut map = HashMap::new();
//! map.insert("lang", "rust");
//! map.insert("body", "json");
//!
//! let client = reqwest::Client::new().unwrap();
//! let res = client.post("http://httpbin.org/post")
//!     .json(&map)
//!     .send();
//! ```
//!
//! [hyper]: http://hyper.rs
//! [client]: ./struct.Client.html
//! [builder]: ./client/struct.RequestBuilder.html
//! [serde]: http://serde.rs
extern crate hyper;

#[macro_use] extern crate log;
extern crate native_tls;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate url;

pub use hyper::client::IntoUrl;
pub use hyper::Error as HyperError;
pub use hyper::header;
pub use hyper::method::Method;
pub use hyper::status::StatusCode;
pub use hyper::version::HttpVersion;
pub use hyper::Url;
pub use url::ParseError as UrlError;

pub use self::client::{Client, Response, RequestBuilder};
pub use self::error::{Error, Result};
pub use self::body::Body;
pub use self::redirect::RedirectPolicy;

mod body;
mod client;
mod error;
mod redirect;
mod tls;

/// Shortcut method to quickly make a `GET` request.
pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {
    let client = try!(Client::new());
    client.get(url).send()
}

fn _assert_impls() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<Client>();
    assert_sync::<Client>();

    assert_send::<RequestBuilder>();
    assert_send::<Response>();
}
<commit_msg>Re-export Mime<commit_after>#![deny(warnings)]
#![deny(missing_docs)]

//! # reqwest
//!
//! The `reqwest` crate provides a convenient, higher-level HTTP Client.
//!
//! It handles many of the things that most people just expect an HTTP client
//! to do for them.
//!
//! - Uses system-native TLS
//! - Plain bodies, JSON, urlencoded, (TODO: multipart)
//! - Customizable redirect policy
//! - (TODO: Cookies)
//!
//! The `reqwest::Client` is synchronous, making it a great fit for
//! applications that only require a few HTTP requests, and wish to handle
//! them synchronously. When [hyper][] releases with asynchronous support,
//! `reqwest` will be updated to use it internally, but still provide a
//! synchronous Client, for convenience. A `reqwest::async::Client` will also
//! be added.
//!
//! ## Making a GET request
//!
//! For a single request, you can use the `get` shortcut method.
//!
//!
//! ```no_run
//! let resp = reqwest::get("https://www.rust-lang.org").unwrap();
//! assert!(resp.status().is_success());
//! ```
//!
//! If you plan to perform multiple requests, it is best to create a [`Client`][client]
//! and reuse it, taking advantage of keep-alive connection pooling.
//!
//! ## Making POST requests (or setting request bodies)
//!
//! There are several ways you can set the body of a request. The basic one is
//! by using the `body()` method of a [`RequestBuilder`][builder]. This lets you set the
//! exact raw bytes of what the body should be. It accepts various types,
//! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom
//! Reader, you can use the `reqwest::Body::new()` constructor.
//!
//! ```no_run
//! let client = reqwest::Client::new().unwrap();
//! let res = client.post("http://httpbin.org/post")
//!     .body("the exact body that is sent")
//!     .send();
//! ```
//!
//! ### Forms
//!
//! It's very common to want to send form data in a request body. This can be
//! done with any type that can be serialized into form data.
//!
//! This can be an array of tuples, or a `HashMap`, or a custom type that
//! implements [`Serialize`][serde].
//!
//! ```no_run
//! // This will POST a body of `foo=bar&baz=quux`
//! let params = [("foo", "bar"), ("baz", "quux")];
//! let client = reqwest::Client::new().unwrap();
//! let res = client.post("http://httpbin.org/post")
//!     .form(&params)
//!     .send();
//! ```
//!
//! ### JSON
//!
//! There is also a `json` method helper on the [`RequestBuilder`][builder] that works in
//! a similar fashion the `form` method. It can take any value that can be
//! serialized into JSON.
//!
//! ```no_run
//! # use std::collections::HashMap;
//! // This will POST a body of `{"lang":"rust","body":"json"}`
//! let mut map = HashMap::new();
//! map.insert("lang", "rust");
//! map.insert("body", "json");
//!
//! let client = reqwest::Client::new().unwrap();
//! let res = client.post("http://httpbin.org/post")
//!     .json(&map)
//!     .send();
//! ```
//!
//! [hyper]: http://hyper.rs
//! [client]: ./struct.Client.html
//! [builder]: ./client/struct.RequestBuilder.html
//! [serde]: http://serde.rs
extern crate hyper;

#[macro_use] extern crate log;
extern crate native_tls;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate url;

pub use hyper::client::IntoUrl;
pub use hyper::Error as HyperError;
pub use hyper::header;
pub use hyper::mime;
pub use hyper::method::Method;
pub use hyper::status::StatusCode;
pub use hyper::version::HttpVersion;
pub use hyper::Url;
pub use url::ParseError as UrlError;

pub use self::client::{Client, Response, RequestBuilder};
pub use self::error::{Error, Result};
pub use self::body::Body;
pub use self::redirect::RedirectPolicy;

mod body;
mod client;
mod error;
mod redirect;
mod tls;

/// Shortcut method to quickly make a `GET` request.
pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {
    let client = try!(Client::new());
    client.get(url).send()
}

fn _assert_impls() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<Client>();
    assert_sync::<Client>();

    assert_send::<RequestBuilder>();
    assert_send::<Response>();
}
<|endoftext|>


<commit_before><commit_msg>Rename Code to Program<commit_after><|endoftext|>


<commit_before>#![crate_name = "rusoto"]
#![crate_type = "lib"]
#![cfg_attr(feature = "unstable", feature(custom_derive, plugin))]
#![cfg_attr(feature = "unstable", plugin(serde_macros))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding, ptr_arg))]
#![allow(dead_code)]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]

//! Rusoto is an [AWS](https://aws.amazon.com/) SDK for Rust.
//! A high level overview is available in `README.md` at https://github.com/rusoto/rusoto.

extern crate chrono;
extern crate hyper;
#[macro_use] extern crate log;
extern crate openssl;
extern crate regex;
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
extern crate time;
extern crate url;
extern crate xml;

pub use credential::{
    AwsCredentials,
    ChainProvider,
    EnvironmentProvider,
    IamProvider,
    ProfileProvider,
    ProvideAwsCredentials,
    DefaultCredentialsProvider,
    DefaultCredentialsProviderSync,
};
pub use region::{ParseRegionError, Region};
pub use request::{DispatchSignedRequest, HttpResponse, HttpDispatchError};

mod credential;
mod param;
mod region;
mod request;
mod xmlerror;
mod xmlutil;
mod serialization;
#[macro_use] mod signature;

#[cfg(feature = "acm")]
pub mod acm;
#[cfg(feature = "cloudhsm")]
pub mod cloudhsm;
#[cfg(feature = "cloudtrail")]
pub mod cloudtrail;
#[cfg(feature = "codecommit")]
pub mod codecommit;
#[cfg(feature = "codedeploy")]
pub mod codedeploy;
#[cfg(feature = "codepipeline")]
pub mod codepipeline;
#[cfg(feature = "cognito-identity")]
pub mod cognitoidentity;
#[cfg(feature = "config")]
pub mod config;
#[cfg(feature = "datapipeline")]
pub mod datapipeline;
#[cfg(feature = "devicefarm")]
pub mod devicefarm;
#[cfg(feature = "directconnect")]
pub mod directconnect;
#[cfg(feature = "ds")]
pub mod ds;
#[cfg(feature = "dynamodb")]
pub mod dynamodb;
#[cfg(feature = "dynamodbstreams")]
pub mod dynamodbstreams;
#[cfg(feature = "ec2")]
pub mod ec2;
#[cfg(feature = "ecr")]
pub mod ecr;
#[cfg(feature = "ecs")]
pub mod ecs;
#[cfg(feature = "emr")]
pub mod emr;
#[cfg(feature = "elastictranscoder")]
pub mod elastictranscoder;
#[cfg(feature = "events")]
pub mod events;
#[cfg(feature = "firehose")]
pub mod firehose;
#[cfg(feature = "inspector")]
pub mod inspector;
#[cfg(feature = "iot")]
pub mod iot;
#[cfg(feature = "kinesis")]
pub mod kinesis;
#[cfg(feature = "kms")]
pub mod kms;
#[cfg(feature = "logs")]
pub mod logs;
#[cfg(feature = "machinelearning")]
pub mod machinelearning;
#[cfg(feature = "marketplacecommerceanalytics")]
pub mod marketplacecommerceanalytics;
#[cfg(feature = "opsworks")]
pub mod opsworks;
#[cfg(feature = "route53domains")]
pub mod route53domains;
#[cfg(feature = "s3")]
pub mod s3;
#[cfg(feature = "sqs")]
pub mod sqs;
#[cfg(feature = "ssm")]
pub mod ssm;
#[cfg(feature = "storagegateway")]
pub mod storagegateway;
#[cfg(feature = "swf")]
pub mod swf;
#[cfg(feature = "waf")]
pub mod waf;
#[cfg(feature = "workspaces")]
pub mod workspaces;

/*
#[cfg(feature = "gamelift")]
pub mod gamelift;
#[cfg(feature = "support")]
pub mod support;
*/

<commit_msg>docs(rusoto): add DynamoDB code example<commit_after>#![crate_name = "rusoto"]
#![crate_type = "lib"]
#![cfg_attr(feature = "unstable", feature(custom_derive, plugin))]
#![cfg_attr(feature = "unstable", plugin(serde_macros))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding, ptr_arg))]
#![allow(dead_code)]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]

//! Rusoto is an [AWS](https://aws.amazon.com/) SDK for Rust.
//! A high level overview is available in `README.md` at https://github.com/rusoto/rusoto.
//!
//! # Example
//!
//! The following code shows a simple example of using Rusoto's DynamoDB API to
//! list the names of all tables in a database.
//!
//! ```
//! use std::default::Default;
//!
//! use rusoto::{DefaultCredentialsProvider, Region};
//! use rusoto::dynamodb::{DynamoDbClient, ListTablesInput};
//!
//! let provider = DefaultCredentialsProvider::new().unwrap();
//! let client = DynamoDbClient::new(provider, Region::UsEast1);
//! let list_tables_input: ListTablesInput = Default::default();
//!
//! match client.list_tables(&list_tables_input) {
//!     Ok(output) => {
//!         match output.table_names {
//!             Some(table_name_list) => {
//!                 println!("Tables in database:");
//!
//!                 for table_name in table_name_list {
//!                     println!("{}", table_name);
//!                 }
//!             },
//!             None => println!("No tables in database!"),
//!         }
//!     },
//!     Err(error) => {
//!         println!("Error: {:?}", error);
//!     },
//! }

extern crate chrono;
extern crate hyper;
#[macro_use] extern crate log;
extern crate openssl;
extern crate regex;
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
extern crate time;
extern crate url;
extern crate xml;

pub use credential::{
    AwsCredentials,
    ChainProvider,
    EnvironmentProvider,
    IamProvider,
    ProfileProvider,
    ProvideAwsCredentials,
    DefaultCredentialsProvider,
    DefaultCredentialsProviderSync,
};
pub use region::{ParseRegionError, Region};
pub use request::{DispatchSignedRequest, HttpResponse, HttpDispatchError};

mod credential;
mod param;
mod region;
mod request;
mod xmlerror;
mod xmlutil;
mod serialization;
#[macro_use] mod signature;

#[cfg(feature = "acm")]
pub mod acm;
#[cfg(feature = "cloudhsm")]
pub mod cloudhsm;
#[cfg(feature = "cloudtrail")]
pub mod cloudtrail;
#[cfg(feature = "codecommit")]
pub mod codecommit;
#[cfg(feature = "codedeploy")]
pub mod codedeploy;
#[cfg(feature = "codepipeline")]
pub mod codepipeline;
#[cfg(feature = "cognito-identity")]
pub mod cognitoidentity;
#[cfg(feature = "config")]
pub mod config;
#[cfg(feature = "datapipeline")]
pub mod datapipeline;
#[cfg(feature = "devicefarm")]
pub mod devicefarm;
#[cfg(feature = "directconnect")]
pub mod directconnect;
#[cfg(feature = "ds")]
pub mod ds;
#[cfg(feature = "dynamodb")]
pub mod dynamodb;
#[cfg(feature = "dynamodbstreams")]
pub mod dynamodbstreams;
#[cfg(feature = "ec2")]
pub mod ec2;
#[cfg(feature = "ecr")]
pub mod ecr;
#[cfg(feature = "ecs")]
pub mod ecs;
#[cfg(feature = "emr")]
pub mod emr;
#[cfg(feature = "elastictranscoder")]
pub mod elastictranscoder;
#[cfg(feature = "events")]
pub mod events;
#[cfg(feature = "firehose")]
pub mod firehose;
#[cfg(feature = "inspector")]
pub mod inspector;
#[cfg(feature = "iot")]
pub mod iot;
#[cfg(feature = "kinesis")]
pub mod kinesis;
#[cfg(feature = "kms")]
pub mod kms;
#[cfg(feature = "logs")]
pub mod logs;
#[cfg(feature = "machinelearning")]
pub mod machinelearning;
#[cfg(feature = "marketplacecommerceanalytics")]
pub mod marketplacecommerceanalytics;
#[cfg(feature = "opsworks")]
pub mod opsworks;
#[cfg(feature = "route53domains")]
pub mod route53domains;
#[cfg(feature = "s3")]
pub mod s3;
#[cfg(feature = "sqs")]
pub mod sqs;
#[cfg(feature = "ssm")]
pub mod ssm;
#[cfg(feature = "storagegateway")]
pub mod storagegateway;
#[cfg(feature = "swf")]
pub mod swf;
#[cfg(feature = "waf")]
pub mod waf;
#[cfg(feature = "workspaces")]
pub mod workspaces;

/*
#[cfg(feature = "gamelift")]
pub mod gamelift;
#[cfg(feature = "support")]
pub mod support;
*/

<|endoftext|>


<commit_before><commit_msg>adding base code<commit_after><|endoftext|>


<commit_before><commit_msg>Added documentation comments to briefly describe the purpse of the geom and world modules<commit_after><|endoftext|>


<commit_before><commit_msg>Add powershell to easage-completions.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Added artists table.<commit_after><|endoftext|>


<commit_before><commit_msg>Using SSR to block first 10 microseconds of data.<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Only use rand in testing<commit_after><|endoftext|>


<commit_before><commit_msg>Just changed a few flags and layed out the structure I want to use.<commit_after><|endoftext|>


<commit_before><commit_msg>add slug<commit_after>use nom::{Offset, AsBytes, Compare, CompareResult, InputLength, InputIter, Slice};
use std::ops::{Range, RangeFrom, RangeTo, RangeFull};
use inlinable_string::InlinableString;

#[macro_export]
macro_rules! slug {
    (__internal Done, $log:ident, $r:ident, ($rem:expr, $out:expr)) => {
        {
        use $crate::Compare;
        match $r {
            $crate::IResult::Done(rem, out) => {
                if rem.compare($rem) != $crate::CompareResult::Ok {
                    let expected: &str = $rem.into();
                    let found: &str = rem.into();
                    println!("expected {:?}, found {:?}", expected, found);
                    panic!();
                }
                if !out.eq(&$out) {
                    println!("different output: {:?} != {:?}", out, $out);
                    panic!();
                }
                println!("ok");
            },
            $crate::IResult::Error(e) => {
                println!("error: {:?}", e);
                panic!();
            },
            $crate::IResult::Incomplete(e) => {
                println!("incomplete: {:?}", e);
                panic!();
            }
        }

        }
    };

    (__internal Error, $log:ident, $r:ident, ) => {
        match $r {
            $crate::IResult::Done(_, _) => {
                println!("did not fail");
                panic!();
            },
            $crate::IResult::Error(_) => println!("ok"),
            nom::IResult::Incomplete(e) => {
                println!("incomplete: {:?}", e);
                panic!();
            }
        }
    };

    ( $(
        $parser:ident ($case:expr $(, $arg:expr)* ) => $d:tt $( ( $e:expr, $f:expr ) )* ;
        )* ) => {
        $(
            println!("{}({:?})", stringify!($parser), stringify!($case $(,$arg)*));

            let b = $crate::slug::wrap($case.into());
            let r = $parser(b.clone() $(,$arg)*);
            slug!(__internal $d, b, r, $( ($e, $f) )* );
        )*
    }
}

use std;
#[derive(Clone)]
pub struct Slug<'a> {
    // full input data
    data:           &'a str,

    // current slice
    slice:          &'a str,

    line:           usize
}
impl<'a> Slug<'a> {
    pub fn parse<F>(&self) -> Result<F, F::Err> where F: std::str::FromStr {
        self.slice.parse()
    }
    pub fn show(&self) {
        use std::iter::{repeat};

        // offset of slice into data
        let offset = self.slice.as_ptr() as usize - self.data.as_ptr() as usize;
        let line_start = self.data[.. offset]
            .rfind('\n')
            .map(|p| p+1)
            .unwrap_or_else(|| 0);
        let (line, endl) = match self.data[offset ..].find('\n') {
            Some(end) => (&self.data[line_start .. end+offset], '\u{21B5}'),
            None => (&self.data[line_start ..], '\u{2016}')
        };
        let cursor = self.data[line_start .. offset].chars().count();
        let marker: String = repeat(" ").take(cursor).collect();
        println!("line {}\n{}{}\n{}^ position", self.line, line, endl, marker);
    }
    pub fn len(&self) -> usize {
        self.slice.len()
    }
}
impl<'a> PartialEq for Slug<'a> {
    #[inline(always)]
    fn eq(&self, other: &Slug<'a>) -> bool {
        self.slice.eq(other.slice)
    }
}
impl<'a> PartialEq<str> for Slug<'a> {
    #[inline(always)]
    fn eq(&self, other: &str) -> bool {
        self.slice.eq(other)
    }
}
impl<'a, 'b> PartialEq<&'b str> for Slug<'a> {
    #[inline(always)]
    fn eq(&self, other: &&'b str) -> bool {
        self.slice.eq(*other)
    }
}
impl<'a> Into<&'a str> for Slug<'a> {
    #[inline(always)]
    fn into(self) -> &'a str {
        self.slice
    }
}
impl<'a> Into<String> for Slug<'a> {
    fn into(self) -> String {
        self.slice.to_owned()
    }
}
impl<'a> Into<InlinableString> for Slug<'a> {
    fn into(self) -> InlinableString {
        self.slice.into()
    }
}

impl<'a> std::fmt::Debug for Slug<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.slice.fmt(f)
    }
}

impl<'a> AsBytes for Slug<'a> {
    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        self.data.as_bytes()
    }
}
impl<'a, 'b> Compare<&'b str> for Slug<'a> {
    #[inline(always)]
    fn compare(&self, o: &'b str) -> CompareResult {
        self.slice.compare(o)
    }

    #[inline(always)]
    fn compare_no_case(&self, o: &'b str) -> CompareResult {
        self.slice.compare_no_case(o)
    }
}
impl<'a> Slice<Range<usize>> for Slug<'a> {
    #[inline(always)]
    fn slice(&self, r: Range<usize>) -> Slug<'a> {
        let lines = self.slice[.. r.start].chars().filter(|&c| c == '\n').count();
        Slug {
            data:           self.data,
            slice:          self.slice.slice(r),
            line:           self.line + lines
        }
    }
}
impl<'a> Slice<RangeFrom<usize>> for Slug<'a> {
    #[inline(always)]
    fn slice(&self, r: RangeFrom<usize>) -> Slug<'a> {
        let lines = self.slice[.. r.start].chars().filter(|&c| c == '\n').count();
        Slug {
            data:           self.data,
            slice:          self.slice.slice(r),
            line:           self.line + lines
        }
    }
}
impl<'a> Slice<RangeTo<usize>> for Slug<'a> {
    #[inline(always)]
    fn slice(&self, r: RangeTo<usize>) -> Slug<'a> {
        Slug {
            data:           self.data,
            slice:          self.slice.slice(r),
            line:           self.line
        }
    }
}
impl<'a> Slice<RangeFull> for Slug<'a> {
    #[inline(always)]
    fn slice(&self, r: RangeFull) -> Slug<'a> {
        Slug {
            data:           self.data,
            slice:          self.slice,
            line:           self.line
        }
    }
}
impl<'a> Offset for Slug<'a> {
    #[inline(always)]
    fn offset(&self, second: &Slug) -> usize {
        let start = self.slice.as_ptr() as usize;
        let end = second.slice.as_ptr() as usize;

        assert!(end >= start, "negative offset");
        end - start
    }
}
impl<'a> InputLength for Slug<'a> {
    #[inline(always)]
    fn input_len(&self) -> usize {
        self.slice.len()
    }
}
impl<'a> InputIter for Slug<'a> {
    type Item     = char;
    type RawItem  = char;
    type Iter     = std::str::CharIndices<'a>;
    type IterElem = std::str::Chars<'a>;
    #[inline]
    fn iter_indices(&self) -> std::str::CharIndices<'a> {
        self.slice.char_indices()
    }
    #[inline]
    fn iter_elements(&self) -> std::str::Chars<'a> {
      self.slice.chars()
    }
    fn position<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::RawItem) -> bool {
      for (o,c) in self.slice.char_indices() {
        if predicate(c) {
          return Some(o)
        }
      }
      None
    }
    #[inline]
    fn slice_index(&self, count: usize) -> Option<usize> {
      let mut cnt    = 0;
      for (index, _) in self.slice.char_indices() {
        if cnt == count {
          return Some(index)
        }
        cnt += 1;
      }
      None
    }
}
pub fn wrap(data: &str) -> Slug {
    Slug {
        data:           data,
        slice:          data,
        line:           1
    }
}
<|endoftext|>


<commit_before><commit_msg>stage2 run-pass test for #3753<commit_after>// Issue #3656
// Issue Name: pub method preceeded by attribute can't be parsed
// Abstract: Visibility parsing failed when compiler parsing

struct Point {
    x: float,
    y: float
}

pub enum Shape {
    Circle(Point, float),
    Rectangle(Point, Point)
}

pub impl Shape {
    pub fn area(sh: Shape) -> float {
        match sh {
            Circle(_, size) => float::consts::pi * size * size,
            Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y)
        }
    }
}

fn main(){
    let s = Circle(Point { x: 1f, y: 2f }, 3f);
    io::println(fmt!("%f", s.area(s)));
}<|endoftext|>


<commit_before><commit_msg>testsuite: Add test for #4210<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

fn main()
{
    unsafe {
        libc::exit(0);
    }
    error!("ack");
}
<|endoftext|>


<commit_before><commit_msg>add reconnect example<commit_after>use futures_executor::{LocalPool, ThreadPool};
use futures_util::stream::StreamExt;
use lapin::{
    options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection,
    ConnectionProperties, Result,
};
use log::info;
use std::sync::Arc;

fn retry_rabbit_stuff(addr: String, executor: Arc<ThreadPool>) {
    std::thread::sleep(std::time::Duration::from_millis(2000));
    log::debug!("Reconnecting to rabbitmq");
    try_rabbit_stuff(addr, executor);
}

fn try_rabbit_stuff(addr: String, executor: Arc<ThreadPool>) {
    executor.clone().spawn_ok(async move {
        if let Err(err) = rabbit_stuff(addr.clone(), executor.clone()).await {
            log::error!("Error: {}", err);
            retry_rabbit_stuff(addr, executor);
        }
    });
}

async fn rabbit_stuff(addr: String, executor: Arc<ThreadPool>) -> Result<()> {
    let conn = Connection::connect(
        &addr,
        ConnectionProperties::default().with_default_executor(8),
    )
    .await?;

    info!("CONNECTED");

    let channel_a = conn.create_channel().await?;
    let channel_b = conn.create_channel().await?;

    let queue = channel_a
        .queue_declare(
            "hello",
            QueueDeclareOptions::default(),
            FieldTable::default(),
        )
        .await?;

    info!("Declared queue {:?}", queue);

    let mut consumer = channel_b
        .basic_consume(
            "hello",
            "my_consumer",
            BasicConsumeOptions::default(),
            FieldTable::default(),
        )
        .await?;
    executor.spawn_ok(async move {
        info!("will consume");
        while let Some(delivery) = consumer.next().await {
            let (channel, delivery) = delivery.expect("error in consumer");
            channel
                .basic_ack(delivery.delivery_tag, BasicAckOptions::default())
                .await
                .expect("ack");
        }
    });

    let payload = b"Hello world!";

    loop {
        let confirm = channel_a
            .basic_publish(
                "",
                "hello",
                BasicPublishOptions::default(),
                payload.to_vec(),
                BasicProperties::default(),
            )
            .await?
            .await?;
        assert_eq!(confirm, Confirmation::NotRequested);
    }
}

fn main() -> Result<()> {
    if std::env::var("RUST_LOG").is_err() {
        std::env::set_var("RUST_LOG", "info");
    }

    env_logger::init();

    let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
    let executor = Arc::new(ThreadPool::new()?);

    try_rabbit_stuff(addr, executor);

    LocalPool::new().run_until(futures_util::future::pending())
}
<|endoftext|>


<commit_before><commit_msg>Move TDD accountkit to Todo<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Add back client ackmode."<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #78996 - lcnr:cg-promotion, r=RalfJung<commit_after>// run-pass
// tests that promoting expressions containing const parameters is allowed.
#![feature(min_const_generics)]

fn promotion_test<const N: usize>() -> &'static usize {
    &(3 + N)
}

fn main() {
    assert_eq!(promotion_test::<13>(), &16);
}
<|endoftext|>


<commit_before><commit_msg>style: Factor dynamic toolbar max height into layout metrics.<commit_after><|endoftext|>


<commit_before><commit_msg>euler: add rust solution to problem 3<commit_after>use std::num;
use std::vec;

#[test]
fn correct_answer() {
    let factors = prime_factors(600851475143);
    let expected_answer = 6857;
    let computed_answer = *factors.last();
    assert_eq!(computed_answer, expected_answer);
}

fn prime_factors(mut n: int) -> ~[int] {
    let mut divisor = 2;
    let mut factors: ~[int] = ~[];
    while divisor <= num::sqrt(n as float) as int {
        if n%divisor == 0 {
            factors = vec::append_one(factors, divisor);
            n = n / divisor;
            divisor = 2;
        } else {
            divisor += 1;
        }
    }
    factors = vec::append_one(factors, n);
    return factors;
}

fn main() {
    let factors = prime_factors(600851475143);
    let largest_prime_factor = *factors.last();
    println!("largest prime factor == {}", largest_prime_factor);
}
<|endoftext|>


<commit_before><commit_msg>Fix error checking bugs in load_shader.<commit_after><|endoftext|>


<commit_before>use runtime::Runtime;
use storage::backend::{StorageBackendError, StorageBackend};

use module::Module;
use module::ModuleError;
use module::CommandResult;
use module::CommandEnv;

use module::bm::header::build_header;
use module::bm::header::get_tags_from_header;
use storage::json::parser::JsonHeaderParser;
use storage::parser::{Parser, FileHeaderParser};
use storage::file::File;
use ui::file::{FilePrinter, TablePrinter};
use std::vec::IntoIter;

use clap::ArgMatches;
use regex::Regex;

pub fn add_command(module: &Module, env: CommandEnv) -> CommandResult {
    let url = env.matches.value_of("url").unwrap();
    let tags = get_tags(env.rt, env.matches);
    info!("Adding url '{}' with tags '{:?}'", url, tags);

    let header  = build_header(&String::from(url), &tags);
    let file    = File::new_with_header(module, header);
    let parser  = Parser::new(JsonHeaderParser::new(None));
    let putres  = env.bk.put_file(file, &parser);

    putres.map_err(|sberr| {
        let mut err = ModuleError::new("Storage Backend Error");
        err.caused_by = Some(Box::new(sberr));
        err
    })
}

pub fn list_command(module: &Module, env: CommandEnv) -> CommandResult {
    let printer = TablePrinter::new(env.rt.is_verbose(), env.rt.is_debugging());
    let files   = get_filtered_files_from_backend(module, &env);

    debug!("Printing files now");
    printer.print_files(files);

    Ok(())
}

pub fn remove_command(module: &Module, env: CommandEnv) -> CommandResult {
    let checked : bool = run_removal_checking(&env);
    debug!("Checked mode: {}", checked);
    if let Some(id) = get_id(env.rt, env.matches) {
        debug!("Remove by id: {}", id);

        let parser = Parser::new(JsonHeaderParser::new(None));
        let file   = env.bk.get_file_by_id(module, &id, &parser).unwrap();
        debug!("Remove file  : {:?}", file);

        if let Err(e) = env.bk.remove_file(module, file, checked) {
            debug!("Remove failed");
            let mut err = ModuleError::new("Removing file failed");
            err.caused_by = Some(Box::new(e));
            Err(err)
        } else {
            debug!("Remove worked");
            Ok(())
        }
    } else {
        debug!("Remove more than one file");

        let files = get_filtered_files_from_backend(module, &env);
        let nfiles = files.len();
        info!("Removing {} Files", nfiles);

        let errs = files.map(|file| {
                debug!("Remove file: {:?}", file);
                env.bk.remove_file(module, file, checked)
            })
            .filter(|e| e.is_err())
            .map(|e| {
                let err = e.err().unwrap();
                warn!("Error occured in Filesystem operation: {}", err);
                err
            })
            .collect::<Vec<StorageBackendError>>();

        let nerrs = errs.len();

        if nerrs != 0 {
            warn!("{} Errors occured while removing {} files", nerrs, nfiles);
            let moderr = ModuleError::new("File removal failed");

            // TODO : Collect StorageBackendErrors

            Err(moderr)
        } else {
            Ok(())
        }
    }
}

/*
 *
 * Private helpers
 *
 */

fn get_filtered_files_from_backend<'a>(module: &'a Module,
                                       env: &CommandEnv) -> IntoIter<File<'a>>
{
    let parser = Parser::new(JsonHeaderParser::new(None));
    let tags = get_tags(env.rt, env.matches);
    debug!("Tags: {:?}", tags);
    env.bk.iter_files(module, &parser).and_then(|files| {
        let f = files.filter(|file| {
            if tags.len() != 0 {
                debug!("Checking tags of: {:?}", file.id());
                get_tags_from_header(&file.header()).iter()
                    .any(|t| tags.contains(t))
            } else {
                true
            }
        }).filter(|file| {
            debug!("Checking matches of: {:?}", file.id());
            get_matcher(env.rt, env.matches)
                .and_then(|r| Some(file.matches_with(&r)))
                .unwrap_or(true)
        }).collect::<Vec<File>>();
        Some(f)
    }).unwrap_or(Vec::<File>::new()).into_iter()
}

fn get_tags<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Vec<String> {
    debug!("Fetching tags from commandline");
    sub.value_of("tags").and_then(|tags|
                                  Some(tags.split(",")
                                       .into_iter()
                                       .map(|s| s.to_string())
                                       .filter(|e|
                                            if e.contains(" ") {
                                                warn!("Tag contains spaces: '{}'", e);
                                                false
                                            } else {
                                                true
                                            }).collect()
                                      )
                                 ).or(Some(vec![])).unwrap()

}

fn get_matcher<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<Regex> {
    debug!("Fetching matcher from commandline");
    if let Some(s) = sub.value_of("match") {
        if let Ok(r) = Regex::new(s) {
            return Some(r)
        } else {
            error!("Regex error, continuing without regex");
        }
    }
    None

}

fn get_id<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<String> {
    debug!("Fetching id from commandline");
    sub.value_of("id").and_then(|s| Some(String::from(s)))
}

/*
 * Checks whether the commandline call was set to run the removal "checked",
 * so if another entry from the store refers to this ID, do not remove the file.
 */
fn run_removal_checking(env: &CommandEnv) -> bool {
    env.matches.is_present("check")
}
<commit_msg>module/bm/commands: Use FileID::into()<commit_after>use runtime::Runtime;
use storage::backend::{StorageBackendError, StorageBackend};

use module::Module;
use module::ModuleError;
use module::CommandResult;
use module::CommandEnv;

use module::bm::header::build_header;
use module::bm::header::get_tags_from_header;
use storage::json::parser::JsonHeaderParser;
use storage::parser::{Parser, FileHeaderParser};
use storage::file::File;
use ui::file::{FilePrinter, TablePrinter};
use std::vec::IntoIter;

use clap::ArgMatches;
use regex::Regex;

pub fn add_command(module: &Module, env: CommandEnv) -> CommandResult {
    let url = env.matches.value_of("url").unwrap();
    let tags = get_tags(env.rt, env.matches);
    info!("Adding url '{}' with tags '{:?}'", url, tags);

    let header  = build_header(&String::from(url), &tags);
    let file    = File::new_with_header(module, header);
    let parser  = Parser::new(JsonHeaderParser::new(None));
    let putres  = env.bk.put_file(file, &parser);

    putres.map_err(|sberr| {
        let mut err = ModuleError::new("Storage Backend Error");
        err.caused_by = Some(Box::new(sberr));
        err
    })
}

pub fn list_command(module: &Module, env: CommandEnv) -> CommandResult {
    let printer = TablePrinter::new(env.rt.is_verbose(), env.rt.is_debugging());
    let files   = get_filtered_files_from_backend(module, &env);

    debug!("Printing files now");
    printer.print_files(files);

    Ok(())
}

pub fn remove_command(module: &Module, env: CommandEnv) -> CommandResult {
    let checked : bool = run_removal_checking(&env);
    debug!("Checked mode: {}", checked);
    if let Some(id) = get_id(env.rt, env.matches) {
        debug!("Remove by id: {}", id);

        let parser = Parser::new(JsonHeaderParser::new(None));
        let file   = env.bk.get_file_by_id(module, &id.into(), &parser).unwrap();
        debug!("Remove file  : {:?}", file);

        if let Err(e) = env.bk.remove_file(module, file, checked) {
            debug!("Remove failed");
            let mut err = ModuleError::new("Removing file failed");
            err.caused_by = Some(Box::new(e));
            Err(err)
        } else {
            debug!("Remove worked");
            Ok(())
        }
    } else {
        debug!("Remove more than one file");

        let files = get_filtered_files_from_backend(module, &env);
        let nfiles = files.len();
        info!("Removing {} Files", nfiles);

        let errs = files.map(|file| {
                debug!("Remove file: {:?}", file);
                env.bk.remove_file(module, file, checked)
            })
            .filter(|e| e.is_err())
            .map(|e| {
                let err = e.err().unwrap();
                warn!("Error occured in Filesystem operation: {}", err);
                err
            })
            .collect::<Vec<StorageBackendError>>();

        let nerrs = errs.len();

        if nerrs != 0 {
            warn!("{} Errors occured while removing {} files", nerrs, nfiles);
            let moderr = ModuleError::new("File removal failed");

            // TODO : Collect StorageBackendErrors

            Err(moderr)
        } else {
            Ok(())
        }
    }
}

/*
 *
 * Private helpers
 *
 */

fn get_filtered_files_from_backend<'a>(module: &'a Module,
                                       env: &CommandEnv) -> IntoIter<File<'a>>
{
    let parser = Parser::new(JsonHeaderParser::new(None));
    let tags = get_tags(env.rt, env.matches);
    debug!("Tags: {:?}", tags);
    env.bk.iter_files(module, &parser).and_then(|files| {
        let f = files.filter(|file| {
            if tags.len() != 0 {
                debug!("Checking tags of: {:?}", file.id());
                get_tags_from_header(&file.header()).iter()
                    .any(|t| tags.contains(t))
            } else {
                true
            }
        }).filter(|file| {
            debug!("Checking matches of: {:?}", file.id());
            get_matcher(env.rt, env.matches)
                .and_then(|r| Some(file.matches_with(&r)))
                .unwrap_or(true)
        }).collect::<Vec<File>>();
        Some(f)
    }).unwrap_or(Vec::<File>::new()).into_iter()
}

fn get_tags<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Vec<String> {
    debug!("Fetching tags from commandline");
    sub.value_of("tags").and_then(|tags|
                                  Some(tags.split(",")
                                       .into_iter()
                                       .map(|s| s.to_string())
                                       .filter(|e|
                                            if e.contains(" ") {
                                                warn!("Tag contains spaces: '{}'", e);
                                                false
                                            } else {
                                                true
                                            }).collect()
                                      )
                                 ).or(Some(vec![])).unwrap()

}

fn get_matcher<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<Regex> {
    debug!("Fetching matcher from commandline");
    if let Some(s) = sub.value_of("match") {
        if let Ok(r) = Regex::new(s) {
            return Some(r)
        } else {
            error!("Regex error, continuing without regex");
        }
    }
    None

}

fn get_id<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<String> {
    debug!("Fetching id from commandline");
    sub.value_of("id").and_then(|s| Some(String::from(s)))
}

/*
 * Checks whether the commandline call was set to run the removal "checked",
 * so if another entry from the store refers to this ID, do not remove the file.
 */
fn run_removal_checking(env: &CommandEnv) -> bool {
    env.matches.is_present("check")
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #90936 - JohnTitor:issue-80772, r=Mark-Simulacrum<commit_after>// check-pass

trait SomeTrait {}

pub struct Exhibit {
    constant: usize,
    factory: fn(&usize) -> Box<dyn SomeTrait>,
}

pub const A_CONSTANT: &[Exhibit] = &[
    Exhibit {
        constant: 1,
        factory: |_| unimplemented!(),
    },
    Exhibit {
        constant: "Hello world".len(),
        factory: |_| unimplemented!(),
    },
];

fn main() {}
<|endoftext|>


<commit_before><commit_msg>support offline access token<commit_after><|endoftext|>


<commit_before>/*
Module: generic_os

Some miscellaneous platform functions.

These should be rolled into another module.
*/

import core::option;

// Wow, this is an ugly way to write doc comments

#[cfg(bogus)]
#[doc = "Get the value of an environment variable"]
fn getenv(n: str) -> option<str> { }

#[cfg(bogus)]
#[doc = "Set the value of an environment variable"]
fn setenv(n: str, v: str) { }

fn env() -> [(str,str)] {
    let pairs = [];
    for p in os::rustrt::rust_env_pairs() {
        let vs = str::splitn_char(p, '=', 1u);
        assert vec::len(vs) == 2u;
        pairs += [(vs[0], vs[1])];
    }
    ret pairs;
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn getenv(n: str) -> option<str> unsafe {
    let s = str::as_buf(n, {|buf| os::libc::getenv(buf) });
    ret if unsafe::reinterpret_cast(s) == 0 {
            option::none::<str>
        } else {
            let s = unsafe::reinterpret_cast(s);
            option::some::<str>(str::from_cstr(s))
        };
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn setenv(n: str, v: str) {
    // FIXME (868)
    str::as_buf(
        n,
        // FIXME (868)
        {|nbuf|
            str::as_buf(
                v,
                {|vbuf|
                    os::libc::setenv(nbuf, vbuf, 1i32)})});
}

#[cfg(target_os = "win32")]
fn getenv(n: str) -> option<str> {
    let nsize = 256u;
    while true {
        let v: [u8] = [];
        vec::reserve(v, nsize);
        let res =
            str::as_buf(n,
                        {|nbuf|
                            unsafe {
                            let vbuf = vec::to_ptr(v);
                            os::kernel32::GetEnvironmentVariableA(nbuf, vbuf,
                                                                  nsize)
                        }
                        });
        if res == 0u {
            ret option::none;
        } else if res < nsize {
            unsafe {
                vec::unsafe::set_len(v, res);
            }
            ret option::some(str::from_bytes(v)); // UTF-8 or fail
        } else { nsize = res; }
    }
    fail;
}

#[cfg(target_os = "win32")]
fn setenv(n: str, v: str) {
    // FIXME (868)
    let _: () =
        str::as_buf(n, {|nbuf|
            let _: () =
                str::as_buf(v, {|vbuf|
                    os::kernel32::SetEnvironmentVariableA(nbuf, vbuf);
                });
        });
}

#[cfg(test)]
mod tests {

    fn make_rand_name() -> str {
        import rand;
        let rng: rand::rng = rand::mk_rng();
        let n = "TEST" + rng.gen_str(10u);
        assert option::is_none(getenv(n));
        n
    }

    #[test]
    #[ignore(reason = "fails periodically on mac")]
    fn test_setenv() {
        let n = make_rand_name();
        setenv(n, "VALUE");
        assert getenv(n) == option::some("VALUE");
    }

    #[test]
    #[ignore(reason = "fails periodically on mac")]
    fn test_setenv_overwrite() {
        let n = make_rand_name();
        setenv(n, "1");
        setenv(n, "2");
        assert getenv(n) == option::some("2");
        setenv(n, "");
        assert getenv(n) == option::some("");
    }

    // Windows GetEnvironmentVariable requires some extra work to make sure
    // the buffer the variable is copied into is the right size
    #[test]
    #[ignore(reason = "fails periodically on mac")]
    fn test_getenv_big() {
        let s = "";
        let i = 0;
        while i < 100 { s += "aaaaaaaaaa"; i += 1; }
        let n = make_rand_name();
        setenv(n, s);
        log(debug, s);
        assert getenv(n) == option::some(s);
    }

    #[test]
    fn test_get_exe_path() {
        let path = os::get_exe_path();
        assert option::is_some(path);
        let path = option::get(path);
        log(debug, path);

        // Hard to test this function
        if os::target_os() != "win32" {
            assert str::starts_with(path, fs::path_sep());
        } else {
            assert path[1] == ':' as u8;
        }
    }

    #[test]
    fn test_env_getenv() {
        let e = env();
        assert vec::len(e) > 0u;
        for (n, v) in e {
            log(debug, n);
            let v2 = getenv(n);
            // MingW seems to set some funky environment variables like
            // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
            // from env() but not visible from getenv().
            assert option::is_none(v2) || v2 == option::some(v);
        }
    }

    #[test]
    fn test_env_setenv() {
        let n = make_rand_name();

        let e = env();
        setenv(n, "VALUE");
        assert !vec::contains(e, (n, "VALUE"));

        e = env();
        assert vec::contains(e, (n, "VALUE"));
    }
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>std: vec::to_ptr -> vec::unsafe::to_ptr<commit_after>/*
Module: generic_os

Some miscellaneous platform functions.

These should be rolled into another module.
*/

import core::option;

// Wow, this is an ugly way to write doc comments

#[cfg(bogus)]
#[doc = "Get the value of an environment variable"]
fn getenv(n: str) -> option<str> { }

#[cfg(bogus)]
#[doc = "Set the value of an environment variable"]
fn setenv(n: str, v: str) { }

fn env() -> [(str,str)] {
    let pairs = [];
    for p in os::rustrt::rust_env_pairs() {
        let vs = str::splitn_char(p, '=', 1u);
        assert vec::len(vs) == 2u;
        pairs += [(vs[0], vs[1])];
    }
    ret pairs;
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn getenv(n: str) -> option<str> unsafe {
    let s = str::as_buf(n, {|buf| os::libc::getenv(buf) });
    ret if unsafe::reinterpret_cast(s) == 0 {
            option::none::<str>
        } else {
            let s = unsafe::reinterpret_cast(s);
            option::some::<str>(str::from_cstr(s))
        };
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn setenv(n: str, v: str) {
    // FIXME (868)
    str::as_buf(
        n,
        // FIXME (868)
        {|nbuf|
            str::as_buf(
                v,
                {|vbuf|
                    os::libc::setenv(nbuf, vbuf, 1i32)})});
}

#[cfg(target_os = "win32")]
fn getenv(n: str) -> option<str> {
    let nsize = 256u;
    while true {
        let v: [u8] = [];
        vec::reserve(v, nsize);
        let res =
            str::as_buf(n,
                        {|nbuf|
                            unsafe {
                            let vbuf = vec::unsafe::to_ptr(v);
                            os::kernel32::GetEnvironmentVariableA(nbuf, vbuf,
                                                                  nsize)
                        }
                        });
        if res == 0u {
            ret option::none;
        } else if res < nsize {
            unsafe {
                vec::unsafe::set_len(v, res);
            }
            ret option::some(str::from_bytes(v)); // UTF-8 or fail
        } else { nsize = res; }
    }
    fail;
}

#[cfg(target_os = "win32")]
fn setenv(n: str, v: str) {
    // FIXME (868)
    let _: () =
        str::as_buf(n, {|nbuf|
            let _: () =
                str::as_buf(v, {|vbuf|
                    os::kernel32::SetEnvironmentVariableA(nbuf, vbuf);
                });
        });
}

#[cfg(test)]
mod tests {

    fn make_rand_name() -> str {
        import rand;
        let rng: rand::rng = rand::mk_rng();
        let n = "TEST" + rng.gen_str(10u);
        assert option::is_none(getenv(n));
        n
    }

    #[test]
    #[ignore(reason = "fails periodically on mac")]
    fn test_setenv() {
        let n = make_rand_name();
        setenv(n, "VALUE");
        assert getenv(n) == option::some("VALUE");
    }

    #[test]
    #[ignore(reason = "fails periodically on mac")]
    fn test_setenv_overwrite() {
        let n = make_rand_name();
        setenv(n, "1");
        setenv(n, "2");
        assert getenv(n) == option::some("2");
        setenv(n, "");
        assert getenv(n) == option::some("");
    }

    // Windows GetEnvironmentVariable requires some extra work to make sure
    // the buffer the variable is copied into is the right size
    #[test]
    #[ignore(reason = "fails periodically on mac")]
    fn test_getenv_big() {
        let s = "";
        let i = 0;
        while i < 100 { s += "aaaaaaaaaa"; i += 1; }
        let n = make_rand_name();
        setenv(n, s);
        log(debug, s);
        assert getenv(n) == option::some(s);
    }

    #[test]
    fn test_get_exe_path() {
        let path = os::get_exe_path();
        assert option::is_some(path);
        let path = option::get(path);
        log(debug, path);

        // Hard to test this function
        if os::target_os() != "win32" {
            assert str::starts_with(path, fs::path_sep());
        } else {
            assert path[1] == ':' as u8;
        }
    }

    #[test]
    fn test_env_getenv() {
        let e = env();
        assert vec::len(e) > 0u;
        for (n, v) in e {
            log(debug, n);
            let v2 = getenv(n);
            // MingW seems to set some funky environment variables like
            // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
            // from env() but not visible from getenv().
            assert option::is_none(v2) || v2 == option::some(v);
        }
    }

    #[test]
    fn test_env_setenv() {
        let n = make_rand_name();

        let e = env();
        setenv(n, "VALUE");
        assert !vec::contains(e, (n, "VALUE"));

        e = env();
        assert vec::contains(e, (n, "VALUE"));
    }
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>Remove `convert` feature<commit_after><|endoftext|>


<commit_before><commit_msg>sample rust executable<commit_after>fn main() {
	println!("platypie");
}
<|endoftext|>


<commit_before><commit_msg>feat(--force): Allow forceful overwrite of files<commit_after><|endoftext|>


<commit_before><commit_msg>More explicit variable's name<commit_after><|endoftext|>


<commit_before><commit_msg>Added extension stripping.<commit_after><|endoftext|>


<commit_before><commit_msg>Parse schedules.<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Still phone_number_util<commit_after><|endoftext|>


<commit_before><commit_msg>First hello world in rust<commit_after><|endoftext|>


<commit_before>#![crate_name = "clog"]
#![feature(plugin)]
#![plugin(regex_macros)]

extern crate regex;
extern crate time;

extern crate clap;

use git::LogReaderConfig;
use log_writer::{ LogWriter, LogWriterOptions };
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::borrow::ToOwned;

use clap::{App, Arg};

mod common;
mod git;
mod log_writer;
mod section_builder;
mod format_util;

fn main () {
    // Pull version from Cargo.toml
    let version = format!("{}.{}.{}{}",
                          env!("CARGO_PKG_VERSION_MAJOR"),
                          env!("CARGO_PKG_VERSION_MINOR"),
                          env!("CARGO_PKG_VERSION_PATCH"),
                          option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
    let matches = App::new("clog")
        .version(&version[..])
        .about("a conventional changelog for the rest of us")
        .arg(Arg::new("repository")
            .short("r")
            .long("repository")
            .takes_value(true)
            .required(true)
            .help("e.g. https://github.com/thoughtram/clog"))
        .arg(Arg::new("setversion")
            .long("setversion")
            .help("e.g. 1.0.1")
            .takes_value(true))
        .arg(Arg::new("subtitle")
            .long("subtitle")
            .help("e.g. crazy-release-title")
            .takes_value(true)
            .required(true))
        .arg(Arg::new("from")
            .help("e.g. 12a8546")
            .long("from")
            .required(true)
            .takes_value(true))
        .arg(Arg::new("to")
            .long("to")
            .help("e.g. 8057684")
            .takes_value(true)
            .required(true))
        .arg(Arg::new("from-latest-tag")
            .long("from-latest-tag")
            .help("uses the latest tag as starting point (ignores other --from parameters)")
            .mutually_excludes("from"))
        .get_matches();

    let start_nsec = time::get_time().nsec;

    let log_reader_config = LogReaderConfig {
        grep: "^feat|^fix|BREAKING'".to_owned(),
        format: "%H%n%s%n%b%n==END==".to_owned(),
        from: if matches.is_present("from-latest-tag") { Some(git::get_latest_tag()) } else { Some(matches.value_of("from").unwrap().to_owned()) },
        to: matches.value_of("to").unwrap().to_owned()
    };

    let commits = git::get_log_entries(log_reader_config);

    let sections = section_builder::build_sections(commits.clone());

    let mut contents = String::new();
    match File::open(&Path::new("changelog.md")).ok().expect("couldn't open changelog.md").read_to_string(&mut contents) {
        Ok(_) => (),
        Err(_) => contents = "".to_owned()
    }

    let mut file = File::create(&Path::new("changelog.md")).ok().unwrap();
    let mut writer = LogWriter::new(&mut file, LogWriterOptions {
        repository_link: matches.value_of("repository").unwrap(),
        version: if matches.is_present("setversion") {
                    matches.value_of("setversion").unwrap().to_owned()
                } else {
                    format_util::get_short_hash(&git::get_last_commit()[..]).to_owned()
                },
        subtitle: matches.value_of("subtitle").unwrap().to_owned()
    });

    writer.write_header().ok().expect("failed to write header");
    writer.write_section("Bug Fixes", &sections.fixes).ok().expect("failed to write bugfixes");;
    writer.write_section("Features", &sections.features).ok().expect("failed to write features");;
    writer.write(&contents[..]).ok().expect("failed to write contents");;

    let end_nsec = time::get_time().nsec;
    let elapsed_mssec = (end_nsec - start_nsec) / 1000000;
    println!("changelog updated. (took {} ms)", elapsed_mssec);
}
<commit_msg>fix(main): make --to param optional<commit_after>#![crate_name = "clog"]
#![feature(plugin)]
#![plugin(regex_macros)]

extern crate regex;
extern crate time;

extern crate clap;

use git::LogReaderConfig;
use log_writer::{ LogWriter, LogWriterOptions };
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::borrow::ToOwned;

use clap::{App, Arg};

mod common;
mod git;
mod log_writer;
mod section_builder;
mod format_util;

fn main () {
    // Pull version from Cargo.toml
    let version = format!("{}.{}.{}{}",
                          env!("CARGO_PKG_VERSION_MAJOR"),
                          env!("CARGO_PKG_VERSION_MINOR"),
                          env!("CARGO_PKG_VERSION_PATCH"),
                          option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
    let matches = App::new("clog")
        .version(&version[..])
        .about("a conventional changelog for the rest of us")
        .arg(Arg::new("repository")
            .short("r")
            .long("repository")
            .takes_value(true)
            .required(true)
            .help("e.g. https://github.com/thoughtram/clog"))
        .arg(Arg::new("setversion")
            .long("setversion")
            .help("e.g. 1.0.1")
            .takes_value(true))
        .arg(Arg::new("subtitle")
            .long("subtitle")
            .help("e.g. crazy-release-title")
            .takes_value(true)
            .required(true))
        .arg(Arg::new("from")
            .help("e.g. 12a8546")
            .long("from")
            .required(true)
            .takes_value(true))
        .arg(Arg::new("to")
            .long("to")
            .help("e.g. 8057684")
            .takes_value(true))
        .arg(Arg::new("from-latest-tag")
            .long("from-latest-tag")
            .help("uses the latest tag as starting point (ignores other --from parameters)")
            .mutually_excludes("from"))
        .get_matches();

    let start_nsec = time::get_time().nsec;

    let log_reader_config = LogReaderConfig {
        grep: "^feat|^fix|BREAKING'".to_owned(),
        format: "%H%n%s%n%b%n==END==".to_owned(),
        from: if matches.is_present("from-latest-tag") { Some(git::get_latest_tag()) } else { Some(matches.value_of("from").unwrap().to_owned()) },
        to: matches.value_of("to").unwrap_or("").to_owned()
    };

    let commits = git::get_log_entries(log_reader_config);

    let sections = section_builder::build_sections(commits.clone());

    let mut contents = String::new();
    match File::open(&Path::new("changelog.md")).ok().expect("couldn't open changelog.md").read_to_string(&mut contents) {
        Ok(_) => (),
        Err(_) => contents = "".to_owned()
    }

    let mut file = File::create(&Path::new("changelog.md")).ok().unwrap();
    let mut writer = LogWriter::new(&mut file, LogWriterOptions {
        repository_link: matches.value_of("repository").unwrap(),
        version: if matches.is_present("setversion") {
                    matches.value_of("setversion").unwrap().to_owned()
                } else {
                    format_util::get_short_hash(&git::get_last_commit()[..]).to_owned()
                },
        subtitle: matches.value_of("subtitle").unwrap().to_owned()
    });

    writer.write_header().ok().expect("failed to write header");
    writer.write_section("Bug Fixes", &sections.fixes).ok().expect("failed to write bugfixes");;
    writer.write_section("Features", &sections.features).ok().expect("failed to write features");;
    writer.write(&contents[..]).ok().expect("failed to write contents");;

    let end_nsec = time::get_time().nsec;
    let elapsed_mssec = (end_nsec - start_nsec) / 1000000;
    println!("changelog updated. (took {} ms)", elapsed_mssec);
}
<|endoftext|>


<commit_before><commit_msg>Returning tuple with (value, status)<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for kelvin -> celsius conversion<commit_after><|endoftext|>


<commit_before><commit_msg>Find home<commit_after><|endoftext|>


<commit_before><commit_msg>made a box that moves with ncurses<commit_after><|endoftext|>


<commit_before><commit_msg>Add unwrapping of beta to sphinx_packet_unwrap<commit_after><|endoftext|>


<commit_before><commit_msg>Fix(syncignore): Don't sync Thumbs.db<commit_after><|endoftext|>


<commit_before><commit_msg>tests(SubCommands): adds tests for subcmds after mult args<commit_after><|endoftext|>


<commit_before><commit_msg>drawing images is leaving artifacts<commit_after><|endoftext|>


<commit_before><commit_msg>yaaay day 7a done<commit_after><|endoftext|>


<commit_before><commit_msg>Bundled channels, emojis, and message processing<commit_after><|endoftext|>


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

extern crate getopts;
extern crate image;

use std::default::Default;
use std::old_io::fs::File;

mod css;
mod dom;
mod html;
mod layout;
mod style;
mod painting;
mod pdf;

fn main() {
    // Parse command-line options:
    let mut opts = getopts::Options::new();
    opts.optopt("h", "html", "HTML document", "FILENAME");
    opts.optopt("c", "css", "CSS stylesheet", "FILENAME");
    opts.optopt("o", "output", "Output file", "FILENAME");
    opts.optopt("f", "format", "Output file format", "png | pdf");

    let matches = match opts.parse(std::env::args().skip(1)) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string())
    };

    let png = match matches.opt_str("f") {
        None => true,
        Some(format) => match &*format {
            "png" => true,
            "pdf" => false,
            _ => panic!("Unknow output format: {}", format),
        }
    };

    // Read input files:
    let read_source = |&: arg_filename: Option<String>, default_filename: &str| {
        let path = match arg_filename {
            Some(ref filename) => &**filename,
            None => default_filename,
        };
        File::open(&Path::new(path)).read_to_string().unwrap()
    };
    let html = read_source(matches.opt_str("h"), "examples/test.html");
    let css  = read_source(matches.opt_str("c"), "examples/test.css");

    // Since we don't have an actual window, hard-code the "viewport" size.
    let initial_containing_block = layout::Dimensions {
        content: layout::Rect { x: 0.0, y: 0.0, width: 800.0, height: 600.0 },
        padding: Default::default(),
        border: Default::default(),
        margin: Default::default(),
    };

    // Parsing and rendering:
    let root_node = html::parse(html);
    let stylesheet = css::parse(css);
    let style_root = style::style_tree(&root_node, &stylesheet);
    let layout_root = layout::layout_tree(&style_root, initial_containing_block);

    // Create the output file:
    let default_filename = if png { "output.png" } else { "output.pdf" };
    let filename = matches.opt_str("o").unwrap_or(default_filename.to_string());
    let mut file = File::create(&Path::new(&*filename)).unwrap();

    let result_ok;
    if png {
        let canvas = painting::paint(&layout_root, initial_containing_block.content);

        // Save an image:
        let (w, h) = (canvas.width as u32, canvas.height as u32);
        let buffer: Vec<image::Rgba<u8>> = unsafe { std::mem::transmute(canvas.pixels) };
        let img = image::ImageBuffer::from_fn(w, h, Box::new(|&: x: u32, y: u32| buffer[(y * w + x) as usize]));

        result_ok = image::ImageRgba8(img).save(&mut file, image::PNG).is_ok();
    } else {
        result_ok = pdf::render(&layout_root, initial_containing_block.content, &mut file).is_ok();
    }

    if result_ok {
        println!("Saved output as {}", filename)
    } else {
        println!("Error saving output as {}", filename)
    }
}
<commit_msg>Update closure syntax<commit_after>#![feature(core, std_misc, collections, env, path, io)]

extern crate getopts;
extern crate image;

use std::default::Default;
use std::old_io::fs::File;

mod css;
mod dom;
mod html;
mod layout;
mod style;
mod painting;
mod pdf;

fn main() {
    // Parse command-line options:
    let mut opts = getopts::Options::new();
    opts.optopt("h", "html", "HTML document", "FILENAME");
    opts.optopt("c", "css", "CSS stylesheet", "FILENAME");
    opts.optopt("o", "output", "Output file", "FILENAME");
    opts.optopt("f", "format", "Output file format", "png | pdf");

    let matches = match opts.parse(std::env::args().skip(1)) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string())
    };

    let png = match matches.opt_str("f") {
        None => true,
        Some(format) => match &*format {
            "png" => true,
            "pdf" => false,
            _ => panic!("Unknow output format: {}", format),
        }
    };

    // Read input files:
    let read_source = |arg_filename: Option<String>, default_filename: &str| {
        let path = match arg_filename {
            Some(ref filename) => &**filename,
            None => default_filename,
        };
        File::open(&Path::new(path)).read_to_string().unwrap()
    };
    let html = read_source(matches.opt_str("h"), "examples/test.html");
    let css  = read_source(matches.opt_str("c"), "examples/test.css");

    // Since we don't have an actual window, hard-code the "viewport" size.
    let initial_containing_block = layout::Dimensions {
        content: layout::Rect { x: 0.0, y: 0.0, width: 800.0, height: 600.0 },
        padding: Default::default(),
        border: Default::default(),
        margin: Default::default(),
    };

    // Parsing and rendering:
    let root_node = html::parse(html);
    let stylesheet = css::parse(css);
    let style_root = style::style_tree(&root_node, &stylesheet);
    let layout_root = layout::layout_tree(&style_root, initial_containing_block);

    // Create the output file:
    let default_filename = if png { "output.png" } else { "output.pdf" };
    let filename = matches.opt_str("o").unwrap_or(default_filename.to_string());
    let mut file = File::create(&Path::new(&*filename)).unwrap();

    let result_ok;
    if png {
        let canvas = painting::paint(&layout_root, initial_containing_block.content);

        // Save an image:
        let (w, h) = (canvas.width as u32, canvas.height as u32);
        let buffer: Vec<image::Rgba<u8>> = unsafe { std::mem::transmute(canvas.pixels) };
        let img = image::ImageBuffer::from_fn(w, h, Box::new(move |x: u32, y: u32| buffer[(y * w + x) as usize]));

        result_ok = image::ImageRgba8(img).save(&mut file, image::PNG).is_ok();
    } else {
        result_ok = pdf::render(&layout_root, initial_containing_block.content, &mut file).is_ok();
    }

    if result_ok {
        println!("Saved output as {}", filename)
    } else {
        println!("Error saving output as {}", filename)
    }
}
<|endoftext|>


<commit_before><commit_msg>Added preorder and postorder traversal methods to the ast<commit_after><|endoftext|>


<commit_before><commit_msg>sharp rectangles set<commit_after><|endoftext|>


<commit_before><commit_msg>Add argument forwarding for --ignore-ids<commit_after><|endoftext|>


<commit_before><commit_msg>fetch current version from Cargo.toml<commit_after><|endoftext|>


<commit_before><commit_msg>wip: now game uses KeyDown as KeyPress<commit_after><|endoftext|>


<commit_before><commit_msg>Added a check for a polygon engulfing a rectangle or a rectangle engulfing a polygon<commit_after><|endoftext|>


<commit_before>use redox::Box;
use redox::fs::file::File;
use redox::io::{Read, Write, Seek, SeekFrom};
use redox::mem;
use redox::net::*;
use redox::ptr;
use redox::rand;
use redox::slice;
use redox::{str, String, ToString};
use redox::to_num::*;
use redox::Vec;

/// Ethernet resource
pub struct Resource {
    /// The network
    network: Box<Resource>,
    /// The data
    data: Vec<u8>,
    /// The MAC addresss
    peer_addr: MACAddr,
    /// The ethernet type
    ethertype: u16,
}

impl Resource {
    fn dup(&self) -> Option<Box<Self>> {
        match self.network.dup() {
            Some(network) => Some(box Resource {
                network: network,
                data: self.data.clone(),
                peer_addr: self.peer_addr,
                ethertype: self.ethertype,
            }),
            None => None
        }
    }

    pub fn path(&self, buf: &mut [u8]) -> Option<usize> {
        let path = format!("ethernet://{}/{}", self.peer_addr.to_string(), String::from_num_radix(self.ethertype as usize, 16));

        let mut i = 0;
        for b in path.bytes() {
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            } else {
                break;
            }
        }

        Some(i)
    }

    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        /*
        if self.data.len() > 0 {
            let mut bytes: Vec<u8> = Vec::new();
            swap(&mut self.data, &mut bytes);
            vec.push_all(&bytes);
            return Some(bytes.len());
        }

        loop {
            let mut bytes: Vec<u8> = Vec::new();
            match self.network.read_to_end(&mut bytes) {
                Some(_) => {
                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                        if frame.header.ethertype.get() == self.ethertype &&
                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) &&
                           (frame.header.src.equals(self.peer_addr) ||
                            self.peer_addr.equals(BROADCAST_MAC_ADDR)) {
                            vec.push_all(&frame.data);
                            return Some(frame.data.len());
                        }
                    }
                }
                None => return None,
            }
        }
        */
        None
    }

    fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let data = Vec::from(buf);

        /*
        match self.network.write(EthernetII {
            header: EthernetIIHeader {
                src: unsafe { MAC_ADDR },
                dst: self.peer_addr,
                ethertype: n16::new(self.ethertype),
            },
            data: data,
        }.to_bytes().as_slice()) {
            Some(_) => return Some(buf.len()),
            None => return None,
        }
        */
        None
    }

    fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        None
    }

    fn sync(&mut self) -> bool {
        self.network.sync()
    }
}

pub struct Scheme;

impl Scheme {
    fn new() -> Box<Self> {
        box Scheme
    }

    fn open(&mut self, url: &str) -> Option<Box<Resource>> {
        //Split scheme from the rest of the URL
        let (scheme, mut not_scheme) = url.split_at(url.find(':').unwrap_or(url.len()));

        //Remove the starting two slashes
        if not_scheme.starts_with("//") {
            not_scheme = &not_scheme[2..not_scheme.len() - 2];
        }

        //Check host and port vs path
        if not_scheme.starts_with("/") {
            if let Some(mut network) = File::open("network://") {
                if url.path().len() > 0 {
                    let ethertype = url.path().to_num_radix(16) as u16;

                    if url.host().len() > 0 {
                        return Some(box Resource {
                            network: network,
                            data: Vec::new(),
                            peer_addr: MACAddr::from_string(&url.host()),
                            ethertype: ethertype,
                        });
                    } else {
                        loop {
                            let mut bytes: Vec<u8> = Vec::new();
                            match network.read_to_end(&mut bytes) {
                                Some(_) => {
                                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                                        if frame.header.ethertype.get() == ethertype &&
                                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) {
                                            return Some(box Resource {
                                                network: network,
                                                data: frame.data,
                                                peer_addr: frame.header.src,
                                                ethertype: ethertype,
                                            });
                                        }
                                    }
                                }
                                None => break,
                            }
                        }
                    }
                } else {
                    /*
                    debug::d("Ethernet: No ethertype provided\n");
                    */
                }
            }
        }

        None
    }
}
<commit_msg>Forgot to make the userspace ethernet scheme have pub methods in `Resource` and `Scheme`<commit_after>use redox::Box;
use redox::fs::file::File;
use redox::io::{Read, Write, Seek, SeekFrom};
use redox::mem;
use redox::net::*;
use redox::ptr;
use redox::rand;
use redox::slice;
use redox::{str, String, ToString};
use redox::to_num::*;
use redox::Vec;

/// Ethernet resource
pub struct Resource {
    /// The network
    network: Box<Resource>,
    /// The data
    data: Vec<u8>,
    /// The MAC addresss
    peer_addr: MACAddr,
    /// The ethernet type
    ethertype: u16,
}

impl Resource {
    pub fn dup(&self) -> Option<Box<Self>> {
        match self.network.dup() {
            Some(network) => Some(box Resource {
                network: network,
                data: self.data.clone(),
                peer_addr: self.peer_addr,
                ethertype: self.ethertype,
            }),
            None => None
        }
    }

    pub fn path(&self, buf: &mut [u8]) -> Option<usize> {
        let path = format!("ethernet://{}/{}", self.peer_addr.to_string(), String::from_num_radix(self.ethertype as usize, 16));

        let mut i = 0;
        for b in path.bytes() {
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            } else {
                break;
            }
        }

        Some(i)
    }

    pub fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        /*
        if self.data.len() > 0 {
            let mut bytes: Vec<u8> = Vec::new();
            swap(&mut self.data, &mut bytes);
            vec.push_all(&bytes);
            return Some(bytes.len());
        }

        loop {
            let mut bytes: Vec<u8> = Vec::new();
            match self.network.read_to_end(&mut bytes) {
                Some(_) => {
                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                        if frame.header.ethertype.get() == self.ethertype &&
                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) &&
                           (frame.header.src.equals(self.peer_addr) ||
                            self.peer_addr.equals(BROADCAST_MAC_ADDR)) {
                            vec.push_all(&frame.data);
                            return Some(frame.data.len());
                        }
                    }
                }
                None => return None,
            }
        }
        */
        None
    }

    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let data = Vec::from(buf);

        /*
        match self.network.write(EthernetII {
            header: EthernetIIHeader {
                src: unsafe { MAC_ADDR },
                dst: self.peer_addr,
                ethertype: n16::new(self.ethertype),
            },
            data: data,
        }.to_bytes().as_slice()) {
            Some(_) => return Some(buf.len()),
            None => return None,
        }
        */
        None
    }

    pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        None
    }

    pub fn sync(&mut self) -> bool {
        self.network.sync()
    }
}

pub struct Scheme;

impl Scheme {
    pub fn new() -> Box<Self> {
        box Scheme
    }

    pub fn open(&mut self, url: &str) -> Option<Box<Resource>> {
        //Split scheme from the rest of the URL
        let (scheme, mut not_scheme) = url.split_at(url.find(':').unwrap_or(url.len()));

        //Remove the starting two slashes
        if not_scheme.starts_with("//") {
            not_scheme = &not_scheme[2..not_scheme.len() - 2];
        }

        //Check host and port vs path
        if not_scheme.starts_with("/") {
            if let Some(mut network) = File::open("network://") {
                if url.path().len() > 0 {
                    let ethertype = url.path().to_num_radix(16) as u16;

                    if url.host().len() > 0 {
                        return Some(box Resource {
                            network: network,
                            data: Vec::new(),
                            peer_addr: MACAddr::from_string(&url.host()),
                            ethertype: ethertype,
                        });
                    } else {
                        loop {
                            let mut bytes: Vec<u8> = Vec::new();
                            match network.read_to_end(&mut bytes) {
                                Some(_) => {
                                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                                        if frame.header.ethertype.get() == ethertype &&
                                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) {
                                            return Some(box Resource {
                                                network: network,
                                                data: frame.data,
                                                peer_addr: frame.header.src,
                                                ethertype: ethertype,
                                            });
                                        }
                                    }
                                }
                                None => break,
                            }
                        }
                    }
                } else {
                    /*
                    debug::d("Ethernet: No ethertype provided\n");
                    */
                }
            }
        }

        None
    }
}
<|endoftext|>