<commit_before><commit_msg>added scatter-gather helpercode<commit_after>#![feature(default_type_params)]
use std::iter::RandomAccessIterator;

pub trait ScatterInto<'a, T,INDEX=uint> {
	fn scatter_into<SRC:Iterator<(INDEX,T)>> (&mut self, src:SRC);
	fn scatter_by_indices<IDXS:Iterator<INDEX>, TS:Iterator<T>> (&mut self, indices:IDXS,values:TS) { self.scatter_into(indices.zip(values) ) }
}

pub trait ScatterIntoGrow<'a, T,INDEX=uint> {
	/// Scatter values into a collection, and grow it if its not large enough
	fn scatter_into_grow<SRC:Iterator<(INDEX,T)>> (&mut self, src:SRC, default_value:&T);
}

// TODO - implement for slice...
impl<'a, T:Clone,INDEX:Int> ScatterInto<'a, T,INDEX> for Vec<T> {
	fn scatter_into<SRC:Iterator<(&'a INDEX,&'a T)>> (&mut self, mut src:SRC) {
		for (index,value) in src {
			let i=index.to_uint().unwrap();
			*(self.get_mut(i))=value.clone();
		}
	}
}
impl<'a, T:Clone,INDEX:Int> ScatterIntoGrow<'a, T,INDEX> for Vec<T> {
	fn scatter_into_grow<SRC:Iterator<(&'a INDEX,&'a T)> >(&mut self, mut src:SRC, default_value:&T) {
		for (index,value) in src {
			let i=index.to_uint().unwrap();
			let len=self.len();
			if i>= len {
				self.grow( 1+i-len, default_value);
			}
			*(self.get_mut(i))=value.clone();
		}
	}
}

pub trait ScatterToVec<'a, T> : Iterator<&'a T> {
	fn scatter_to_vec<I:Int,IS:Iterator<&'a I>>(self, indices:IS, default_value:&T)->Vec<T>;
}

impl<'a, T:Clone, TS:Iterator<&'a T> > ScatterToVec<'a, T> for TS {
	/// Take an iterator of values, scatter by an iterator of indices creating a new vector.
	fn scatter_to_vec<I:Int,IS:Iterator<&'a I>>(self,  indices:IS, default_value:&T)->Vec<T> {
		let mut result = Vec::new();
		let foo : ::std::iter::Zip<IS, TS> = indices.zip(self);
		result.scatter_into_grow(foo, default_value);
		result.shrink_to_fit();
		result
	}

}
trait ScatterValuesToVec<'a, I:Int> : Iterator<&'a I> {
	fn scatter_values_to_vec<T:Clone,TS:Iterator<&'a T>>(self, values:TS, default_value:&T)->Vec<T>;
}

impl<'a, I:Int, IS:Iterator<&'a I> > ScatterValuesToVec<'a, I> for IS {
	/// Take an iterator of values, scatter by an iterator of indices creating a new vector.
	fn scatter_values_to_vec<T:Int,TS:Iterator<&'a T>>(self, values:TS, default_value:&T)->Vec<T> {
		let mut result = Vec::new();
		let foo : ::std::iter::Zip<IS, TS> = self.zip(values);
		result.scatter_into_grow(foo, default_value);
		result.shrink_to_fit();
		result
	}

}

struct IterGather<'a, TS, INDICES> {
	indices: INDICES,	// todo: parameterize index.
	values: TS,		// any collection with a .index() or .get(), whichever it becomes.
}

impl<'a,T, TS:RandomAccessIterator<T>, INDICES:Iterator<&'a uint>> Iterator<T> for IterGather<'a, TS, INDICES> {
	fn next(&mut self)->Option<T> {
		match self.indices.next() {
			None=>None,
			Some(index)=>{
				self.values.idx(*index)
			}
		}
	}
}

pub trait Gather<'a, T,I=uint> : RandomAccessIterator<T> {
	/// yields an iterator that is the values of self permuted by indices from the source iterator  (look up table, shuffle, permute)
	fn gather<IS:Iterator<I>>(self, indices: IS )->IterGather<'a,  Self,IS>;
}

impl<'a, T,I, TS: RandomAccessIterator<T> > Gather<'a,T,I> for TS
{
	fn gather<IS:Iterator<I>>(self, iter_indices: IS)->IterGather<'a, TS, IS> {
		IterGather{ indices:iter_indices, values:self,  }
	}
}

pub trait GatherFrom<'a, I:Int,T,TS:RandomAccessIterator<T>> : Iterator<&'a I> {
	/// Given an iterator of indices, lookup values from a given random-acess iterator, yield an iterator over the results
	fn gather_from<'a>(self, values: TS )->IterGather<'a,  TS,Self> {
		values.gather(self)
	}
}

impl<'a, T,I:Int, IS:Iterator<&'a I>,TS:RandomAccessIterator<T> >  GatherFrom<'a, I,T,TS> for IS
{
}

//values.scatter(indices)
//indices.scatter_from(values)

fn write_and_grow<T:Clone, I:Int>(mut dst:&Vec<T>,at_index:I,value:&T, default:&T) {
	if at_index.to_uint().unwrap() >= dst.len() {
		dst.grow(at_index.to_uint().unwrap() +1 - dst.len(), default);
	}
	*dst.get_mut(at_index.to_uint().unwrap()) = value.clone();
}

