<commit_before>#![crate_name = "nickel"]
#![crate_type = "rlib"]

//!Nickel is supposed to be a simple and lightweight foundation for web applications written in Rust. Its API is inspired by the popular express framework for JavaScript.
//!
//!Some of the features are:
//!
//!* Easy handlers: A handler is just a function that takes a `Request` and `ResponseWriter`
//!* Variables in routes. Just write `my/route/:someid`
//!* Easy parameter access: `request.params.get(&"someid")`
//!* simple wildcard routes: `/some/*/route`
//!* double wildcard routes: `/a/**/route`
//!* middleware

extern crate time;
extern crate rustc_serialize as serialize;
extern crate hyper;
extern crate regex;
extern crate typemap;
extern crate plugin;
extern crate url;
extern crate mustache;
extern crate groupable;
extern crate modifier;

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

pub use nickel::Nickel;
pub use request::Request;
pub use response::Response;
pub use middleware::{Action, Continue, Halt, Middleware, ErrorHandler, MiddlewareResult};
pub use static_files_handler::StaticFilesHandler;
pub use favicon_handler::FaviconHandler;
pub use default_error_handler::DefaultErrorHandler;
pub use json_body_parser::JsonBody;
pub use query_string::{QueryString, Query};
pub use router::{Router, Route, RouteResult, HttpRouter};
pub use nickel_error::NickelError;
pub use mimes::MediaType;
pub use responder::Responder;

#[macro_use] pub mod macros;

pub mod router;
mod server;
mod nickel;
mod request;
mod response;
mod middleware;
mod responder;
mod favicon_handler;
mod static_files_handler;
mod json_body_parser;
pub mod mimes;
mod query_string;
mod urlencoded;
mod nickel_error;
mod default_error_handler;

pub mod status {
    pub use hyper::status::StatusCode;
}
<commit_msg>chore(*): remove old crate attributes<commit_after>//!Nickel is supposed to be a simple and lightweight foundation for web applications written in Rust. Its API is inspired by the popular express framework for JavaScript.
//!
//!Some of the features are:
//!
//!* Easy handlers: A handler is just a function that takes a `Request` and `ResponseWriter`
//!* Variables in routes. Just write `my/route/:someid`
//!* Easy parameter access: `request.params.get(&"someid")`
//!* simple wildcard routes: `/some/*/route`
//!* double wildcard routes: `/a/**/route`
//!* middleware

extern crate time;
extern crate rustc_serialize as serialize;
extern crate hyper;
extern crate regex;
extern crate typemap;
extern crate plugin;
extern crate url;
extern crate mustache;
extern crate groupable;
extern crate modifier;

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

pub use nickel::Nickel;
pub use request::Request;
pub use response::Response;
pub use middleware::{Action, Continue, Halt, Middleware, ErrorHandler, MiddlewareResult};
pub use static_files_handler::StaticFilesHandler;
pub use favicon_handler::FaviconHandler;
pub use default_error_handler::DefaultErrorHandler;
pub use json_body_parser::JsonBody;
pub use query_string::{QueryString, Query};
pub use router::{Router, Route, RouteResult, HttpRouter};
pub use nickel_error::NickelError;
pub use mimes::MediaType;
pub use responder::Responder;

#[macro_use] pub mod macros;

pub mod router;
mod server;
mod nickel;
mod request;
mod response;
mod middleware;
mod responder;
mod favicon_handler;
mod static_files_handler;
mod json_body_parser;
pub mod mimes;
mod query_string;
mod urlencoded;
mod nickel_error;
mod default_error_handler;

pub mod status {
    pub use hyper::status::StatusCode;
}
<|endoftext|>


<commit_before><commit_msg>Add function for read and write from/to socket<commit_after><|endoftext|>


<commit_before><commit_msg>plan interface with agent<commit_after><|endoftext|>


<commit_before><commit_msg>Remove warning for unnecessary 'core' feature with rustc-beta2.<commit_after><|endoftext|>


<commit_before><commit_msg>Add record_flags field into DbRecord<commit_after><|endoftext|>


<commit_before><commit_msg>(chore) More fallout from Response deprecations.<commit_after><|endoftext|>


<commit_before><commit_msg>add basic logger spike<commit_after><|endoftext|>


<commit_before><commit_msg>Adding 32-Bit decoding<commit_after><|endoftext|>


<commit_before><commit_msg>Fix lib level example to not run on test<commit_after><|endoftext|>


<commit_before><commit_msg>Clean up some le logic<commit_after><|endoftext|>


<commit_before>//! SQS bindings for Rust
//!
//! Check [SQSHelper](http://dualspark.github.io/rusoto/rusoto/sqs/struct.SQSHelper.html) for convenience functions.
//!

#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
use error::*;
use xmlutil::*;
use std::str::FromStr;
use regions::*;

// include the code generated from the SQS botocore templates
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/codegen/sqs.rs"));

/// Easier to use SQS client: wraps SQSClient class.
pub struct SQSHelper<'a> {
	client: SQSClient<'a>
}

impl<'a> SQSHelper<'a> {
	/// Creates a new SQS helper
	pub fn new<P: AWSCredentialsProvider + 'a>(credentials: P, region:&'a Region) -> SQSHelper<'a> {
		SQSHelper { client: SQSClient::new(credentials, region) }
	}

	/// Lists queues
	pub fn list_queues(&mut self) -> Result<ListQueuesResult, AWSError> {
		self.client.list_queues(&ListQueuesRequest::default())
	}

	/// Creates a new queue
	pub fn create_queue(&mut self, queue_name: &str) -> Result<CreateQueueResult, AWSError> {
		let mut req = CreateQueueRequest::default();
		req.queue_name = queue_name.to_string();
		self.client.create_queue(&req)
	}

	/// Gets a queue URL by the queue's name
	pub fn get_queue_url(&mut self, queue_name: &str) -> Result<GetQueueUrlResult, AWSError> {
		let mut req = GetQueueUrlRequest::default();
		req.queue_name = queue_name.to_string();
		self.client.get_queue_url(&req)
	}

	/// Send message to specified queue
	pub fn send_message(&mut self, queue_url: &str, message_body: &str) -> Result<SendMessageResult, AWSError> {
		let mut req = SendMessageRequest::default();
		req.queue_url = queue_url.to_string();
		req.message_body = message_body.to_string();
		self.client.send_message(&req)
	}

	/// Receive a message from specified queue
	pub fn receive_message(&mut self, queue_url: &str) -> Result<ReceiveMessageResult, AWSError> {
		let mut req = ReceiveMessageRequest::default();
		req.queue_url = queue_url.to_string();
		self.client.receive_message(&req)
	}

	/// Delete a message from the specified queue
	pub fn delete_message(&mut self, queue_url: &str, receipt_handle: &str) -> Result<(), AWSError> {
		let mut req = DeleteMessageRequest::default();
		req.queue_url = queue_url.to_string();
		req.receipt_handle = receipt_handle.to_string();
		self.client.delete_message(&req)
	}

	/// Delete the specified queue
	pub fn delete_queue(&mut self, queue_url: &str) -> Result<(), AWSError> {
		let mut req = DeleteQueueRequest::default();
		req.queue_url = queue_url.to_string();
		self.client.delete_queue(&req)
	}

}
<commit_msg>Adds functionality for SQS create queue to accept user specified request fields.<commit_after>//! SQS bindings for Rust
//!
//! Check [SQSHelper](http://dualspark.github.io/rusoto/rusoto/sqs/struct.SQSHelper.html) for convenience functions.
//!

#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
use error::*;
use xmlutil::*;
use std::str::FromStr;
use regions::*;

// include the code generated from the SQS botocore templates
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/codegen/sqs.rs"));

/// Easier to use SQS client: wraps SQSClient class.
pub struct SQSHelper<'a> {
	client: SQSClient<'a>
}