pub struct BucketVec<I,T> {
	first_per_j:Vec<I>,
	num_per_j:Vec<I>,
	values:Vec<T>
}
impl<I,T> BucketVec<I,T> {
	pub fn get_num_buckets(&self)->uint{self.first_per_j.len()}
	pub fn get_num(&self, j:uint)->uint { *self.num_per_j.get(j)}
	pub fn get(&self,j:uint, i:uint)->&T {
		self.values.get( *self.first_per_j.get(j) + i)
	}
	pub fn iter(&self)->BucketVecIterBucket<I,T> {
		return BucketVecIterBucket{
			src:self, curr_j:0
		}
	}
}
pub struct BucketVecIterBucket<'a, I,T> {
	src:&'a BucketVec<I,T>, curr_j:uint
}
impl<'a, I,T> BucketVecIterBucket<'a, I,T> {
	fn next(&'a mut self)->Option<&'a [T]> {
		if self.curr_j >= self.get_num_buckets() {
			None
		} else {
			let x0=self.first_per_j.get(self.curr_j);
			let x1=x0+self.num_per_j.get(self.curr_j);
			self.curr_j+=1;
			Some( self.values.slice(x0,x1))
		}
	}
}

/// Scatter values into buckets, with minimal allocations, by prepasses that count.
fn scatter_into_buckets<I:Int,T:Clone>(scatter_indices:Vec<I>, values:Vec<T>, default:&T)-> BucketVec<I,I> {
	// TODO: version of this which scatters indices to create gather indices,
	// then yields an iterator-of-iterators over the src values

	// 'j' = bucket index;
	let mut max_j=0;
	// find the larget output index..
	for x in scatter_indices.iter() {
		max_j = ::std::cmp::max(max_j,x);
	}

	// count the number of elements per output bucket
	let mut num_per_j=Vec::new(max_j,0);
	for x in scatter_indices.iter() {
		*num_per_j.get_mut(x) +=1 ;
	}

	// allocate base index per bucket ...
	let mut first_per_j=Vec::new(max_j,0);
	let mut main_index=0;
	for x in range(0,max_j) {
		*first_per_j.get(x)=main_index;
		let write_index=main_index;
		main_index+=*num_per_j.get(x);
		*num_per_j.get_mut(x)=write_index;	// we re-use this index
	}

	// scatter the values into the output vector.. TODO:this wants to be unsafe - we avoid allocating temporary.
	let mut values: Vec<T> =Vec::from_elem(max_j, default);
	for (i,ref v) in scatter_indices.iter().zip(values.iter()) {
		let x=*num_per_j.get_mut(i);
		*values.get_mut(x) = v.clone();
		*num_per_j.get_mut(i)=x+1;
	}
	// reset 'num' indices
	for i in range(0,max_j) {
		*num_per_j.get_mut(i) -= *num_per_j.get(i);
	}

	// construct the buckets object..
	// TODO write out a permute of source indices aswell.
	BucketVec{
		first_per_j:first_per_j,
		num_per_j:num_per_j,
		values:values
	}

}

fn main() {
	let indices=vec!(3u,2u,1u,0u);
	let indices2=vec!(7u,6u,3u,0u);
	let src=vec!("zero","one","two","three");
	let result: Vec<&'static str> =Vec::from_elem(4,&"");
	std::io::print("Output of scatter:\n");
	println!("{}",result);

	let mut result2: Vec<&'static str> =Vec::new();
	result2.scatter_into_grow( indices2.iter().zip(src.iter()), &&"empty" );
	std::io::print("Output of scatter_grow:\n");
	println!("{}",result2);

	std::io::print("Scatter Iterator:\n");
	for (i,x) in src.iter().scatter_to_vec(indices2.iter(),&&"-").iter().enumerate() {
		println!("scatter result {}={}",i,x);
	}

	std::io::print("Gather iterator:\n");

	for x in src.iter().gather(indices.iter()) {
		println!("{}", x);
	}
	for x in indices.iter().gather_from(src.iter()) {
		println!("{}", x);
	}
	std::io::print("\n");
}
<|endoftext|>


<commit_before><commit_msg>use macro to remove duplciated code<commit_after><|endoftext|>


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

extern crate alloc;
extern crate core;

use alloc::boxed::Box;
use std::{io, rand};
use core::ptr;

macro_rules! readln {
    () => {
        {
            let mut line = String::new();
            match io::stdin().read_line(&mut line) {
                Ok(_) => Some(line.trim().to_string()),
                Err(_) => None
            }
        }
    };
}

fn console_title(title: &str){

}

#[no_mangle]
pub fn main() {
    console_title("Test");

    println!("Type help for a command list");
    while let Some(line) = readln!() {
        let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();

        if let Some(command) = args.get(0) {
            println!("# {}", line);
            let console_commands = ["panic", "ls", "ptr_write"];

            match &command[..] {
                command if command == console_commands[0] =>
                    panic!("Test panic"),
                command if command == console_commands[1] => {
                    // TODO: import std::fs functions into libredox
                    //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
                }
                command if command == console_commands[2] => {
                    let a_ptr = rand() as *mut u8;
                    let mut a_box = Box::new(rand() as u8);
                    unsafe {
                        ptr::write(a_ptr, rand() as u8);
                        // TODO: import Box::{from_raw, to_raw} methods in libredox
                        //ptr::write(a_box.to_raw(), rand() as u8);
                    }
                }
                _ => println!("Commands: {}", console_commands.join(" ")),
            }
        }
    }
}
<commit_msg>Write to Boxes as well for test app<commit_after>#![feature(core)]

extern crate core;

use std::Box;
use std::{io, rand};
use core::ptr;

macro_rules! readln {
    () => {
        {
            let mut line = String::new();
            match io::stdin().read_line(&mut line) {
                Ok(_) => Some(line.trim().to_string()),
                Err(_) => None
            }
        }
    };
}

fn console_title(title: &str){

}

#[no_mangle]
pub fn main() {
    console_title("Test");

    println!("Type help for a command list");
    while let Some(line) = readln!() {
        let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();

        if let Some(a_command) = args.get(0) {
            println!("# {}", line);
            let console_commands = ["panic",
                                    "ls",
                                    "ptr_write",
                                    "box_write",];

            match &a_command[..] {
                command if command == console_commands[0] =>
                    panic!("Test panic"),
                command if command == console_commands[1] => {
                    // TODO: import std::fs functions into libredox
                    //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
                }
                command if command == console_commands[2] => {
                    let a_ptr = rand() as *mut u8;
                    unsafe { ptr::write(a_ptr, rand() as u8); }
                }
                command if command == console_commands[3] => {
                    let mut a_box = Box::new(rand() as u8);
                    unsafe { ptr::write(Box::into_raw(a_box), rand() as u8); }
                }
                _ => println!("Commands: {}", console_commands.join(" ")),
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>rustc: Rename diagnostic::diagnostictype to 'level'<commit_after><|endoftext|>


<commit_before><commit_msg>[mtl] use existing CAMetalLayer if available<commit_after><|endoftext|>


<commit_before><commit_msg>Add solution to problem 28<commit_after>#[macro_use] extern crate libeuler;

/// Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is
/// formed as follows:
///
///                              21 22 23 24 25
///                              20  7  8  9 10
///                              19  6  1  2 11
///                              18  5  4  3 12
///                              17 16 15 14 13
///
/// It can be verified that the sum of the numbers on the diagonals is 101.
///
/// What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
fn main() {
    solutions! {
        inputs: (size: i64 = 1001)

        sol naive {
            let mut val = 1;
            let mut length = 1;
            let mut sum = 1;

            while length < size {
                for _ in 0..4 {
                    val += length + 1;
                    sum += val;
                }

                length += 2;
            }

            sum
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add solution to problem 44<commit_after>#[macro_use] extern crate libeuler;

/// Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers
/// are:
///
/// 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
///
/// It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is
/// not pentagonal.
///
/// Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are
/// pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
fn main() {
    solutions! {
        sol naive {
            let mut mindist = None;
            for k in 1..10_000 {
                let pk = (k * (3*k - 1)) / 2;
                for j in k..10_000 {
                    let pj = (j * (3*j - 1)) / 2;

                    if is_pentagonal(pj - pk) {
                        if is_pentagonal(pk + pj) {
                            let d = (pk - pj).abs();
                            mindist = match mindist {
                                Some(dist) => Some(if d > dist { d } else { dist }),
                                None => Some(d)
                            };
                        }
                    }
                }
            }

            mindist.unwrap()
        }
    }
}

/// x = (n(3n - 1))/2
/// 2x = n(3n - 1)
/// 2x = 3n^2 - n
/// 24x = 36n^2 - 12n
/// 24x + 1 = 36n^2 - 12n + 1
/// 24x + 1 = (6n - 1)^2
/// sqrt(24x + 1) = 6n - 1
/// 6n = sqrt(24x + 1) - 1
/// n = 1/6(sqrt(24x + 1) + 1)
fn is_pentagonal(i: i64) -> bool {
    let v = (1.0/6.0) * ((24.0 * (i as f64) + 1.0).sqrt() + 1.0);

    v.floor() == v
}
<|endoftext|>


<commit_before><commit_msg>Add solution to problem 53<commit_after>#![feature(core)]
#[macro_use] extern crate libeuler;

use std::collections::HashMap;
use std::iter::range_inclusive;
/// There are exactly ten ways of selecting three from five, 12345:
///
/// 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
///
/// In combinatorics, we use the notation, 5C3 = 10.
///
/// In general,
/// nCr = n! / (r!(n−r)!)
///
/// where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
///
/// It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
///
/// How many, not necessarily distinct, values of  nCr, for 1 ≤ n ≤ 100, are greater than
/// one-million?
fn main() {
    solutions! {
        inputs: (min_val: i64 = 1_000_000)

        sol naive {
            let mut mem = HashMap::new();

            range_inclusive(1, 100).map(|n| {
                range_inclusive(0, n).map(|r| {
                    match ncr(&mut mem, n, r) {
                        Num::TooBig => 1,
                        Num::N(a) if a > min_val => 1,
                        _ => 0
                    }
                }).sum::<i64>()
            }).sum::<i64>()
        }
    }
}

#[derive(Debug, Copy, Clone)]
enum Num {
    TooBig,
    N(i64)
}

fn ncr(memo: &mut HashMap<(i64, i64), Num>, n: i64, r: i64) -> Num {
    use Num::*;

    if memo.contains_key(&(n, r)) {
        return memo[&(n, r)];
    }

    let proto_ret = match (n, r) {
        (_, 0) => N(1),
        (n, r) if n == r => N(1),
        (n, r) => match (ncr(memo, n-1, r-1), ncr(memo, n-1, r)) {
            (TooBig, _) => TooBig,
            (_, TooBig) => TooBig,
            (N(a), N(b)) => N(a + b)
        }
    };

    let ret = match proto_ret {
        N(a) if a > 1_000_000_000 => TooBig,
        a => a
    };

    memo.insert((n,r), ret);

    ret
}
<|endoftext|>


<commit_before>// 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.

//! Feature gating
//!
//! This modules implements the gating necessary for preventing certain compiler
//! features from being used by default. This module will crawl a pre-expanded
//! AST to ensure that there are no features which are used that are not
//! enabled.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
use self::Status::*;

use abi::RustIntrinsic;
use ast::NodeId;
use ast;
use attr;
use attr::AttrMetaMethods;
use codemap::Span;
use diagnostic::SpanHandler;
use visit;
use visit::Visitor;
use parse::token;

use std::slice;

/// This is a list of all known features since the beginning of time. This list
/// can never shrink, it may only be expanded (in order to prevent old programs
/// from failing to compile). The status of each feature may change, however.
static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
    ("globs", Active),
    ("macro_rules", Active),
    ("struct_variant", Accepted),
    ("asm", Active),
    ("managed_boxes", Removed),
    ("non_ascii_idents", Active),
    ("thread_local", Active),
    ("link_args", Active),
    ("phase", Active),
    ("plugin_registrar", Active),
    ("log_syntax", Active),
    ("trace_macros", Active),
    ("concat_idents", Active),
    ("unsafe_destructor", Active),
    ("intrinsics", Active),
    ("lang_items", Active),

    ("simd", Active),
    ("default_type_params", Active),
    ("quote", Active),
    ("linkage", Active),
    ("struct_inherit", Removed),

    ("quad_precision_float", Removed),

    ("rustc_diagnostic_macros", Active),
    ("unboxed_closures", Active),
    ("import_shadowing", Active),
    ("advanced_slice_patterns", Active),
    ("tuple_indexing", Active),
    ("associated_types", Active),
    ("visible_private_types", Active),
    ("slicing_syntax", Active),

    ("if_let", Active),
    ("while_let", Active),

    // if you change this list without updating src/doc/reference.md, cmr will be sad

    // A temporary feature gate used to enable parser extensions needed
    // to bootstrap fix for #5723.
    ("issue_5723_bootstrap", Accepted),

    // These are used to test this portion of the compiler, they don't actually
    // mean anything
    ("test_accepted_feature", Accepted),
    ("test_removed_feature", Removed),
];

enum Status {
    /// Represents an active feature that is currently being implemented or
    /// currently being considered for addition/removal.
    Active,

    /// Represents a feature which has since been removed (it was once Active)
    Removed,

    /// This language feature has since been Accepted (it was once Active)
    Accepted,
}

/// A set of features to be used by later passes.
pub struct Features {
    pub default_type_params: bool,
    pub unboxed_closures: bool,
    pub rustc_diagnostic_macros: bool,
    pub import_shadowing: bool,
    pub visible_private_types: bool,
    pub quote: bool,
}

impl Features {
    pub fn new() -> Features {
        Features {
            default_type_params: false,
            unboxed_closures: false,
            rustc_diagnostic_macros: false,
            import_shadowing: false,
            visible_private_types: false,
            quote: false,
        }
    }
}

struct Context<'a> {
    features: Vec<&'static str>,
    span_handler: &'a SpanHandler,
}

impl<'a> Context<'a> {
    fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
        if !self.has_feature(feature) {
            self.span_handler.span_err(span, explain);
            self.span_handler.span_help(span, format!("add #![feature({})] to the \
                                                       crate attributes to enable",
                                                      feature).as_slice());
        }
    }

    fn has_feature(&self, feature: &str) -> bool {
        self.features.iter().any(|n| n.as_slice() == feature)
    }
}

impl<'a, 'v> Visitor<'v> for Context<'a> {
    fn visit_name(&mut self, sp: Span, name: ast::Name) {
        if !token::get_name(name).get().is_ascii() {
            self.gate_feature("non_ascii_idents", sp,
                              "non-ascii idents are not fully supported.");
        }
    }

    fn visit_view_item(&mut self, i: &ast::ViewItem) {
        match i.node {
            ast::ViewItemUse(ref path) => {
                if let ast::ViewPathGlob(..) = path.node {
                    self.gate_feature("globs", path.span,
                                      "glob import statements are \
                                       experimental and possibly buggy");
                }
            }
            ast::ViewItemExternCrate(..) => {
                for attr in i.attrs.iter() {
                    if attr.name().get() == "phase"{
                        self.gate_feature("phase", attr.span,
                                          "compile time crate loading is \
                                           experimental and possibly buggy");
                    }
                }
            }
        }
        visit::walk_view_item(self, i)
    }

    fn visit_item(&mut self, i: &ast::Item) {
        for attr in i.attrs.iter() {
            if attr.name().equiv(&("thread_local")) {
                self.gate_feature("thread_local", i.span,
                                  "`#[thread_local]` is an experimental feature, and does not \
                                  currently handle destructors. There is no corresponding \
                                  `#[task_local]` mapping to the task model");
            } else if attr.name().equiv(&("linkage")) {
                self.gate_feature("linkage", i.span,
                                  "the `linkage` attribute is experimental \
                                   and not portable across platforms")
            }
        }
        match i.node {
            ast::ItemForeignMod(ref foreign_module) => {
                if attr::contains_name(i.attrs.as_slice(), "link_args") {
                    self.gate_feature("link_args", i.span,
                                      "the `link_args` attribute is not portable \
                                       across platforms, it is recommended to \
                                       use `#[link(name = \"foo\")]` instead")
                }
                if foreign_module.abi == RustIntrinsic {
                    self.gate_feature("intrinsics",
                                      i.span,
                                      "intrinsics are subject to change")
                }
            }

            ast::ItemFn(..) => {
                if attr::contains_name(i.attrs.as_slice(), "plugin_registrar") {
                    self.gate_feature("plugin_registrar", i.span,
                                      "compiler plugins are experimental and possibly buggy");
                }
            }

            ast::ItemStruct(..) => {
                if attr::contains_name(i.attrs.as_slice(), "simd") {
                    self.gate_feature("simd", i.span,
                                      "SIMD types are experimental and possibly buggy");
                }
            }

            ast::ItemImpl(_, _, _, ref items) => {
                if attr::contains_name(i.attrs.as_slice(),
                                       "unsafe_destructor") {
                    self.gate_feature("unsafe_destructor",
                                      i.span,
                                      "`#[unsafe_destructor]` allows too \
                                       many unsafe patterns and may be \
                                       removed in the future");
                }

                for item in items.iter() {
                    match *item {
                        ast::MethodImplItem(_) => {}
                        ast::TypeImplItem(ref typedef) => {
                            self.gate_feature("associated_types",
                                              typedef.span,
                                              "associated types are \
                                               experimental")
                        }
                    }
                }
            }

            _ => {}
        }

        visit::walk_item(self, i);
    }

    fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
        match *trait_item {
            ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {}
            ast::TypeTraitItem(ref ti) => {
                self.gate_feature("associated_types",
                                  ti.ty_param.span,
                                  "associated types are experimental")
            }
        }
    }

    fn visit_mac(&mut self, macro: &ast::Mac) {
        let ast::MacInvocTT(ref path, _, _) = macro.node;
        let id = path.segments.last().unwrap().identifier;

        if id == token::str_to_ident("macro_rules") {
            self.gate_feature("macro_rules", path.span, "macro definitions are \
                not stable enough for use and are subject to change");
        }

        else if id == token::str_to_ident("asm") {
            self.gate_feature("asm", path.span, "inline assembly is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("log_syntax") {
            self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("trace_macros") {
            self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("concat_idents") {
            self.gate_feature("concat_idents", path.span, "`concat_idents` is not \
                stable enough for use and is subject to change");
        }
    }

    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
        if attr::contains_name(i.attrs.as_slice(), "linkage") {
            self.gate_feature("linkage", i.span,
                              "the `linkage` attribute is experimental \
                               and not portable across platforms")
        }
        visit::walk_foreign_item(self, i)
    }

    fn visit_ty(&mut self, t: &ast::Ty) {
        if let ast::TyClosure(ref closure) =  t.node {
            // this used to be blocked by a feature gate, but it should just
            // be plain impossible right now
            assert!(closure.onceness != ast::Once);
        }

        visit::walk_ty(self, t);
    }

    fn visit_expr(&mut self, e: &ast::Expr) {
        match e.node {
            ast::ExprClosure(_, Some(_), _, _) => {
                self.gate_feature("unboxed_closures",
                                  e.span,
                                  "unboxed closures are a work-in-progress \
                                   feature with known bugs");
            }
            ast::ExprTupField(..) => {
                self.gate_feature("tuple_indexing",
                                  e.span,
                                  "tuple indexing is experimental");
            }
            ast::ExprIfLet(..) => {
                self.gate_feature("if_let", e.span,
                                  "`if let` syntax is experimental");
            }
            ast::ExprSlice(..) => {
                self.gate_feature("slicing_syntax",
                                  e.span,
                                  "slicing syntax is experimental");
            }
            ast::ExprWhileLet(..) => {
                self.gate_feature("while_let", e.span,
                                  "`while let` syntax is experimental");
            }
            _ => {}
        }
        visit::walk_expr(self, e);
    }

    fn visit_generics(&mut self, generics: &ast::Generics) {
        for type_parameter in generics.ty_params.iter() {
            match type_parameter.default {
                Some(ref ty) => {
                    self.gate_feature("default_type_params", ty.span,
                                      "default type parameters are \
                                       experimental and possibly buggy");
                }
                None => {}
            }
        }
        visit::walk_generics(self, generics);
    }

    fn visit_attribute(&mut self, attr: &ast::Attribute) {
        if attr::contains_name(slice::ref_slice(attr), "lang") {
            self.gate_feature("lang_items",
                              attr.span,
                              "language items are subject to change");
        }
    }

    fn visit_pat(&mut self, pattern: &ast::Pat) {
        match pattern.node {
            ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
                self.gate_feature("advanced_slice_patterns",
                                  pattern.span,
                                  "multiple-element slice matches anywhere \
                                   but at the end of a slice (e.g. \
                                   `[0, ..xs, 0]` are experimental")
            }
            _ => {}
        }
        visit::walk_pat(self, pattern)
    }

    fn visit_fn(&mut self,
                fn_kind: visit::FnKind<'v>,
                fn_decl: &'v ast::FnDecl,
                block: &'v ast::Block,
                span: Span,
                _node_id: NodeId) {
        match fn_kind {
            visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
                self.gate_feature("intrinsics",
                                  span,
                                  "intrinsics are subject to change")
            }
            _ => {}
        }
        visit::walk_fn(self, fn_kind, fn_decl, block, span);
    }

    fn visit_path_parameters(&mut self, path_span: Span, parameters: &'v ast::PathParameters) {
        match *parameters {
            ast::ParenthesizedParameters(..) => {
                self.gate_feature("unboxed_closures",
                                  path_span,
                                  "parenthetical parameter notation is subject to change");
            }
            ast::AngleBracketedParameters(..) => { }
        }

        visit::walk_path_parameters(self, path_span, parameters)
    }
}

pub fn check_crate(span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, Vec<Span>) {
    let mut cx = Context {
        features: Vec::new(),
        span_handler: span_handler,
    };

    let mut unknown_features = Vec::new();

    for attr in krate.attrs.iter() {
        if !attr.check_name("feature") {
            continue
        }

        match attr.meta_item_list() {
            None => {
                span_handler.span_err(attr.span, "malformed feature attribute, \
                                                  expected #![feature(...)]");
            }
            Some(list) => {
                for mi in list.iter() {
                    let name = match mi.node {
                        ast::MetaWord(ref word) => (*word).clone(),
                        _ => {
                            span_handler.span_err(mi.span,
                                                  "malformed feature, expected just \
                                                   one word");
                            continue
                        }
                    };
                    match KNOWN_FEATURES.iter()
                                        .find(|& &(n, _)| name.equiv(&n)) {
                        Some(&(name, Active)) => { cx.features.push(name); }
                        Some(&(_, Removed)) => {
                            span_handler.span_err(mi.span, "feature has been removed");
                        }
                        Some(&(_, Accepted)) => {
                            span_handler.span_warn(mi.span, "feature has been added to Rust, \
                                                             directive not necessary");
                        }
                        None => {
                            unknown_features.push(mi.span);
                        }
                    }
                }
            }
        }
    }

    visit::walk_crate(&mut cx, krate);

    (Features {
        default_type_params: cx.has_feature("default_type_params"),
        unboxed_closures: cx.has_feature("unboxed_closures"),
        rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
        import_shadowing: cx.has_feature("import_shadowing"),
        visible_private_types: cx.has_feature("visible_private_types"),
        quote: cx.has_feature("quote"),
    },
    unknown_features)
}
<commit_msg>Remove outdated comment.<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.

//! Feature gating
//!
//! This modules implements the gating necessary for preventing certain compiler
//! features from being used by default. This module will crawl a pre-expanded
//! AST to ensure that there are no features which are used that are not
//! enabled.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
use self::Status::*;

use abi::RustIntrinsic;
use ast::NodeId;
use ast;
use attr;
use attr::AttrMetaMethods;
use codemap::Span;
use diagnostic::SpanHandler;
use visit;
use visit::Visitor;
use parse::token;

use std::slice;

// if you change this list without updating src/doc/reference.md, @cmr will be sad
static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
    ("globs", Active),
    ("macro_rules", Active),
    ("struct_variant", Accepted),
    ("asm", Active),
    ("managed_boxes", Removed),
    ("non_ascii_idents", Active),
    ("thread_local", Active),
    ("link_args", Active),
    ("phase", Active),
    ("plugin_registrar", Active),
    ("log_syntax", Active),
    ("trace_macros", Active),
    ("concat_idents", Active),
    ("unsafe_destructor", Active),
    ("intrinsics", Active),
    ("lang_items", Active),

    ("simd", Active),
    ("default_type_params", Active),
    ("quote", Active),
    ("linkage", Active),
    ("struct_inherit", Removed),

    ("quad_precision_float", Removed),

    ("rustc_diagnostic_macros", Active),
    ("unboxed_closures", Active),
    ("import_shadowing", Active),
    ("advanced_slice_patterns", Active),
    ("tuple_indexing", Active),
    ("associated_types", Active),
    ("visible_private_types", Active),
    ("slicing_syntax", Active),

    ("if_let", Active),
    ("while_let", Active),

    // A temporary feature gate used to enable parser extensions needed
    // to bootstrap fix for #5723.
    ("issue_5723_bootstrap", Accepted),

    // These are used to test this portion of the compiler, they don't actually
    // mean anything
    ("test_accepted_feature", Accepted),
    ("test_removed_feature", Removed),
];

enum Status {
    /// Represents an active feature that is currently being implemented or
    /// currently being considered for addition/removal.
    Active,

    /// Represents a feature which has since been removed (it was once Active)
    Removed,

    /// This language feature has since been Accepted (it was once Active)
    Accepted,
}

/// A set of features to be used by later passes.
pub struct Features {
    pub default_type_params: bool,
    pub unboxed_closures: bool,
    pub rustc_diagnostic_macros: bool,
    pub import_shadowing: bool,
    pub visible_private_types: bool,
    pub quote: bool,
}

impl Features {
    pub fn new() -> Features {
        Features {
            default_type_params: false,
            unboxed_closures: false,
            rustc_diagnostic_macros: false,
            import_shadowing: false,
            visible_private_types: false,
            quote: false,
        }
    }
}

struct Context<'a> {
    features: Vec<&'static str>,
    span_handler: &'a SpanHandler,
}

impl<'a> Context<'a> {
    fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
        if !self.has_feature(feature) {
            self.span_handler.span_err(span, explain);
            self.span_handler.span_help(span, format!("add #![feature({})] to the \
                                                       crate attributes to enable",
                                                      feature).as_slice());
        }
    }

    fn has_feature(&self, feature: &str) -> bool {
        self.features.iter().any(|n| n.as_slice() == feature)
    }
}

impl<'a, 'v> Visitor<'v> for Context<'a> {
    fn visit_name(&mut self, sp: Span, name: ast::Name) {
        if !token::get_name(name).get().is_ascii() {
            self.gate_feature("non_ascii_idents", sp,
                              "non-ascii idents are not fully supported.");
        }
    }