impl<'a> SQSHelper<'a> {
	/// Creates a new SQS helper
	pub fn new<P: AWSCredentialsProvider + 'a>(credentials: P, region:&'a Region) -> SQSHelper<'a> {
		SQSHelper { client: SQSClient::new(credentials, region) }
	}

	/// Lists queues
	pub fn list_queues(&mut self) -> Result<ListQueuesResult, AWSError> {
		self.client.list_queues(&ListQueuesRequest::default())
	}

	/// Creates a new queue with given name
	pub fn create_queue(&mut self, queue_name: &str) -> Result<CreateQueueResult, AWSError> {
		let mut req = CreateQueueRequest::default();
		req.queue_name = queue_name.to_string();
		self.create_queue_with_request(&req)
	}

	/// Create queue with options specified in request
	pub fn create_queue_with_request(&mut self, request: &CreateQueueRequest) -> Result<CreateQueueResult, AWSError> {
		self.client.create_queue(&request)
	}

	/// Gets a queue URL by the queue's name
	pub fn get_queue_url(&mut self, queue_name: &str) -> Result<GetQueueUrlResult, AWSError> {
		let mut req = GetQueueUrlRequest::default();
		req.queue_name = queue_name.to_string();
		self.client.get_queue_url(&req)
	}

	/// Send message to specified queue
	pub fn send_message(&mut self, queue_url: &str, message_body: &str) -> Result<SendMessageResult, AWSError> {
		let mut req = SendMessageRequest::default();
		req.queue_url = queue_url.to_string();
		req.message_body = message_body.to_string();
		self.send_message_with_request(&req)
	}

	/// Send message with specified request options
	pub fn send_message_with_request(&mut self, request: &SendMessageRequest) -> Result<SendMessageResult, AWSError> {
		self.client.send_message(&request)
	}

	/// Receive a message from specified queue
	pub fn receive_message(&mut self, queue_url: &str) -> Result<ReceiveMessageResult, AWSError> {
		let mut req = ReceiveMessageRequest::default();
		req.queue_url = queue_url.to_string();
		self.receive_message_with_request(&req)
	}

	/// Receive message with specified request options
	pub fn receive_message_with_request(&mut self, request: &ReceiveMessageRequest)-> Result<ReceiveMessageResult, AWSError> {
		self.client.receive_message(&request)
	}

	/// Delete a message from the specified queue
	pub fn delete_message(&mut self, queue_url: &str, receipt_handle: &str) -> Result<(), AWSError> {
		let mut req = DeleteMessageRequest::default();
		req.queue_url = queue_url.to_string();
		req.receipt_handle = receipt_handle.to_string();
		self.delete_message_with_request(&req)
	}

	/// Delete message with specified request options
	pub fn delete_message_with_request(&mut self, request: &DeleteMessageRequest) -> Result<(), AWSError> {
		self.client.delete_message(&request)
	}

	/// Delete the specified queue
	pub fn delete_queue(&mut self, queue_url: &str) -> Result<(), AWSError> {
		let mut req = DeleteQueueRequest::default();
		req.queue_url = queue_url.to_string();
		self.delete_queue_with_request(&req)
	}

	/// Delete the queue with specified request options
	pub fn delete_queue_with_request(&mut self, request: &DeleteQueueRequest) -> Result<(), AWSError> {
		self.client.delete_queue(&request)
	}

}
<|endoftext|>


<commit_before><commit_msg>Add a secure_with_ssl method to FtpStream so that users can supply their own SSL configuration<commit_after><|endoftext|>


<commit_before><commit_msg>Updated vfs tests.<commit_after><|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::collections::BTreeMap;
use std::error::Error;

use ruru::{Class, Object, AnyObject, Boolean, RString, VM, Hash, NilClass, VerifiedObject};

use libimagstore::store::EntryHeader;
use libimagstore::store::EntryContent;
use libimagstore::store::Entry;
use libimagstore::storeid::StoreId;

use ruby_utils::IntoToml;
use toml_utils::IntoRuby;
use util::Wrap;
use util::Unwrap;
use cache::StoreHandle;

pub struct FileLockEntryHandle(StoreHandle, StoreId);

impl FileLockEntryHandle {
    pub fn new(sh: StoreHandle, id: StoreId) -> FileLockEntryHandle {
        FileLockEntryHandle(sh, id)
    }

    pub fn store_handle(&self) -> &StoreHandle {
        &self.0
    }

    pub fn fle_handle(&self) -> &StoreId {
        &self.1
    }
}

wrappable_struct!(FileLockEntryHandle, FileLockEntryWrapper, FLE_WRAPPER);
class!(RFileLockEntryHandle);
impl_wrap!(FileLockEntryHandle => FLE_WRAPPER);
impl_unwrap!(RFileLockEntryHandle => FileLockEntryHandle => FLE_WRAPPER);
impl_verified_object!(RFileLockEntryHandle);

/// Helper macro for operating on RUBY_STORE_CACHE object
///
/// This helps us calling operations on FileLockEntry objects.
///
/// What I do here: Fetch the Store object from the cache, fetch the appropriate FileLockEntry and
/// call the operation on it.
///
/// This could be improved with another cache, so not the store is cached but the FileLockEntry
/// only, but then we run into lifetime problems with the Store and its FileLockEntry objects.
/// Feel free to fix this, but for now, this is a workable solution.
///
#[macro_export]
macro_rules! call_on_fle_from_store {
    ($itself:ident ($wrapper:ident) -> $name:ident -> $operation:block) => {{
        let handle = $itself.get_data(&*$wrapper);
        let store_handle = handle.store_handle();
        call_on_store_by_handle! {
            store_handle named store inside {
                match store.get(handle.fle_handle().clone()) {
                    Ok(Some(mut $name)) => {
                        $operation
                    },
                    Ok(None) => {
                        VM::raise(Class::from_existing("RuntimeError"), "Obj does not exist");
                        NilClass::new().to_any_object()
                    },
                    Err(e) => {
                        VM::raise(Class::from_existing("RuntimeError"), e.description());
                        NilClass::new().to_any_object()
                    },
                }
            }
        }
    }};
    ($itself:ident ($wrapper:ident) -> $name:ident -> $operation: block on fail return $ex:expr) => {{
        let handle = $itself.get_data(&*$wrapper);
        let store_handle = handle.store_handle();
        call_on_store_by_handle! {
            store_handle named store inside {
                match store.get(handle.fle_handle().clone()) {
                    Ok(Some(mut $name)) => {
                        $operation
                    },
                    Ok(None) => {
                        VM::raise(Class::from_existing("RuntimeError"), "Obj does not exist");
                        $ex
                    },
                    Err(e) => {
                        VM::raise(Class::from_existing("RuntimeError"), e.description());
                        $ex
                    },
                }
            } on fail return $ex
        }
    }};
}

methods!(
    RFileLockEntryHandle,
    itself,

    fn r_get_location() -> AnyObject {
        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> { fle.get_location().clone().wrap() })
    }

    fn r_get_header() -> AnyObject {
        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> { fle.get_header().clone().wrap() })
    }

    fn r_set_header(hdr: Hash) -> NilClass {
        use ruby_utils::IntoToml;
        use toml::Value;

        let entryheader = match typecheck!(hdr or return NilClass::new()).into_toml() {
            Value::Table(t) => EntryHeader::from(t),
            _ => {
                let ec = Class::from_existing("RuntimeError");
                VM::raise(ec, "Something weird happened. Hash seems to be not a Hash");
                return NilClass::new();
            },
        };

        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> {
            *fle.get_header_mut() = entryheader;
            NilClass::new().to_any_object()
        });

        NilClass::new()
    }

    fn r_get_content() -> AnyObject {
        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> {
            fle.get_content().clone().wrap()
        } on fail return NilClass::new().to_any_object())
    }

    fn r_set_content(ctt: RString) -> NilClass {
        use ruby_utils::IntoToml;
        use toml::Value;

        let content = match typecheck!(ctt).into_toml() {
            Value::String(s) => s,
            _ => {
                let ec = Class::from_existing("RuntimeError");
                VM::raise(ec, "Something weird happened. String seems to be not a String");
                return NilClass::new();
            },
        };

        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> {
            *fle.get_content_mut() = content;
            NilClass::new().to_any_object()
        });

        NilClass::new()
    }

);