    fn visit_view_item(&mut self, i: &ast::ViewItem) {
        match i.node {
            ast::ViewItemUse(ref path) => {
                if let ast::ViewPathGlob(..) = path.node {
                    self.gate_feature("globs", path.span,
                                      "glob import statements are \
                                       experimental and possibly buggy");
                }
            }
            ast::ViewItemExternCrate(..) => {
                for attr in i.attrs.iter() {
                    if attr.name().get() == "phase"{
                        self.gate_feature("phase", attr.span,
                                          "compile time crate loading is \
                                           experimental and possibly buggy");
                    }
                }
            }
        }
        visit::walk_view_item(self, i)
    }

    fn visit_item(&mut self, i: &ast::Item) {
        for attr in i.attrs.iter() {
            if attr.name().equiv(&("thread_local")) {
                self.gate_feature("thread_local", i.span,
                                  "`#[thread_local]` is an experimental feature, and does not \
                                  currently handle destructors. There is no corresponding \
                                  `#[task_local]` mapping to the task model");
            } else if attr.name().equiv(&("linkage")) {
                self.gate_feature("linkage", i.span,
                                  "the `linkage` attribute is experimental \
                                   and not portable across platforms")
            }
        }
        match i.node {
            ast::ItemForeignMod(ref foreign_module) => {
                if attr::contains_name(i.attrs.as_slice(), "link_args") {
                    self.gate_feature("link_args", i.span,
                                      "the `link_args` attribute is not portable \
                                       across platforms, it is recommended to \
                                       use `#[link(name = \"foo\")]` instead")
                }
                if foreign_module.abi == RustIntrinsic {
                    self.gate_feature("intrinsics",
                                      i.span,
                                      "intrinsics are subject to change")
                }
            }

            ast::ItemFn(..) => {
                if attr::contains_name(i.attrs.as_slice(), "plugin_registrar") {
                    self.gate_feature("plugin_registrar", i.span,
                                      "compiler plugins are experimental and possibly buggy");
                }
            }

            ast::ItemStruct(..) => {
                if attr::contains_name(i.attrs.as_slice(), "simd") {
                    self.gate_feature("simd", i.span,
                                      "SIMD types are experimental and possibly buggy");
                }
            }

            ast::ItemImpl(_, _, _, ref items) => {
                if attr::contains_name(i.attrs.as_slice(),
                                       "unsafe_destructor") {
                    self.gate_feature("unsafe_destructor",
                                      i.span,
                                      "`#[unsafe_destructor]` allows too \
                                       many unsafe patterns and may be \
                                       removed in the future");
                }

                for item in items.iter() {
                    match *item {
                        ast::MethodImplItem(_) => {}
                        ast::TypeImplItem(ref typedef) => {
                            self.gate_feature("associated_types",
                                              typedef.span,
                                              "associated types are \
                                               experimental")
                        }
                    }
                }
            }

            _ => {}
        }

        visit::walk_item(self, i);
    }

    fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
        match *trait_item {
            ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {}
            ast::TypeTraitItem(ref ti) => {
                self.gate_feature("associated_types",
                                  ti.ty_param.span,
                                  "associated types are experimental")
            }
        }
    }

    fn visit_mac(&mut self, macro: &ast::Mac) {
        let ast::MacInvocTT(ref path, _, _) = macro.node;
        let id = path.segments.last().unwrap().identifier;

        if id == token::str_to_ident("macro_rules") {
            self.gate_feature("macro_rules", path.span, "macro definitions are \
                not stable enough for use and are subject to change");
        }

        else if id == token::str_to_ident("asm") {
            self.gate_feature("asm", path.span, "inline assembly is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("log_syntax") {
            self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("trace_macros") {
            self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("concat_idents") {
            self.gate_feature("concat_idents", path.span, "`concat_idents` is not \
                stable enough for use and is subject to change");
        }
    }

    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
        if attr::contains_name(i.attrs.as_slice(), "linkage") {
            self.gate_feature("linkage", i.span,
                              "the `linkage` attribute is experimental \
                               and not portable across platforms")
        }
        visit::walk_foreign_item(self, i)
    }

    fn visit_ty(&mut self, t: &ast::Ty) {
        if let ast::TyClosure(ref closure) =  t.node {
            // this used to be blocked by a feature gate, but it should just
            // be plain impossible right now
            assert!(closure.onceness != ast::Once);
        }

        visit::walk_ty(self, t);
    }

    fn visit_expr(&mut self, e: &ast::Expr) {
        match e.node {
            ast::ExprClosure(_, Some(_), _, _) => {
                self.gate_feature("unboxed_closures",
                                  e.span,
                                  "unboxed closures are a work-in-progress \
                                   feature with known bugs");
            }
            ast::ExprTupField(..) => {
                self.gate_feature("tuple_indexing",
                                  e.span,
                                  "tuple indexing is experimental");
            }
            ast::ExprIfLet(..) => {
                self.gate_feature("if_let", e.span,
                                  "`if let` syntax is experimental");
            }
            ast::ExprSlice(..) => {
                self.gate_feature("slicing_syntax",
                                  e.span,
                                  "slicing syntax is experimental");
            }
            ast::ExprWhileLet(..) => {
                self.gate_feature("while_let", e.span,
                                  "`while let` syntax is experimental");
            }
            _ => {}
        }
        visit::walk_expr(self, e);
    }

    fn visit_generics(&mut self, generics: &ast::Generics) {
        for type_parameter in generics.ty_params.iter() {
            match type_parameter.default {
                Some(ref ty) => {
                    self.gate_feature("default_type_params", ty.span,
                                      "default type parameters are \
                                       experimental and possibly buggy");
                }
                None => {}
            }
        }
        visit::walk_generics(self, generics);
    }

    fn visit_attribute(&mut self, attr: &ast::Attribute) {
        if attr::contains_name(slice::ref_slice(attr), "lang") {
            self.gate_feature("lang_items",
                              attr.span,
                              "language items are subject to change");
        }
    }

    fn visit_pat(&mut self, pattern: &ast::Pat) {
        match pattern.node {
            ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
                self.gate_feature("advanced_slice_patterns",
                                  pattern.span,
                                  "multiple-element slice matches anywhere \
                                   but at the end of a slice (e.g. \
                                   `[0, ..xs, 0]` are experimental")
            }
            _ => {}
        }
        visit::walk_pat(self, pattern)
    }

    fn visit_fn(&mut self,
                fn_kind: visit::FnKind<'v>,
                fn_decl: &'v ast::FnDecl,
                block: &'v ast::Block,
                span: Span,
                _node_id: NodeId) {
        match fn_kind {
            visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
                self.gate_feature("intrinsics",
                                  span,
                                  "intrinsics are subject to change")
            }
            _ => {}
        }
        visit::walk_fn(self, fn_kind, fn_decl, block, span);
    }