wrappable_struct!(EntryHeader, EntryHeaderWrapper, ENTRY_HEADER_WRAPPER);
class!(REntryHeader);
impl_wrap!(EntryHeader => ENTRY_HEADER_WRAPPER);
impl_unwrap!(REntryHeader => EntryHeader => ENTRY_HEADER_WRAPPER);
impl_verified_object!(REntryHeader);

methods!(
    REntryHeader,
    itself,

    fn r_entry_header_new() -> AnyObject {
        EntryHeader::new().wrap()
    }

    fn r_entry_header_insert(spec: RString, obj: AnyObject) -> Boolean {
        let spec = typecheck!(spec or return Boolean::new(false)).to_string();
        let obj = obj.unwrap(); // possibly not safe... TODO

        match itself.get_data(&*ENTRY_HEADER_WRAPPER).insert(&spec, obj.into_toml()) {
            Ok(b) => Boolean::new(b),
            Err(e) => {
                VM::raise(Class::from_existing("RuntimeError"), e.description());
                Boolean::new(false)
            }
        }
    }

    fn r_entry_header_set(spec: RString, obj: AnyObject) -> AnyObject {
        use ruru::NilClass;

        let spec = typecheck!(spec or return any Boolean::new(false)).to_string();
        let obj = obj.unwrap(); // possibly not safe... TODO

        match itself.get_data(&*ENTRY_HEADER_WRAPPER).set(&spec, obj.into_toml()) {
            Ok(Some(v)) => v.into_ruby(),
            Ok(None)    => NilClass::new().to_any_object(),
            Err(e) => {
                VM::raise(Class::from_existing("RuntimeError"), e.description());
                return Boolean::new(false).to_any_object();
            }
        }
    }

    fn r_entry_header_get(spec: RString) -> AnyObject {
        use ruru::NilClass;

        let spec = typecheck!(spec or return any Boolean::new(false)).to_string();

        match itself.get_data(&*ENTRY_HEADER_WRAPPER).read(&spec) {
            Ok(Some(v)) => v.into_ruby(),
            Ok(None)    => NilClass::new().to_any_object(),
            Err(e) => {
                VM::raise(Class::from_existing("RuntimeError"), e.description());
                return Boolean::new(false).to_any_object();
            }
        }
    }

);

wrappable_struct!(EntryContent, EntryContentWrapper, ENTRY_CONTENT_WRAPPER);
class!(REntryContent);
impl_wrap!(EntryContent => ENTRY_CONTENT_WRAPPER);
impl_unwrap!(REntryContent => EntryContent => ENTRY_CONTENT_WRAPPER);

wrappable_struct!(Entry, EntryWrapper, ENTRY_WRAPPER);
class!(REntry);
impl_unwrap!(REntry => Entry => ENTRY_WRAPPER);

pub fn setup_filelockentry() -> Class {
    let mut class = Class::new("RFileLockEntryHandle", None);
    class.define(|itself| {
        itself.def("location", r_get_location);
        itself.def("header"  , r_get_header);
        itself.def("header=" , r_set_header);
        itself.def("content" , r_get_content);
        itself.def("content=", r_set_content);
    });
    class
}

pub fn setup_entryheader() -> Class {
    let mut class = Class::new("REntryHeader", None);
    class.define(|itself| {
        itself.def("insert", r_entry_header_insert);
        itself.def("set"   , r_entry_header_set);
        itself.def("[]="   , r_entry_header_set);
        itself.def("read"  , r_entry_header_get);
        itself.def("[]"    , r_entry_header_get);
    });
    class
}

pub fn setup_entrycontent() -> Class {
    let string = Class::from_existing("String");
    Class::new("REntryContent", Some(&string))
}
<commit_msg>libimagruby: Eliminate EntryHeader type<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::collections::BTreeMap;
use std::error::Error;

use ruru::{Class, Object, AnyObject, Boolean, RString, VM, Hash, NilClass, VerifiedObject};
use toml::Value;

use libimagstore::store::EntryContent;
use libimagstore::store::Entry;
use libimagstore::storeid::StoreId;
use libimagstore::toml_ext::TomlValueExt;

use ruby_utils::IntoToml;
use toml_utils::IntoRuby;
use util::Wrap;
use util::Unwrap;
use cache::StoreHandle;

pub struct FileLockEntryHandle(StoreHandle, StoreId);

impl FileLockEntryHandle {
    pub fn new(sh: StoreHandle, id: StoreId) -> FileLockEntryHandle {
        FileLockEntryHandle(sh, id)
    }

    pub fn store_handle(&self) -> &StoreHandle {
        &self.0
    }

    pub fn fle_handle(&self) -> &StoreId {
        &self.1
    }
}

wrappable_struct!(FileLockEntryHandle, FileLockEntryWrapper, FLE_WRAPPER);
class!(RFileLockEntryHandle);
impl_wrap!(FileLockEntryHandle => FLE_WRAPPER);
impl_unwrap!(RFileLockEntryHandle => FileLockEntryHandle => FLE_WRAPPER);
impl_verified_object!(RFileLockEntryHandle);

/// Helper macro for operating on RUBY_STORE_CACHE object
///
/// This helps us calling operations on FileLockEntry objects.
///
/// What I do here: Fetch the Store object from the cache, fetch the appropriate FileLockEntry and
/// call the operation on it.
///
/// This could be improved with another cache, so not the store is cached but the FileLockEntry
/// only, but then we run into lifetime problems with the Store and its FileLockEntry objects.
/// Feel free to fix this, but for now, this is a workable solution.
///
#[macro_export]
macro_rules! call_on_fle_from_store {
    ($itself:ident ($wrapper:ident) -> $name:ident -> $operation:block) => {{
        let handle = $itself.get_data(&*$wrapper);
        let store_handle = handle.store_handle();
        call_on_store_by_handle! {
            store_handle named store inside {
                match store.get(handle.fle_handle().clone()) {
                    Ok(Some(mut $name)) => {
                        $operation
                    },
                    Ok(None) => {
                        VM::raise(Class::from_existing("RuntimeError"), "Obj does not exist");
                        NilClass::new().to_any_object()
                    },
                    Err(e) => {
                        VM::raise(Class::from_existing("RuntimeError"), e.description());
                        NilClass::new().to_any_object()
                    },
                }
            }
        }
    }};
    ($itself:ident ($wrapper:ident) -> $name:ident -> $operation: block on fail return $ex:expr) => {{
        let handle = $itself.get_data(&*$wrapper);
        let store_handle = handle.store_handle();
        call_on_store_by_handle! {
            store_handle named store inside {
                match store.get(handle.fle_handle().clone()) {
                    Ok(Some(mut $name)) => {
                        $operation
                    },
                    Ok(None) => {
                        VM::raise(Class::from_existing("RuntimeError"), "Obj does not exist");
                        $ex
                    },
                    Err(e) => {
                        VM::raise(Class::from_existing("RuntimeError"), e.description());
                        $ex
                    },
                }
            } on fail return $ex
        }
    }};
}

methods!(
    RFileLockEntryHandle,
    itself,

    fn r_get_location() -> AnyObject {
        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> { fle.get_location().clone().wrap() })
    }

    fn r_get_header() -> AnyObject {
        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> { fle.get_header().clone().wrap() })
    }

    fn r_set_header(hdr: Hash) -> NilClass {
        use ruby_utils::IntoToml;
        use toml::Value;

        let entryheader = match typecheck!(hdr or return NilClass::new()).into_toml() {
            Value::Table(t) => Value::Table(t),
            _ => {
                let ec = Class::from_existing("RuntimeError");
                VM::raise(ec, "Something weird happened. Hash seems to be not a Hash");
                return NilClass::new();
            },
        };

        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> {
            *fle.get_header_mut() = entryheader;
            NilClass::new().to_any_object()
        });

        NilClass::new()
    }

    fn r_get_content() -> AnyObject {
        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> {
            fle.get_content().clone().wrap()
        } on fail return NilClass::new().to_any_object())
    }

    fn r_set_content(ctt: RString) -> NilClass {
        use ruby_utils::IntoToml;
        use toml::Value;

        let content = match typecheck!(ctt).into_toml() {
            Value::String(s) => s,
            _ => {
                let ec = Class::from_existing("RuntimeError");
                VM::raise(ec, "Something weird happened. String seems to be not a String");
                return NilClass::new();
            },
        };

        call_on_fle_from_store!(itself (FLE_WRAPPER) -> fle -> {
            *fle.get_content_mut() = content;
            NilClass::new().to_any_object()
        });

        NilClass::new()
    }

);