    fn visit_path_parameters(&mut self, path_span: Span, parameters: &'v ast::PathParameters) {
        match *parameters {
            ast::ParenthesizedParameters(..) => {
                self.gate_feature("unboxed_closures",
                                  path_span,
                                  "parenthetical parameter notation is subject to change");
            }
            ast::AngleBracketedParameters(..) => { }
        }

        visit::walk_path_parameters(self, path_span, parameters)
    }
}

pub fn check_crate(span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, Vec<Span>) {
    let mut cx = Context {
        features: Vec::new(),
        span_handler: span_handler,
    };

    let mut unknown_features = Vec::new();

    for attr in krate.attrs.iter() {
        if !attr.check_name("feature") {
            continue
        }

        match attr.meta_item_list() {
            None => {
                span_handler.span_err(attr.span, "malformed feature attribute, \
                                                  expected #![feature(...)]");
            }
            Some(list) => {
                for mi in list.iter() {
                    let name = match mi.node {
                        ast::MetaWord(ref word) => (*word).clone(),
                        _ => {
                            span_handler.span_err(mi.span,
                                                  "malformed feature, expected just \
                                                   one word");
                            continue
                        }
                    };
                    match KNOWN_FEATURES.iter()
                                        .find(|& &(n, _)| name.equiv(&n)) {
                        Some(&(name, Active)) => { cx.features.push(name); }
                        Some(&(_, Removed)) => {
                            span_handler.span_err(mi.span, "feature has been removed");
                        }
                        Some(&(_, Accepted)) => {
                            span_handler.span_warn(mi.span, "feature has been added to Rust, \
                                                             directive not necessary");
                        }
                        None => {
                            unknown_features.push(mi.span);
                        }
                    }
                }
            }
        }
    }

    visit::walk_crate(&mut cx, krate);

    (Features {
        default_type_params: cx.has_feature("default_type_params"),
        unboxed_closures: cx.has_feature("unboxed_closures"),
        rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
        import_shadowing: cx.has_feature("import_shadowing"),
        visible_private_types: cx.has_feature("visible_private_types"),
        quote: cx.has_feature("quote"),
    },
    unknown_features)
}
<|endoftext|>