wrappable_struct!(Value, EntryHeaderWrapper, ENTRY_HEADER_WRAPPER);
class!(REntryHeader);
impl_wrap!(Value => ENTRY_HEADER_WRAPPER);
impl_unwrap!(REntryHeader => Value => ENTRY_HEADER_WRAPPER);
impl_verified_object!(REntryHeader);

methods!(
    REntryHeader,
    itself,

    fn r_entry_header_new() -> AnyObject {
        Entry::default_header().wrap()
    }

    fn r_entry_header_insert(spec: RString, obj: AnyObject) -> Boolean {
        let spec = typecheck!(spec or return Boolean::new(false)).to_string();
        let obj = obj.unwrap(); // possibly not safe... TODO

        match itself.get_data(&*ENTRY_HEADER_WRAPPER).insert(&spec, obj.into_toml()) {
            Ok(b) => Boolean::new(b),
            Err(e) => {
                VM::raise(Class::from_existing("RuntimeError"), e.description());
                Boolean::new(false)
            }
        }
    }

    fn r_entry_header_set(spec: RString, obj: AnyObject) -> AnyObject {
        use ruru::NilClass;

        let spec = typecheck!(spec or return any Boolean::new(false)).to_string();
        let obj = obj.unwrap(); // possibly not safe... TODO

        match itself.get_data(&*ENTRY_HEADER_WRAPPER).set(&spec, obj.into_toml()) {
            Ok(Some(v)) => v.into_ruby(),
            Ok(None)    => NilClass::new().to_any_object(),
            Err(e) => {
                VM::raise(Class::from_existing("RuntimeError"), e.description());
                return Boolean::new(false).to_any_object();
            }
        }
    }

    fn r_entry_header_get(spec: RString) -> AnyObject {
        use ruru::NilClass;

        let spec = typecheck!(spec or return any Boolean::new(false)).to_string();

        match itself.get_data(&*ENTRY_HEADER_WRAPPER).read(&spec) {
            Ok(Some(v)) => v.into_ruby(),
            Ok(None)    => NilClass::new().to_any_object(),
            Err(e) => {
                VM::raise(Class::from_existing("RuntimeError"), e.description());
                return Boolean::new(false).to_any_object();
            }
        }
    }

);

wrappable_struct!(EntryContent, EntryContentWrapper, ENTRY_CONTENT_WRAPPER);
class!(REntryContent);
impl_wrap!(EntryContent => ENTRY_CONTENT_WRAPPER);
impl_unwrap!(REntryContent => EntryContent => ENTRY_CONTENT_WRAPPER);

wrappable_struct!(Entry, EntryWrapper, ENTRY_WRAPPER);
class!(REntry);
impl_unwrap!(REntry => Entry => ENTRY_WRAPPER);

pub fn setup_filelockentry() -> Class {
    let mut class = Class::new("RFileLockEntryHandle", None);
    class.define(|itself| {
        itself.def("location", r_get_location);
        itself.def("header"  , r_get_header);
        itself.def("header=" , r_set_header);
        itself.def("content" , r_get_content);
        itself.def("content=", r_set_content);
    });
    class
}

pub fn setup_entryheader() -> Class {
    let mut class = Class::new("REntryHeader", None);
    class.define(|itself| {
        itself.def("insert", r_entry_header_insert);
        itself.def("set"   , r_entry_header_set);
        itself.def("[]="   , r_entry_header_set);
        itself.def("read"  , r_entry_header_get);
        itself.def("[]"    , r_entry_header_get);
    });
    class
}

pub fn setup_entrycontent() -> Class {
    let string = Class::from_existing("String");
    Class::new("REntryContent", Some(&string))
}
<|endoftext|>


<commit_before><commit_msg>Implementation of RC4's key scheduling algorithm.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove temp tests.<commit_after><|endoftext|>


<commit_before><commit_msg>still black<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Added import of middleware module.<commit_after><|endoftext|>


<commit_before><commit_msg> change to make all tests run<commit_after><|endoftext|>


<commit_before><commit_msg>Add clear_history function<commit_after><|endoftext|>


<commit_before><commit_msg>Rearrange comments<commit_after><|endoftext|>


<commit_before><commit_msg>Invalid source code formating (rustfmt) Fixed<commit_after><|endoftext|>


<commit_before><commit_msg>lib src file<commit_after><|endoftext|>


<commit_before><commit_msg>Client struct<commit_after><|endoftext|>


<commit_before><commit_msg>Hide `Archive::from_bytes` in documentation<commit_after><|endoftext|>


<commit_before>extern crate orbclient;
extern crate sinulation;

pub mod start;
pub mod vid;

#[allow(dead_code)]
pub mod shaders;
//pub mod out;
<commit_msg>Change that doesn't matter<commit_after>extern crate orbclient;
extern crate sinulation;

pub mod start;
pub mod vid;

#[allow(unused_variables, dead_code)]
pub mod shaders;
//pub mod out;
<|endoftext|>


<commit_before><commit_msg>Fix String entry and covered all types in test.<commit_after><|endoftext|>


<commit_before><commit_msg>Trait implementations.<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust feature flags for the latest rustc nightly.<commit_after><|endoftext|>


<commit_before><commit_msg>Add easy_plugin plugin stub<commit_after><|endoftext|>


<commit_before><commit_msg>Break out decompose module.<commit_after><|endoftext|>


<commit_before><commit_msg>first draft done<commit_after>extern crate timely;
extern crate differential_dataflow;
extern crate rand;

use differential_dataflow::input::InputSession;
use differential_dataflow::operators::{Join,CountTotal,Count};

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

fn main() {

    timely::execute_from_args(std::env::args(), move |worker| {

        let mut interactions_input = InputSession::new();

        let probe = worker.dataflow(|scope| {

            let interactions = interactions_input.to_collection(scope);

            // Find all users with more than 5 and less than 500 interactions
            let users_with_enough_interactions = interactions
                .map(|(user, _item)| user)
                .count_total()
                .filter(move |(_user, count): &(u32, isize)| *count > 5 && *count < 500)
                .map(|(user, _count)| user);

            // Remove users with too few or too many interactions
            let remaining_interactions = interactions
                .semijoin(&users_with_enough_interactions);

            let num_interactions_per_item = remaining_interactions
                .map(|(_user, item)| item)
                .count_total();

            // Compute the number of cooccurrences of each item pair
            let cooccurrences = remaining_interactions
                .join_map(&remaining_interactions, |_user, &item_a, &item_b| (item_a, item_b))
                .filter(|&(item_a, item_b)| item_a > item_b)
                .count();

            // Compute the jaccard similarity between item pairs (= number of users that interacted
            // with both items / number of users that interacted with at least one of the items)
            let jaccard_similarities = cooccurrences
                .map(|((item_a, item_b), num_cooc)| (item_a, (item_b, num_cooc)))
                .join_map(&num_interactions_per_item, |&item_a, &(item_b, num_cooc), &occ_a| {
                    (item_b, (item_a, num_cooc, occ_a))
                })
                .join_map(
                    &num_interactions_per_item,
                    |&item_b, &(item_a, num_cooc, occ_a), &occ_b| {
                        ((item_a, item_b), (num_cooc, occ_a, occ_b))
                    },
                )
                // We have to do this calculation in a map due to the lack of a total order for f64
                .map(|((item_a, item_b), (num_cooc, occ_a, occ_b))| {
                    let jaccard = num_cooc as f64 / (occ_a + occ_b - num_cooc) as f64;
                    ((item_a, item_b), jaccard)
                });

            // We threshold the similarity matrix
            let thresholded_similarities = jaccard_similarities
                .filter(|(_item_pair, jaccard)| *jaccard > 0.05);

            thresholded_similarities.probe()
        });

        let num_interactions: usize = std::env::args().nth(1)
            .or_else(|| Some(String::from("10000"))).unwrap().parse().unwrap();

        if worker.index() == 0 {
            println!("Generating {} synthetic interactions...", num_interactions);
        }

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

        let synthetic_interactions = generate_interactions(num_interactions, &mut rng);

        let num_users = synthetic_interactions.iter().map(|(user, _item)| user).max().unwrap() + 1;
        let users_to_remove = rand::seq::sample_iter(&mut rng, 0..num_users, 20).unwrap();

        let interactions_to_remove: Vec<(u32,u32)> = synthetic_interactions.iter()
            .filter(|(user, _item)| users_to_remove.contains(&user))
            .map(|(user, item)| (*user, *item))
            .collect();

        let timer = worker.timer();

        for (user, item) in synthetic_interactions.iter() {
            if *user as usize % worker.peers() == worker.index() {
                interactions_input.insert((*user, *item));
            }
        }

        interactions_input.advance_to(1);
        interactions_input.flush();

        worker.step_while(|| probe.less_than(interactions_input.time()));

        let initial_model_time = timer.elapsed();
        println!("Model trained in {:?} on worker {:?}", initial_model_time, worker.index());

        if worker.index() == 0 {
            println!("Removing {} interactions...", interactions_to_remove.len());
        }

        for (user, item) in interactions_to_remove.iter() {
            if *user as usize % worker.peers() == worker.index() {
                interactions_input.remove((*user, *item));
            }
        }

        interactions_input.advance_to(2);
        interactions_input.flush();

        worker.step_while(|| probe.less_than(interactions_input.time()));

        let removal_time = timer.elapsed();
        println!(
            "Model updated after {:?} on worker {:?}",
            (removal_time - initial_model_time),
            worker.index(),
        );

    }).unwrap();
}

struct CRP { alpha: f64, discount: f64, weight: f64, weights: Vec<f64> }

impl CRP {
    fn new(alpha: f64, discount: f64) -> Self {
        CRP { alpha, discount, weight: 0.0, weights: Vec::new() }
    }

    fn sample<R>(&mut self, rng: &mut R) -> u32 where R: Rng {
        let mut u = rng.gen::<f64>() * (self.alpha + self.weight);
        for j in 0 .. self.weights.len() {
            if u < self.weights[j] - self.discount {
                self.weights[j] += 1.0;
                self.weight += 1.0;
                return j as u32;
            } else {
                u = u - self.weights[j] - self.discount;
            }
        }

        self.weights.push(1.0);
        self.weight = self.weight + 1.0;

        (self.weights.len() - 1) as u32
    }
}

// Generate synthetic interactions with a skewed distribution
fn generate_interactions<R>(how_many: usize, rng: &mut R) -> Vec<(u32,u32)> where R: Rng {
    let mut interactions = Vec::with_capacity(how_many);

    let mut user_sampler = CRP::new(6000.0, 0.35);
    let mut item_sampler = CRP::new(6000.0, 0.35);

    for _ in 0 .. how_many {
        let user = user_sampler.sample(rng);
        let item = item_sampler.sample(rng);
        interactions.push((user, item));
    }

    interactions
}<|endoftext|>


<commit_before><commit_msg>Run cargo fmt<commit_after><|endoftext|>


<commit_before><commit_msg>Add test of common PartialEq cases<commit_after>use serde_bytes::{Bytes, ByteBuf};

fn _bytes_eq_slice(bytes: &Bytes, slice: &[u8]) -> bool {
    bytes == slice
}

fn _bytebuf_eq_vec(bytebuf: ByteBuf, vec: Vec<u8>) -> bool {
    bytebuf == vec
}

fn _bytes_eq_bytestring(bytes: &Bytes) -> bool {
    bytes == b"..."
}
<|endoftext|>


<commit_before><commit_msg>started building my vectors using macros<commit_after><|endoftext|>


<commit_before><commit_msg>Added P 6<commit_after>//The sum of the squares of the first ten natural numbers is,
//
//1^2 + 2^2 + ... + 10^2 = 385
//
//The square of the sum of the first ten natural numbers is,
//
//(1 + 2 + ... + 10)^2 = 55^2 = 3025
//
//Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
//
//Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

fn solve(setbound: u64) -> u64 {
    let mut sumofsquares = 0;
    let mut squareofsum = 0;
    if setbound == 0 {
        panic!();
    }
    for i in 1..(setbound + 1) {
        sumofsquares += i * i;
        squareofsum += i;
    }
    (squareofsum * squareofsum) - sumofsquares
}

fn main() {
    println!("{}", solve(100).to_string());
}

#[cfg(test)]
mod tests {
    #[test]
    #[should_panic]
    fn sum_square_diff_badbound() {
        super::solve(0);
    }
    #[test]
    fn sum_square_diff_10() {
        assert_eq!(2640, super::solve(10));
    }
    #[test]
    fn sum_square_diff_100() {
        assert_eq!(25164150, super::solve(100));
    }
}
<|endoftext|>


<commit_before><commit_msg>Rewrite UrlLinker<commit_after><|endoftext|>


<commit_before><commit_msg>Remove second parameter to Eq<commit_after><|endoftext|>


<commit_before><commit_msg>Rustfmt.<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::activation::Activatable;
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast};
use dom::bindings::codegen::InheritTypes::{MouseEventCast, NodeCast};
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::document::{Document, DocumentHelpers};
use dom::domtokenlist::DOMTokenList;
use dom::element::{Element, AttributeHandlers, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;

use num::ToPrimitive;
use std::default::Default;
use string_cache::Atom;
use util::str::DOMString;

#[dom_struct]
pub struct HTMLAnchorElement {
    htmlelement: HTMLElement,
    rel_list: MutNullableHeap<JS<DOMTokenList>>,
}

impl HTMLAnchorElementDerived for EventTarget {
    fn is_htmlanchorelement(&self) -> bool {
        *self.type_id() ==
            EventTargetTypeId::Node(
                NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)))
    }
}

impl HTMLAnchorElement {
    fn new_inherited(localName: DOMString,
                     prefix: Option<DOMString>,
                     document: &Document) -> HTMLAnchorElement {
        HTMLAnchorElement {
            htmlelement:
                HTMLElement::new_inherited(HTMLElementTypeId::HTMLAnchorElement, localName, prefix, document),
            rel_list: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: DOMString,
               prefix: Option<DOMString>,
               document: &Document) -> Root<HTMLAnchorElement> {
        let element = HTMLAnchorElement::new_inherited(localName, prefix, document);
        Node::reflect_node(box element, document, HTMLAnchorElementBinding::Wrap)
    }
}

impl<'a> VirtualMethods for &'a HTMLAnchorElement {
    fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
        let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
        Some(htmlelement as &VirtualMethods)
    }

    fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
        match name {
            &atom!("rel") => AttrValue::from_serialized_tokenlist(value),
            _ => self.super_type().unwrap().parse_plain_attribute(name, value),
        }
    }
}

impl<'a> HTMLAnchorElementMethods for &'a HTMLAnchorElement {
    fn Text(self) -> DOMString {
        let node = NodeCast::from_ref(self);
        node.GetTextContent().unwrap()
    }

    fn SetText(self, value: DOMString) {
        let node = NodeCast::from_ref(self);
        node.SetTextContent(Some(value))
    }

    fn RelList(self) -> Root<DOMTokenList> {
        self.rel_list.or_init(|| {
            DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel"))
        })
    }
}