<commit_before>//! Misc low level stuff

export type_desc;
export get_type_desc;
export size_of;
export min_align_of;
export pref_align_of;
export refcount;
export log_str;
export lock_and_signal, condition, methods;

import task::atomically;

enum type_desc = {
    size: uint,
    align: uint
    // Remaining fields not listed
};

type rust_cond_lock = *libc::c_void;

#[abi = "cdecl"]
extern mod rustrt {
    pure fn shape_log_str(t: *sys::type_desc, data: *()) -> ~str;

    fn rust_create_cond_lock() -> rust_cond_lock;
    fn rust_destroy_cond_lock(lock: rust_cond_lock);
    fn rust_lock_cond_lock(lock: rust_cond_lock);
    fn rust_unlock_cond_lock(lock: rust_cond_lock);
    fn rust_wait_cond_lock(lock: rust_cond_lock);
    fn rust_signal_cond_lock(lock: rust_cond_lock) -> bool;
}

#[abi = "rust-intrinsic"]
extern mod rusti {
    fn get_tydesc<T>() -> *();
    fn size_of<T>() -> uint;
    fn pref_align_of<T>() -> uint;
    fn min_align_of<T>() -> uint;
}

/**
 * Returns a pointer to a type descriptor.
 *
 * Useful for calling certain function in the Rust runtime or otherwise
 * performing dark magick.
 */
pure fn get_type_desc<T>() -> *type_desc {
    unchecked { rusti::get_tydesc::<T>() as *type_desc }
}

/// Returns the size of a type
#[inline(always)]
pure fn size_of<T>() -> uint {
    unchecked { rusti::size_of::<T>() }
}

/**
 * Returns the ABI-required minimum alignment of a type
 *
 * This is the alignment used for struct fields. It may be smaller
 * than the preferred alignment.
 */
pure fn min_align_of<T>() -> uint {
    unchecked { rusti::min_align_of::<T>() }
}

/// Returns the preferred alignment of a type
pure fn pref_align_of<T>() -> uint {
    unchecked { rusti::pref_align_of::<T>() }
}

/// Returns the refcount of a shared box (as just before calling this)
pure fn refcount<T>(+t: @T) -> uint {
    unsafe {
        let ref_ptr: *uint = unsafe::reinterpret_cast(t);
        *ref_ptr - 1
    }
}

pure fn log_str<T>(t: T) -> ~str {
    unsafe {
        let data_ptr: *() = unsafe::reinterpret_cast(ptr::addr_of(t));
        rustrt::shape_log_str(get_type_desc::<T>(), data_ptr)
    }
}

class lock_and_signal {
    let lock: rust_cond_lock;
    new() {
        self.lock = rustrt::rust_create_cond_lock();
    }
    drop { rustrt::rust_destroy_cond_lock(self.lock); }
}

enum condition {
    condition_(rust_cond_lock)
}

class unlock {
    let lock: rust_cond_lock;
    new(lock: rust_cond_lock) { self.lock = lock; }
    drop { rustrt::rust_unlock_cond_lock(self.lock); }
}

impl methods for lock_and_signal {
    unsafe fn lock<T>(f: fn() -> T) -> T {
        rustrt::rust_lock_cond_lock(self.lock);
        let _r = unlock(self.lock);
        do atomically {
            f()
        }
    }

    unsafe fn lock_cond<T>(f: fn(condition) -> T) -> T {
        rustrt::rust_lock_cond_lock(self.lock);
        let _r = unlock(self.lock);
        do atomically {
            f(condition_(self.lock))
        }
    }
}

impl methods for condition {
    fn wait() {
        rustrt::rust_wait_cond_lock(*self);
    }

    fn signal() -> bool {
        rustrt::rust_signal_cond_lock(*self)
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn size_of_basic() {
        assert size_of::<u8>() == 1u;
        assert size_of::<u16>() == 2u;
        assert size_of::<u32>() == 4u;
        assert size_of::<u64>() == 8u;
    }

    #[test]
    #[cfg(target_arch = "x86")]
    #[cfg(target_arch = "arm")]
    fn size_of_32() {
        assert size_of::<uint>() == 4u;
        assert size_of::<*uint>() == 4u;
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn size_of_64() {
        assert size_of::<uint>() == 8u;
        assert size_of::<*uint>() == 8u;
    }

    #[test]
    fn align_of_basic() {
        assert pref_align_of::<u8>() == 1u;
        assert pref_align_of::<u16>() == 2u;
        assert pref_align_of::<u32>() == 4u;
    }

    #[test]
    #[cfg(target_arch = "x86")]
    #[cfg(target_arch = "arm")]
    fn align_of_32() {
        assert pref_align_of::<uint>() == 4u;
        assert pref_align_of::<*uint>() == 4u;
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn align_of_64() {
        assert pref_align_of::<uint>() == 8u;
        assert pref_align_of::<*uint>() == 8u;
    }

    #[test]
    #[ignore] // this can go into infinite loops
    fn condition_variable() {
        let lock = arc::arc(lock_and_signal());
        let lock2 = arc::clone(&lock);

        do task::spawn |move lock2| {
            let lock = arc::get(&lock2);
            do (*lock).lock_cond |c| {
                c.wait();
            }
        }

        let mut signaled = false;
        while !signaled {
            do (*arc::get(&lock)).lock_cond |c| {
                signaled = c.signal()
            }
        }
    }
}

// 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>rust_cond_lock acquire/release should be inside the atomically { .. }<commit_after>//! Misc low level stuff

export type_desc;
export get_type_desc;
export size_of;
export min_align_of;
export pref_align_of;
export refcount;
export log_str;
export lock_and_signal, condition, methods;

import task::atomically;

enum type_desc = {
    size: uint,
    align: uint
    // Remaining fields not listed
};

type rust_cond_lock = *libc::c_void;

#[abi = "cdecl"]
extern mod rustrt {
    pure fn shape_log_str(t: *sys::type_desc, data: *()) -> ~str;

    fn rust_create_cond_lock() -> rust_cond_lock;
    fn rust_destroy_cond_lock(lock: rust_cond_lock);
    fn rust_lock_cond_lock(lock: rust_cond_lock);
    fn rust_unlock_cond_lock(lock: rust_cond_lock);
    fn rust_wait_cond_lock(lock: rust_cond_lock);
    fn rust_signal_cond_lock(lock: rust_cond_lock) -> bool;
}

#[abi = "rust-intrinsic"]
extern mod rusti {
    fn get_tydesc<T>() -> *();
    fn size_of<T>() -> uint;
    fn pref_align_of<T>() -> uint;
    fn min_align_of<T>() -> uint;
}

/**
 * Returns a pointer to a type descriptor.
 *
 * Useful for calling certain function in the Rust runtime or otherwise
 * performing dark magick.
 */
pure fn get_type_desc<T>() -> *type_desc {
    unchecked { rusti::get_tydesc::<T>() as *type_desc }
}

/// Returns the size of a type
#[inline(always)]
pure fn size_of<T>() -> uint {
    unchecked { rusti::size_of::<T>() }
}

/**
 * Returns the ABI-required minimum alignment of a type
 *
 * This is the alignment used for struct fields. It may be smaller
 * than the preferred alignment.
 */
pure fn min_align_of<T>() -> uint {
    unchecked { rusti::min_align_of::<T>() }
}

/// Returns the preferred alignment of a type
pure fn pref_align_of<T>() -> uint {
    unchecked { rusti::pref_align_of::<T>() }
}

/// Returns the refcount of a shared box (as just before calling this)
pure fn refcount<T>(+t: @T) -> uint {
    unsafe {
        let ref_ptr: *uint = unsafe::reinterpret_cast(t);
        *ref_ptr - 1
    }
}

pure fn log_str<T>(t: T) -> ~str {
    unsafe {
        let data_ptr: *() = unsafe::reinterpret_cast(ptr::addr_of(t));
        rustrt::shape_log_str(get_type_desc::<T>(), data_ptr)
    }
}

class lock_and_signal {
    let lock: rust_cond_lock;
    new() {
        self.lock = rustrt::rust_create_cond_lock();
    }
    drop { rustrt::rust_destroy_cond_lock(self.lock); }
}

enum condition {
    condition_(rust_cond_lock)
}

class unlock {
    let lock: rust_cond_lock;
    new(lock: rust_cond_lock) { self.lock = lock; }
    drop { rustrt::rust_unlock_cond_lock(self.lock); }
}

impl methods for lock_and_signal {
    unsafe fn lock<T>(f: fn() -> T) -> T {
        do atomically {
            rustrt::rust_lock_cond_lock(self.lock);
            let _r = unlock(self.lock);
            f()
        }
    }

    unsafe fn lock_cond<T>(f: fn(condition) -> T) -> T {
        do atomically {
            rustrt::rust_lock_cond_lock(self.lock);
            let _r = unlock(self.lock);
            f(condition_(self.lock))
        }
    }
}

impl methods for condition {
    fn wait() {
        rustrt::rust_wait_cond_lock(*self);
    }

    fn signal() -> bool {
        rustrt::rust_signal_cond_lock(*self)
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn size_of_basic() {
        assert size_of::<u8>() == 1u;
        assert size_of::<u16>() == 2u;
        assert size_of::<u32>() == 4u;
        assert size_of::<u64>() == 8u;
    }

    #[test]
    #[cfg(target_arch = "x86")]
    #[cfg(target_arch = "arm")]
    fn size_of_32() {
        assert size_of::<uint>() == 4u;
        assert size_of::<*uint>() == 4u;
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn size_of_64() {
        assert size_of::<uint>() == 8u;
        assert size_of::<*uint>() == 8u;
    }

    #[test]
    fn align_of_basic() {
        assert pref_align_of::<u8>() == 1u;
        assert pref_align_of::<u16>() == 2u;
        assert pref_align_of::<u32>() == 4u;
    }

    #[test]
    #[cfg(target_arch = "x86")]
    #[cfg(target_arch = "arm")]
    fn align_of_32() {
        assert pref_align_of::<uint>() == 4u;
        assert pref_align_of::<*uint>() == 4u;
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn align_of_64() {
        assert pref_align_of::<uint>() == 8u;
        assert pref_align_of::<*uint>() == 8u;
    }

    #[test]
    #[ignore] // this can go into infinite loops
    fn condition_variable() {
        let lock = arc::arc(lock_and_signal());
        let lock2 = arc::clone(&lock);

        do task::spawn |move lock2| {
            let lock = arc::get(&lock2);
            do (*lock).lock_cond |c| {
                c.wait();
            }
        }

        let mut signaled = false;
        while !signaled {
            do (*arc::get(&lock)).lock_cond |c| {
                signaled = c.signal()
            }
        }
    }
}

// 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>Stub for k-means<commit_after>use linalg::matrix::Matrix;
use linalg::vector::Vector;
use learning::UnSupModel;

struct KMeansClassifier {
    iters: usize,
    k: usize,
    centroids: Matrix<f64>,
}

impl UnSupModel<Matrix<f64>, Vector<usize>> for KMeansClassifier {
    fn predict(&self, data: Matrix<f64>) -> Vector<usize> {
        Vector::new(vec![0])
    }

    fn train(&mut self, data: Matrix<f64>) {}
}

fn init_centroids(kmeans: KMeansClassifier) {}

fn find_closest_centroids(kmeans: KMeansClassifier, data: Matrix<f64>) {}

fn compute_means(kmeans: KMeansClassifier, data: Matrix<f64>, classes: Vector<usize>) {}
<|endoftext|>


<commit_before>export anymap, seqmap, parmap;

fn anymap<T:send, U:send>(v: [T], f: fn~(T) -> U) -> [U] {
    seqmap(v, f)
}

fn seqmap<T, U>(v: [T], f: fn(T) -> U) -> [U] {
    vec::map(v, f)
}

fn parmap<T:send, U:send>(v: [T], f: fn~(T) -> U) -> [U] unsafe {
    let futures = vec::map(v) {|elt|
        let po = comm::port();
        let ch = comm::chan(po);
        let addr = ptr::addr_of(elt);
        task::spawn {||
            comm::send(ch, f(*addr));
        }
        po
    };
    vec::map(futures) {|future|
        comm::recv(future)
    }
}

#[test]
fn test_parallel_map() {
    let i = [1, 2, 3, 4];
    let j = parmap(i) {|e| e + 1 };
    assert j == [2, 3, 4, 5];
}<commit_msg>rustdoc: Use parallel map by default<commit_after>export anymap, seqmap, parmap;

fn anymap<T:send, U:send>(v: [T], f: fn~(T) -> U) -> [U] {
    parmap(v, f)
}

fn seqmap<T, U>(v: [T], f: fn(T) -> U) -> [U] {
    vec::map(v, f)
}

fn parmap<T:send, U:send>(v: [T], f: fn~(T) -> U) -> [U] unsafe {
    let futures = vec::map(v) {|elt|
        let po = comm::port();
        let ch = comm::chan(po);
        let addr = ptr::addr_of(elt);
        task::spawn {||
            comm::send(ch, f(*addr));
        }
        po
    };
    vec::map(futures) {|future|
        comm::recv(future)
    }
}

#[test]
fn test_parallel_map() {
    let i = [1, 2, 3, 4];
    let j = parmap(i) {|e| e + 1 };
    assert j == [2, 3, 4, 5];
}<|endoftext|>


<commit_before>use redox::*;

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            }
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            K_ESC => break,
                            K_BKSP => if self.offset > 0 {
                                window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                self.string = self.string[0 .. self.offset - 1].to_string() +
                                              &self.string[self.offset .. self.string.len()];
                                self.offset -= 1;
                            },
                            K_DEL => if self.offset < self.string.len() {
                                window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                self.string = self.string[0 .. self.offset].to_string() +
                                              &self.string[self.offset + 1 .. self.string.len() - 1];
                            },
                            K_F5 => self.reload(&mut window),
                            K_F6 => self.save(&mut window),
                            K_HOME => self.offset = 0,
                            K_UP => {
                                let mut new_offset = 0;
                                for i in 2..self.offset {
                                    match self.string.as_bytes()[self.offset - i] {
                                        0 => break,
                                        10 => {
                                            new_offset = self.offset - i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                self.offset = new_offset;
                            }
                            K_LEFT => if self.offset > 0 {
                                self.offset -= 1;
                            },
                            K_RIGHT => if self.offset < self.string.len() {
                                self.offset += 1;
                            },
                            K_END => self.offset = self.string.len(),
                            K_DOWN => {
                                let mut new_offset = self.string.len();
                                for i in self.offset..self.string.len() {
                                    match self.string.as_bytes()[i] {
                                        0 => break,
                                        10 => {
                                            new_offset = i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                self.offset = new_offset;
                            }
                            _ => match key_event.character {
                                '\0' => (),
                                _ => {
                                    window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                    self.string = self.string[0 .. self.offset].to_string() +
                                                  &key_event.character.to_string() +
                                                  &self.string[self.offset .. self.string.len()];
                                    self.offset += 1;
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Make editor behave more Vi-like<commit_after>use redox::*;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        use self::Mode::*;
                        match (mode, key_event.scancode) {
                            (Insert, K_ESC) => mode = Normal,
                            (Insert, K_BKSP) => if self.offset > 0 {
                                window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                self.string = self.string[0 .. self.offset - 1].to_string() +
                                              &self.string[self.offset .. self.string.len()];
                                self.offset -= 1;
                            },
                            (Insert, K_DEL) => if self.offset < self.string.len() {
                                window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                self.string = self.string[0 .. self.offset].to_string() +
                                              &self.string[self.offset + 1 .. self.string.len() - 1];
                            },
                            (_, K_F5) => self.reload(&mut window),
                            (_, K_F6) => self.save(&mut window),
                            (_, K_HOME) => self.offset = 0,
                            (_, K_UP) => self.up(),
                            (_, K_LEFT) => self.left(),
                            (_, K_RIGHT) => self.right(),
                            (_, K_END) => self.offset = self.string.len(),
                            (_, K_DOWN) => self.down(),
                            (m, _) => match (m, key_event.character) {
                                (Normal, 'i') => mode = Insert,
                                (Normal, 'h') => self.left(),
                                (Normal, 'l') => self.right(),
                                (Normal, 'k') => self.up(),
                                (Normal, 'j') => self.down(),
                                (Normal, 'G') => self.offset = self.string.len(),
                                (Normal, 'a') => {
                                    self.right();
                                    mode = Insert;
                                },
                                (Insert, '\0') => (),
                                (Insert, _) => {
                                    window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                    self.string = self.string[0 .. self.offset].to_string() +
                                                  &key_event.character.to_string() +
                                                  &self.string[self.offset .. self.string.len()];
                                    self.offset += 1;
                                },
                                _ => {},
                            }
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before><commit_msg>zzz well that half-works, tmrw is another day I guess<commit_after><|endoftext|>


<commit_before><commit_msg>wip: try to avoid lifetime errors<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed data race issue regarding locking the mutex of the vec of data descriptors.<commit_after><|endoftext|>


<commit_before><commit_msg>very shady actors<commit_after><|endoftext|>


<commit_before><commit_msg>make typing statuses<commit_after><|endoftext|>


<commit_before><commit_msg>Only show prompt in command mode<commit_after><|endoftext|>


<commit_before><commit_msg>everything but a sprite and three events left for homescreen<commit_after><|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before><commit_msg>Add box filter resampler<commit_after><|endoftext|>


<commit_before><commit_msg>Added implementation of Unique so we can work on Rust stable.<commit_after>use std::marker::PhantomData;
use std::ops::Deref;

pub struct Unique<T> {
    contents: *mut T,
    _marker: PhantomData<T>,
}

impl<T> Deref for Unique<T> {
    type Target = *mut T;
    fn deref(&self) -> &Self::Target {
        &self.contents
    }
}

impl<T> Unique<T> {
    pub fn new(ptr: *mut T) -> Self {
        Unique {
            contents: ptr,
            _marker:  PhantomData,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Implemented some structues around backpropagation, still heavily  WIP<commit_after>pub fn sgd(net: nn::Network, training_data: Vec<Data>, epochs: u8, mini_batch_size: u8, eta: f32) {
    use rand;
    let mut rng = rand::thread_rng();

    for j in 0..epochs {
        rng.shuffle(training_data);
        //let mini_batches = training_data.chunks(mini_batch_size);
        for mini_batch in training_data.chunks(mini_batch_size) {
            nn.update_mini_batch(mini_batch, eta);
        }
        println!("Epoch {} complete!", j);
    }

}

/*
def SGD(self, training_data, epochs, mini_batch_size, eta,
            test_data=None):
        """Train the neural network using mini-batch stochastic
        gradient descent.  The "training_data" is a list of tuples
        "(x, y)" representing the training inputs and the desired
        outputs.  The other non-optional parameters are
        self-explanatory.  If "test_data" is provided then the
        network will be evaluated against the test data after each
        epoch, and partial progress printed out.  This is useful for
        tracking progress, but slows things down substantially."""
        if test_data: n_test = len(test_data)
        n = len(training_data)
        for j in xrange(epochs):
            random.shuffle(training_data)
            mini_batches = [
                training_data[k:k+mini_batch_size]
                for k in xrange(0, n, mini_batch_size)]
            for mini_batch in mini_batches:
                self.update_mini_batch(mini_batch, eta)
            if test_data:
                print "Epoch {0}: {1} / {2}".format(
                    j, self.evaluate(test_data), n_test)
            else:
                print "Epoch {0} complete".format(j)*/
<|endoftext|>


<commit_before><commit_msg>Updated pegger scoring logic.<commit_after><|endoftext|>