impl<'a> Activatable for &'a HTMLAnchorElement {
    fn as_element<'b>(&'b self) -> &'b Element {
        ElementCast::from_ref(*self)
    }

    fn is_instance_activatable(&self) -> bool {
        true
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn pre_click_activation(&self) {
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
    fn canceled_activation(&self) {
    }

    //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour
    fn activation_behavior(&self, event: &Event, target: &EventTarget) {
        //Step 1. If the node document is not fully active, abort.
        let doc = document_from_node(*self);
        if !doc.r().is_fully_active() {
            return;
        }
        //TODO: Step 2. Check if browsing context is specified and act accordingly.
        //Step 3. Handle <img ismap/>.
        let element = ElementCast::from_ref(*self);
        let mouse_event = MouseEventCast::to_ref(event).unwrap();
        let mut ismap_suffix = None;
        if let Some(element) = ElementCast::to_ref(target) {
            if target.is_htmlimageelement() && element.has_attribute(&atom!("ismap")) {

                let target_node = NodeCast::from_ref(element);
                let rect = window_from_node(target_node).r().content_box_query(
                    target_node.to_trusted_node_address());
                ismap_suffix = Some(
                    format!("?{},{}", mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
                                      mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px())
                )
            }
        }

        //TODO: Step 4. Download the link is `download` attribute is set.

        let attr = element.get_attribute(&ns!(""), &atom!("href"));
        match attr {
            Some(ref href) => {
                let value = href.r().Value() + ismap_suffix.as_ref().map(|s| &**s).unwrap_or("");
                debug!("clicked on link to {}", value);
                doc.r().load_anchor_href(value);
            }
            None => ()
        }
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) {
    }
}
<commit_msg>Simplify the string handling in HTMLAnchorElement::activation_behavior.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::activation::Activatable;
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast};
use dom::bindings::codegen::InheritTypes::{MouseEventCast, NodeCast};
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::document::{Document, DocumentHelpers};
use dom::domtokenlist::DOMTokenList;
use dom::element::{Element, AttributeHandlers, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;

use num::ToPrimitive;
use std::default::Default;
use string_cache::Atom;
use util::str::DOMString;

#[dom_struct]
pub struct HTMLAnchorElement {
    htmlelement: HTMLElement,
    rel_list: MutNullableHeap<JS<DOMTokenList>>,
}

impl HTMLAnchorElementDerived for EventTarget {
    fn is_htmlanchorelement(&self) -> bool {
        *self.type_id() ==
            EventTargetTypeId::Node(
                NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)))
    }
}

impl HTMLAnchorElement {
    fn new_inherited(localName: DOMString,
                     prefix: Option<DOMString>,
                     document: &Document) -> HTMLAnchorElement {
        HTMLAnchorElement {
            htmlelement:
                HTMLElement::new_inherited(HTMLElementTypeId::HTMLAnchorElement, localName, prefix, document),
            rel_list: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: DOMString,
               prefix: Option<DOMString>,
               document: &Document) -> Root<HTMLAnchorElement> {
        let element = HTMLAnchorElement::new_inherited(localName, prefix, document);
        Node::reflect_node(box element, document, HTMLAnchorElementBinding::Wrap)
    }
}

impl<'a> VirtualMethods for &'a HTMLAnchorElement {
    fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
        let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
        Some(htmlelement as &VirtualMethods)
    }

    fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
        match name {
            &atom!("rel") => AttrValue::from_serialized_tokenlist(value),
            _ => self.super_type().unwrap().parse_plain_attribute(name, value),
        }
    }
}

impl<'a> HTMLAnchorElementMethods for &'a HTMLAnchorElement {
    fn Text(self) -> DOMString {
        let node = NodeCast::from_ref(self);
        node.GetTextContent().unwrap()
    }

    fn SetText(self, value: DOMString) {
        let node = NodeCast::from_ref(self);
        node.SetTextContent(Some(value))
    }

    fn RelList(self) -> Root<DOMTokenList> {
        self.rel_list.or_init(|| {
            DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel"))
        })
    }
}

impl<'a> Activatable for &'a HTMLAnchorElement {
    fn as_element<'b>(&'b self) -> &'b Element {
        ElementCast::from_ref(*self)
    }

    fn is_instance_activatable(&self) -> bool {
        true
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn pre_click_activation(&self) {
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
    fn canceled_activation(&self) {
    }

    //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour
    fn activation_behavior(&self, event: &Event, target: &EventTarget) {
        //Step 1. If the node document is not fully active, abort.
        let doc = document_from_node(*self);
        if !doc.r().is_fully_active() {
            return;
        }
        //TODO: Step 2. Check if browsing context is specified and act accordingly.
        //Step 3. Handle <img ismap/>.
        let element = ElementCast::from_ref(*self);
        let mouse_event = MouseEventCast::to_ref(event).unwrap();
        let mut ismap_suffix = None;
        if let Some(element) = ElementCast::to_ref(target) {
            if target.is_htmlimageelement() && element.has_attribute(&atom!("ismap")) {

                let target_node = NodeCast::from_ref(element);
                let rect = window_from_node(target_node).r().content_box_query(
                    target_node.to_trusted_node_address());
                ismap_suffix = Some(
                    format!("?{},{}", mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
                                      mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px())
                )
            }
        }

        //TODO: Step 4. Download the link is `download` attribute is set.

        if let Some(ref href) = element.get_attribute(&ns!(""), &atom!("href")) {
            let mut value = href.r().Value();
            if let Some(suffix) = ismap_suffix {
                value.push_str(&suffix);
            }
            debug!("clicked on link to {}", value);
            doc.r().load_anchor_href(value);
        }
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) {
    }
}
<|endoftext|>


<commit_before><commit_msg>Format branch_exchange() to pass rustfmt<commit_after><|endoftext|>


<commit_before><commit_msg>adds option_utils<commit_after>use error::{VcxErrorKind, VcxError, VcxResult};

pub fn get_or_default(config: &Option<String>, default: &str) -> String {
    config.to_owned().unwrap_or(default.to_string())
}

pub fn get_or_err(config: &Option<String>, err: Option<VcxErrorKind>) -> VcxResult<String> {
    let e = VcxError::from(err.unwrap_or(VcxErrorKind::InvalidOption));
    config.to_owned().ok_or(e)
}
<|endoftext|>


<commit_before><commit_msg>[Auto] lib/entry/gps: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>it compilesgit add src/lib.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Ignore `dead_code` warnings for now<commit_after><|endoftext|>


<commit_before><commit_msg>Implement RC4's pseudo-random generator.<commit_after><|endoftext|>


<commit_before><commit_msg>Implement find_bucket<commit_after><|endoftext|>


<commit_before><commit_msg> change to make all tests run<commit_after><|endoftext|>


<commit_before><commit_msg>Implement overflow_pages_needed method<commit_after><|endoftext|>


<commit_before><commit_msg>add custom example<commit_after>/**
    Simple example on how to create a custom window with NWG. This demo creates a window with two scollbars

    In NWG, a custom control is defined by two traits: the template (ControlT) and the control (Control)
    The template is evaluated by the UI and returns an instance of the control. The UI then manages the
    control until it is destroyed (aka unpacked).

    Right now, creating custom control is unsafe. Safe and simpler way to create custom may be added in future version of NWG.

    For simpicity, the custom control source is in the same source file.
    It is a better idea to have a single extern module for every custom control.
*/
extern crate user32;
extern crate winapi;
#[macro_use] extern crate native_windows_gui as nwg;

use std::any::TypeId;
use std::hash::Hash;

use nwg::custom::{Control, ControlT, AnyHandle, SysclassParams, build_sysclass, WindowParams, build_window};
use nwg::{Error, Event, Ui, simple_message, fatal_message, dispatch_events};

use winapi::{HWND, UINT, WPARAM, LPARAM, LRESULT};

// The control template. Aka the configuration object that is sent to an UI.
pub struct MyCustomWindowT;

// The actual control. The object that is saved and managed in NWG.
// A reference to this object is returned when nwg_get is used
pub struct MyCustomWindow {
    handle: HWND
}

impl<ID: Hash+Clone> ControlT<ID> for MyCustomWindowT {
    fn type_id(&self) -> TypeId {
        // This method must return the TypeID of the associated control
        // Used internally by NWG

        TypeId::of::<MyCustomWindow>()
    }

    fn events(&self) -> Vec<Event> {
        // This method must return an vec of events type that NWG will listen to for each instance of the control

        vec![Event::Closed]
    }

    #[allow(unused_variables)]
    fn build(&self, ui: &Ui<ID>) -> Result<Box<Control>, Error> {
        use winapi::{WS_HSCROLL, WS_VISIBLE, WS_VSCROLL, WS_OVERLAPPEDWINDOW};

        // This method must create the low level control and return it as a Boxed Control
        // NWG offers both build_sysclass and build_window in order to facilitate the low level window creation
        // If the method returns an error, Ui::commit will return it.

        unsafe{
            let cls_params = SysclassParams {
                class_name: "MyCustomWindowClass",      // The unique identifier of the window class
                sysproc: Some(custom_window_sysproc),   // The low level window procedure of the window
                background: None,                       // The background color of the window (use the default system color)
                style: None                             // The style class (use defaults)
            };

            let style =  WS_HSCROLL | WS_VISIBLE | WS_VSCROLL | WS_OVERLAPPEDWINDOW;
            let params = WindowParams {
                title: "My custom window",              // The window title
                class_name: "MyCustomWindowClass",      // The window class
                position: (200, 200),                   // The window starting position
                size: (500, 500),                       // The window starting size
                flags: style,                           // The window style
                ex_flags: None,                         // The window extended flags
                parent: ::std::ptr::null_mut()          // The parent (don't forget to include WS_CHILD in flags if there is one)
            };

            // Try to create the custom window class, return an error if it fails
            if let Err(e) = build_sysclass(cls_params) {
                return Err(Error::System(e));
            }

            // Try to create the window, return an error if it fails
            match build_window(params) {
                Ok(h) => {
                    Ok(Box::new(MyCustomWindow{handle: h}) as Box<Control>)
                },
                Err(e) => Err(Error::System(e))
            }
        } // unsafe
    }

}

impl Control for MyCustomWindow {
    fn handle(&self) -> AnyHandle {
        // Must return the handle of the control
        // Use internally by NWG, but it can be used to retrieve the low level handle as a user

        AnyHandle::HWND(self.handle)
    }

    fn free(&mut self) {
        // Free any resources allocated in the template build function
        // This is called by the UI when the control is removed

        use user32::DestroyWindow;
        unsafe{ DestroyWindow(self.handle) };
    }
}

// The custom window proc
#[allow(unused_variables)]
unsafe extern "system" fn custom_window_sysproc(hwnd: HWND, msg: UINT, w: WPARAM, l: LPARAM) -> LRESULT {
    use winapi::{WM_CREATE, WM_CLOSE};
    use user32::{DefWindowProcW, PostQuitMessage, ShowWindow};

    let handled = match msg {
        WM_CREATE => true,
        WM_CLOSE => {
            ShowWindow(hwnd, 0);
            PostQuitMessage(0);
            true
        }
        _ => false
    };

    if handled {
        0
    } else {
        DefWindowProcW(hwnd, msg, w, l)
    }
}

fn main() {
    let app: Ui<&'static str>;

    match Ui::new() {
        Ok(_app) => { app = _app; },
        Err(e) => { fatal_message("Fatal Error", &format!("{:?}", e) ); }
    }

    // Add our custom window to the UI
    app.pack_control(&"MyCustomWindow", MyCustomWindowT);

    // Add a chidlren
    app.pack_control(&"AButton", nwg_button!(parent="MyCustomWindow"; text="Test"; position=(10,10); size=(480, 480)) );

    // Bind an event
    app.bind(&"MyCustomWindow", &"ExitNWG", Event::Closed, |_,_,_,_| {
        simple_message("Hello", "Goodbye!");
        nwg::exit();
    });

    dispatch_events();
}
<|endoftext|>


<commit_before><commit_msg>Create rPi.rs<commit_after>const BCM2708_PERI_BASE: u32 = 0x20000000;
const GPIO_BASE: u32 = BCM2708_PERI_BASE + 0x200000;

enum Void { } // void type

struct bcm2835_peripheral {
    addr_p: u64,
    mem_fd: i32,
    map: *mut Void,
    addr: *mut i32
}
fn main() {
    let gpio = //continue later when you have time
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test case for bare static strings<commit_after>fn main() {
    let x: &static/str = "foo";
    io::println(x);
}

<|endoftext|>


<commit_before><commit_msg>commit -a doesn't add files; oops<commit_after>use communication::Data;
use communication::pact::Exchange;
use construction::{Stream, GraphBuilder};
use construction::operators::unary::UnaryStreamExt;

pub trait ExchangeExt<D: Data> {
    fn exchange<F: Fn(&D)->u64+'static>(&self, func: F) -> Self;
}

impl<G: GraphBuilder, D: Data> ExchangeExt<D> for Stream<G, D> {
    fn exchange<F: Fn(&D)->u64+'static>(&self, func: F) -> Stream<G, D> {
        self.unary_stream(Exchange::new(func), "Exchange", |input, output| {
            while let Some((time, data)) = input.pull() {
                output.session(time).give_message(data);
            }
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Add lints<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #5917.<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.

struct T(&'static [int]);

static A: T = T(&'static [5, 4, 3]);
static B: T = T(&[5, 4, 3]);
static C: T = T([5, 4, 3]);

pub fn main() {
    assert_eq!(A[0], 5);
    assert_eq!(B[1], 4);
    assert_eq!(C[2], 3);
}
<|endoftext|>


<commit_before><commit_msg>[katas] one more ticket<commit_after>impl Solution {
    pub fn duplicate_zeros(arr: &mut Vec<i32>) {
        let length = arr.len();
        let mut tmp = Vec::with_capacity(arr.len());

        for i in arr.clone() {
            if tmp.len() >= length { break; }
            tmp.push(i);

            if tmp.len() >= length { break; }
            if i == 0 { tmp.push(0); } // push one more time
        }

        *arr = tmp;
    }
}
<|endoftext|>


<commit_before><commit_msg>[Rust] Lifetime annotations can be elided<commit_after>use std::slice::Iter;

fn f1<T>(a: &Vec<T>) -> Iter<T> {
    a.iter()
}

fn f2<'a, T>(a: &'a Vec<T>) -> Iter<'a, T> {
    a.iter()
}

fn main() {
    let x = {
        let v: Vec<i32> = vec![1, 2, 3, 4];
        f1(&v)
    };
    for k in x {
        println!("{}", k);
    }
    let x = {
        let v: Vec<i32> = vec![1, 2, 3, 4];
        f2(&v)
    };
    for k in x {
        println!("{}", k);
    }
}
<|endoftext|>


<commit_before><commit_msg>Tagable should not be implemented for Value<commit_after><|endoftext|>


<commit_before><commit_msg>Create creating_a_turtle.rs<commit_after>extern crate turtle;

use turtle::Turtle;

const SIZE: f64 = 3.0;

fn main() {
    let mut turtle = Turtle::new();
    turtle.set_speed(8);

    turtle.pen_up();
    turtle.set_x(-280.0);
    turtle.set_y(-90.0);

    // Panzer
    {
        turtle.set_fill_color([62.0, 114.0, 29.0, 1.0]);
        turtle.begin_fill();

        for _ in 0..180 {
            turtle.forward(SIZE);
            turtle.right(1.0);
        }

        for _ in 0..90 {
            turtle.forward(SIZE / 3.0);
            turtle.right(1.0);
        }

        turtle.set_speed(5);
        let d = SIZE * 360.0 / std::f64::consts::PI;
        turtle.forward(d - d / 3.0);
        turtle.set_speed(10);

        for _ in 0..90 {
            turtle.forward(SIZE / 3.0);
            turtle.right(1.0);
        }

        turtle.end_fill();
    }

    // Tail
    {
        turtle.set_fill_color([119.0, 178.0, 85.0, 1.0]);
        turtle.begin_fill();

        turtle.left(90.0);
        turtle.forward(SIZE);

        for _ in 0..45 {
            turtle.forward(SIZE / 3.0);
            turtle.left(1.0);
        }

        turtle.forward(SIZE * 3.0);

        for _ in 0..25 {
            turtle.forward(SIZE / 3.0);
            turtle.left(6.0);
        }

        turtle.forward(SIZE * 9.0);
        turtle.right(6.0);
        turtle.forward(SIZE * 8.0);

        turtle.end_fill();
    }

    turtle.pen_up();
    turtle.right(55.0);
    turtle.forward(SIZE * 10.0);
    turtle.right(55.0);

    // Hind leg
    draw_leg(&mut turtle);

    turtle.right(86.5);
    turtle.forward(SIZE * 55.0);
    turtle.right(86.0);

    // Front leg
    draw_leg(&mut turtle);

    turtle.right(54.5);
    turtle.forward(SIZE * 8.0);

    // Neck
    {
        turtle.begin_fill();

        for _ in 0..15 {
            turtle.forward(SIZE * 3.0);
            turtle.left(1.5);
        }

        turtle.end_fill();
        turtle.begin_fill();

        turtle.left(100.0);
        turtle.forward(SIZE * 20.0);
        turtle.left(80.0);

        for _ in 0..4 {
            turtle.forward(SIZE * 3.7);
            turtle.left(1.5);
        }

        turtle.left(30.0);

        for _ in 0..27 {
            turtle.forward(SIZE);
            turtle.right(1.0);
        }

        turtle.end_fill();
    }

    turtle.right(172.6);
    turtle.forward(SIZE * 40.0);
    turtle.right(110.0);

    // Head
    {
        turtle.begin_fill();

        for _ in 0..20 {
            turtle.forward(SIZE * 1.2);
            turtle.left(1.0);
        }

        for _ in 0..10 {
            turtle.forward(SIZE * 1.2);
            turtle.left(4.0);
        }

        for _ in 0..10 {
            turtle.forward(SIZE / 1.5);
            turtle.left(7.0);
        }

        for _ in 0..10 {
            turtle.forward(SIZE);
            turtle.left(2.0);
        }

        for _ in 0..50 {
            turtle.forward(SIZE / 2.5);
            turtle.left(1.0);
        }

        for _ in 0..30 {
            turtle.forward(SIZE / 3.0);
            turtle.left(1.8);
        }

        for _ in 0..10 {
            turtle.forward(SIZE / 1.5);
            turtle.left(1.8);
        }

        turtle.end_fill();
    }

    turtle.left(128.0);
    turtle.forward(SIZE * 15.0);

    // Eye
    {
        turtle.set_fill_color("black");
        turtle.begin_fill();
        for _ in 0..90 {
            turtle.forward(SIZE / 3.0);
            turtle.right(4.0);
        }
        turtle.end_fill();
    }

    turtle.set_fill_color([119.0, 178.0, 85.0, 1.0]);

    turtle.left(175.0);
    turtle.forward(SIZE * 43.0);

    // Glare
    {
        // Right glare
        {
            turtle.begin_fill();

            for _ in 0..39 {
                turtle.forward(SIZE / 5.0);
                turtle.left(2.0);
            }

            turtle.forward(SIZE * 36.0);

            for _ in 0..90 {
                turtle.forward(SIZE / 2.5);
                turtle.left(2.0);
            }

            for _ in 0..42 {
                turtle.forward(SIZE);
                turtle.left(0.9);
            }

            for _ in 0..26 {
                turtle.forward(SIZE / 5.0);
                turtle.left(2.0);
            }

            turtle.end_fill();
        }

        turtle.right(18.0);
        turtle.forward(SIZE * 37.0);
        turtle.set_heading(180.0);

        // Middle glare
        {
            turtle.begin_fill();

            for _ in 0..40 {
                turtle.forward(SIZE / 4.0);
                turtle.left(2.0);
            }

            turtle.forward(SIZE * 47.0);
            turtle.left(8.5);

            for _ in 0..90 {
                turtle.forward(SIZE / 2.0);
                turtle.left(2.0);
            }
            turtle.forward(SIZE / 2.0);

            turtle.left(8.5);
            turtle.forward(SIZE * 47.0);

            for _ in 0..40 {
                turtle.left(2.0);
                turtle.forward(SIZE / 4.0);
            }

            turtle.end_fill();
        }

        turtle.left(24.0);
        turtle.forward(SIZE * 36.0);
        turtle.set_heading(180.0);

        // Left glare
        {
            turtle.begin_fill();

            for _ in 0..26 {
                turtle.forward(SIZE / 5.0);
                turtle.left(2.0);
            }

            for _ in 0..42 {
                turtle.forward(SIZE);
                turtle.left(0.9);
            }

            for _ in 0..90 {
                turtle.forward(SIZE / 2.5);
                turtle.left(2.0);
            }

            turtle.forward(SIZE * 36.0);

            for _ in 0..39 {
                turtle.forward(SIZE / 5.0);
                turtle.left(2.0);
            }

            turtle.end_fill();
        }
    }

}

fn draw_leg(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..15 {
        turtle.forward(SIZE);
        turtle.left(0.5);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 6.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 3.0);

    for _ in 0..90 {
        turtle.forward(SIZE / 6.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 14.5);

    turtle.end_fill();
}
<|endoftext|>


<commit_before><commit_msg>Use postgres::Connection::prepare_cached instead of postgres::Connection::prepare<commit_after><|endoftext|>


<commit_before>use redox::*;

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 's') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 'o') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, 'O') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'k',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, '$') => {
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, '0') => {

                                    let mut new_offset = 0;
                                    for i in 2..editor.offset {
                                        match editor.string.as_bytes()[editor.offset - i] {
                                            0 => break,
                                            10 => {
                                                new_offset = editor.offset - i + 1;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, 'd') => {
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => {}
                                        }
                                    }
                                    for _ in 1..new_offset {
                                        editor.delete(window);
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, _) => {
                                    window.set_title(&format!("{}{}{}","Editor (", &editor.url, ") Changed"));
                                    editor.string = editor.string[0 .. editor.offset].to_string() +
                                        &key_event.character.to_string() +
                                        &editor.string[editor.offset .. editor.string.len()];
                                    editor.offset += 1;
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<commit_msg>Add todo<commit_after>use redox::*;

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 's') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 'o') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, 'O') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'k',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, '$') => {
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, '0') => {

                                    let mut new_offset = 0;
                                    for i in 2..editor.offset {
                                        match editor.string.as_bytes()[editor.offset - i] {
                                            0 => break,
                                            10 => {
                                                new_offset = editor.offset - i + 1;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, 'd') => {
                                    // TODO: Is this crash proof?
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => {}
                                        }
                                    }
                                    for _ in 1..new_offset {
                                        editor.delete(window);
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, _) => {
                                    window.set_title(&format!("{}{}{}","Editor (", &editor.url, ") Changed"));
                                    editor.string = editor.string[0 .. editor.offset].to_string() +
                                        &key_event.character.to_string() +
                                        &editor.string[editor.offset .. editor.string.len()];
                                    editor.offset += 1;
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add $RUSH_VERSION env variable similar to $BASH_VERSION.<commit_after><|endoftext|>


<commit_before><commit_msg>add utils module for work with filepaths<commit_after>use std;
use std::path::{Path, PathBuf};

const BASE_DIR_NAME: &'static str = "media";

pub fn is_dir(path: &Path) -> bool {
    match std::fs::metadata(path) {
        Ok(md) => md.is_dir(),
        Err(_) => false
    }
}

pub fn get_base_dir() -> Result<PathBuf, String> {
    let mut cur_dir = std::env::current_dir().unwrap();

    loop {
        cur_dir.push(BASE_DIR_NAME);
        if is_dir(&cur_dir.as_path()) {
            return Ok(cur_dir);
        }
        if !cur_dir.pop() || !cur_dir.pop() {
            break;
        }
    }
    Err(format!("not found base direcory: {}", BASE_DIR_NAME))
}
<|endoftext|>


<commit_before><commit_msg>Use location as key in graphs, rather than tiploc string.<commit_after><|endoftext|>


<commit_before><commit_msg>Wait for key fix<commit_after><|endoftext|>


<commit_before><commit_msg>Remove erroneous reqwest cfg's<commit_after><|endoftext|>