<commit_before>#![unstable(feature = "futures_api",
            reason = "futures in libcore are unstable",
            issue = "50547")]

use marker::Unpin;
use ops;
use pin::Pin;
use task::{Poll, Waker};

/// A future represents an asynchronous computation.
///
/// A future is a value that may not have finished computing yet. This kind of
/// "asynchronous value" makes it possible for a thread to continue doing useful
/// work while it waits for the value to become available.
///
/// # The `poll` method
///
/// The core method of future, `poll`, *attempts* to resolve the future into a
/// final value. This method does not block if the value is not ready. Instead,
/// the current task is scheduled to be woken up when it's possible to make
/// further progress by `poll`ing again. The wake up is performed using
/// the `waker` argument of the `poll()` method, which is a handle for waking
/// up the current task.
///
/// When using a future, you generally won't call `poll` directly, but instead
/// `await!` the value.
#[must_use = "futures do nothing unless polled"]
pub trait Future {
    /// The type of value produced on completion.
    type Output;

    /// Attempt to resolve the future to a final value, registering
    /// the current task for wakeup if the value is not yet available.
    ///
    /// # Return value
    ///
    /// This function returns:
    ///
    /// - [`Poll::Pending`] if the future is not ready yet
    /// - [`Poll::Ready(val)`] with the result `val` of this future if it
    ///   finished successfully.
    ///
    /// Once a future has finished, clients should not `poll` it again.
    ///
    /// When a future is not ready yet, `poll` returns `Poll::Pending` and
    /// stores a clone of the [`Waker`] to be woken once the future can
    /// make progress. For example, a future waiting for a socket to become
    /// readable would call `.clone()` on the [`Waker`] and store it.
    /// When a signal arrives elsewhere indicating that the socket is readable,
    /// `[Waker::wake]` is called and the socket future's task is awoken.
    /// Once a task has been woken up, it should attempt to `poll` the future
    /// again, which may or may not produce a final value.
    ///
    /// Note that on multiple calls to `poll`, only the most recent
    /// [`Waker`] passed to `poll` should be scheduled to receive a
    /// wakeup.
    ///
    /// # Runtime characteristics
    ///
    /// Futures alone are *inert*; they must be *actively* `poll`ed to make
    /// progress, meaning that each time the current task is woken up, it should
    /// actively re-`poll` pending futures that it still has an interest in.
    ///
    /// The `poll` function is not called repeatedly in a tight loop -- instead,
    /// it should only be called when the future indicates that it is ready to
    /// make progress (by calling `wake()`). If you're familiar with the
    /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
    /// typically do *not* suffer the same problems of "all wakeups must poll
    /// all events"; they are more like `epoll(4)`.
    ///
    /// An implementation of `poll` should strive to return quickly, and should
    /// not block. Returning quickly prevents unnecessarily clogging up
    /// threads or event loops. If it is known ahead of time that a call to
    /// `poll` may end up taking awhile, the work should be offloaded to a
    /// thread pool (or something similar) to ensure that `poll` can return
    /// quickly.
    ///
    /// An implementation of `poll` may also never cause memory unsafety.
    ///
    /// # Panics
    ///
    /// Once a future has completed (returned `Ready` from `poll`),
    /// then any future calls to `poll` may panic, block forever, or otherwise
    /// cause any kind of bad behavior expect causing memory unsafety.
    /// The `Future` trait itself provides no guarantees about the behavior
    /// of `poll` after a future has completed.
    ///
    /// [`Poll::Pending`]: ../task/enum.Poll.html#variant.Pending
    /// [`Poll::Ready(val)`]: ../task/enum.Poll.html#variant.Ready
    /// [`Waker`]: ../task/struct.Waker.html
    /// [`Waker::wake`]: ../task/struct.Waker.html#method.wake
    fn poll(self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output>;
}

impl<F: ?Sized + Future + Unpin> Future for &mut F {
    type Output = F::Output;

    fn poll(mut self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
        F::poll(Pin::new(&mut **self), waker)
    }
}

impl
 Future for Pin

where
    P: Unpin + ops::DerefMut,
    P::Target: Future,
{
    type Output = <
::Target as Future>::Output;

    fn poll(self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
        Pin::get_mut(self).as_mut().poll(waker)
    }
}
<commit_msg>Rollup merge of #58565 - thomaseizinger:typo-future-docs, r=frewsxcv<commit_after>#![unstable(feature = "futures_api",
            reason = "futures in libcore are unstable",
            issue = "50547")]

use marker::Unpin;
use ops;
use pin::Pin;
use task::{Poll, Waker};

/// A future represents an asynchronous computation.
///
/// A future is a value that may not have finished computing yet. This kind of
/// "asynchronous value" makes it possible for a thread to continue doing useful
/// work while it waits for the value to become available.
///
/// # The `poll` method
///
/// The core method of future, `poll`, *attempts* to resolve the future into a
/// final value. This method does not block if the value is not ready. Instead,
/// the current task is scheduled to be woken up when it's possible to make
/// further progress by `poll`ing again. The wake up is performed using
/// the `waker` argument of the `poll()` method, which is a handle for waking
/// up the current task.
///
/// When using a future, you generally won't call `poll` directly, but instead
/// `await!` the value.
#[must_use = "futures do nothing unless polled"]
pub trait Future {
    /// The type of value produced on completion.
    type Output;

    /// Attempt to resolve the future to a final value, registering
    /// the current task for wakeup if the value is not yet available.
    ///
    /// # Return value
    ///
    /// This function returns:
    ///
    /// - [`Poll::Pending`] if the future is not ready yet
    /// - [`Poll::Ready(val)`] with the result `val` of this future if it
    ///   finished successfully.
    ///
    /// Once a future has finished, clients should not `poll` it again.
    ///
    /// When a future is not ready yet, `poll` returns `Poll::Pending` and
    /// stores a clone of the [`Waker`] to be woken once the future can
    /// make progress. For example, a future waiting for a socket to become
    /// readable would call `.clone()` on the [`Waker`] and store it.
    /// When a signal arrives elsewhere indicating that the socket is readable,
    /// `[Waker::wake]` is called and the socket future's task is awoken.
    /// Once a task has been woken up, it should attempt to `poll` the future
    /// again, which may or may not produce a final value.
    ///
    /// Note that on multiple calls to `poll`, only the most recent
    /// [`Waker`] passed to `poll` should be scheduled to receive a
    /// wakeup.
    ///
    /// # Runtime characteristics
    ///
    /// Futures alone are *inert*; they must be *actively* `poll`ed to make
    /// progress, meaning that each time the current task is woken up, it should
    /// actively re-`poll` pending futures that it still has an interest in.
    ///
    /// The `poll` function is not called repeatedly in a tight loop -- instead,
    /// it should only be called when the future indicates that it is ready to
    /// make progress (by calling `wake()`). If you're familiar with the
    /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
    /// typically do *not* suffer the same problems of "all wakeups must poll
    /// all events"; they are more like `epoll(4)`.
    ///
    /// An implementation of `poll` should strive to return quickly, and should
    /// not block. Returning quickly prevents unnecessarily clogging up
    /// threads or event loops. If it is known ahead of time that a call to
    /// `poll` may end up taking awhile, the work should be offloaded to a
    /// thread pool (or something similar) to ensure that `poll` can return
    /// quickly.
    ///
    /// An implementation of `poll` may also never cause memory unsafety.
    ///
    /// # Panics
    ///
    /// Once a future has completed (returned `Ready` from `poll`),
    /// then any future calls to `poll` may panic, block forever, or otherwise
    /// cause any kind of bad behavior except causing memory unsafety.
    /// The `Future` trait itself provides no guarantees about the behavior
    /// of `poll` after a future has completed.
    ///
    /// [`Poll::Pending`]: ../task/enum.Poll.html#variant.Pending
    /// [`Poll::Ready(val)`]: ../task/enum.Poll.html#variant.Ready
    /// [`Waker`]: ../task/struct.Waker.html
    /// [`Waker::wake`]: ../task/struct.Waker.html#method.wake
    fn poll(self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output>;
}

impl<F: ?Sized + Future + Unpin> Future for &mut F {
    type Output = F::Output;

    fn poll(mut self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
        F::poll(Pin::new(&mut **self), waker)
    }
}

impl
 Future for Pin

where
    P: Unpin + ops::DerefMut,
    P::Target: Future,
{
    type Output = <
::Target as Future>::Output;

    fn poll(self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
        Pin::get_mut(self).as_mut().poll(waker)
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #491 - Roguelazer:add_getpeereid_function, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>feat: New day, new 30 days of code solution<commit_after><|endoftext|>


<commit_before><commit_msg>Create (6 kyu) Easy Balance Checking.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for std._vec.init_elt, and an XFAILed test for std._vec.init_fn.<commit_after>use std;

fn test_init_elt() {
  let vec[uint] v = std._vec.init_elt[uint](uint(5), uint(3));
  check (std._vec.len[uint](v) == uint(3));
  check (v.(0) == uint(5));
  check (v.(1) == uint(5));
  check (v.(2) == uint(5));
}

fn id(uint x) -> uint {
  ret x;
}
fn test_init_fn() {
  let fn(uint)->uint op = id;
  let vec[uint] v = std._vec.init_fn[uint](op, uint(5));
  // FIXME #108: Can't call templated function twice in the same
  // program, at the moment.
  //check (std._vec.len[uint](v) == uint(5));
  check (v.(0) == uint(0));
  check (v.(1) == uint(1));
  check (v.(2) == uint(2));
  check (v.(3) == uint(3));
  check (v.(4) == uint(4));
}

fn main() {
  test_init_elt();
  //XFAIL: test_init_fn();  // Segfaults.
}<|endoftext|>


<commit_before><commit_msg>Fix another console bug<commit_after><|endoftext|>


<commit_before><commit_msg>Add id reporting in imag-edit<commit_after><|endoftext|>


<commit_before><commit_msg>Remove redundant clone() call<commit_after><|endoftext|>


<commit_before><commit_msg>Added some comments to token.rs and changed some names.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove outcommented code<commit_after><|endoftext|>


<commit_before>use redox::{self, env, BMPFile};
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::file::File;
use redox::io::Read;
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileManager {
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    files: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut resource = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp"));

    let mut vec: Vec<u8> = Vec::new();
    resource.read_to_end(&mut vec);

    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            folder_icon: load_icon("inode-directory"),
            audio_icon: load_icon("audio-x-wav"),
            bin_icon: load_icon("application-x-executable"),
            image_icon: load_icon("image-x-generic"),
            source_icon: load_icon("text-x-makefile"),
            script_icon: load_icon("text-x-script"),
            text_icon: load_icon("text-x-generic"),
            file_icon: load_icon("unknown"),
            files: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        for string in self.files.iter() {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            if string.ends_with('/') {
                window.image(0,
                             32 * row as isize,
                             self.folder_icon.width(),
                             self.folder_icon.height(),
                             self.folder_icon.as_slice());
            } else if string.ends_with(".wav") {
                window.image(0,
                             32 * row as isize,
                             self.audio_icon.width(),
                             self.audio_icon.height(),
                             self.audio_icon.as_slice());
            } else if string.ends_with(".bin") {
                window.image(0,
                             32 * row as isize,
                             self.bin_icon.width(),
                             self.bin_icon.height(),
                             self.bin_icon.as_slice());
            } else if string.ends_with(".bmp") {
                window.image(0,
                             32 * row as isize,
                             self.image_icon.width(),
                             self.image_icon.height(),
                             self.image_icon.as_slice());
            } else if string.ends_with(".rs") || string.ends_with(".asm") || string.ends_with(".list") {
                window.image(0,
                             32 * row as isize,
                             self.source_icon.width(),
                             self.source_icon.height(),
                             self.source_icon.as_slice());
            } else if string.ends_with(".sh") || string.ends_with(".lua") {
                window.image(0,
                             32 * row as isize,
                             self.script_icon.width(),
                             self.script_icon.height(),
                             self.script_icon.as_slice());
            } else if string.ends_with(".md") || string.ends_with(".txt") {
                window.image(0,
                             32 * row as isize,
                             self.text_icon.width(),
                             self.text_icon.height(),
                             self.text_icon.as_slice());
            } else {
                window.image(0,
                             32 * row as isize,
                             self.file_icon.width(),
                             self.file_icon.height(),
                             self.file_icon.as_slice());
            }

            let mut col = 0;
            for c in string.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }
            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        {
            let mut resource = File::open(path);

            let mut vec: Vec<u8> = Vec::new();
            resource.read_to_end(&mut vec);

            for file in unsafe { String::from_utf8_unchecked(vec) }.split('\n') {
                if width < 40 + (file.len() + 1) * 8 {
                    width = 40 + (file.len() + 1) * 8;
                }
                self.files.push(file.to_string());
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path);

        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 {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Option::Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            Option::None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

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

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && (self.last_mouse_event.x - mouse_event.x).abs() <= 4
                            && (self.last_mouse_event.y - mouse_event.y).abs() <= 4 {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                match self.files.get(self.selected as usize) {
                                    Option::Some(file) => {
                                        File::exec(&(path.to_string() + &file));
                                    },
                                    Option::None => (),
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Option::Some(arg) => FileManager::new().main(arg),
        Option::None => FileManager::new().main("file:///"),
    }
}
<commit_msg>Prevent double click on drag<commit_after>use redox::{self, env, BMPFile};
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::file::File;
use redox::io::Read;
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileManager {
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    files: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut resource = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp"));

    let mut vec: Vec<u8> = Vec::new();
    resource.read_to_end(&mut vec);

    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            folder_icon: load_icon("inode-directory"),
            audio_icon: load_icon("audio-x-wav"),
            bin_icon: load_icon("application-x-executable"),
            image_icon: load_icon("image-x-generic"),
            source_icon: load_icon("text-x-makefile"),
            script_icon: load_icon("text-x-script"),
            text_icon: load_icon("text-x-generic"),
            file_icon: load_icon("unknown"),
            files: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        for string in self.files.iter() {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            if string.ends_with('/') {
                window.image(0,
                             32 * row as isize,
                             self.folder_icon.width(),
                             self.folder_icon.height(),
                             self.folder_icon.as_slice());
            } else if string.ends_with(".wav") {
                window.image(0,
                             32 * row as isize,
                             self.audio_icon.width(),
                             self.audio_icon.height(),
                             self.audio_icon.as_slice());
            } else if string.ends_with(".bin") {
                window.image(0,
                             32 * row as isize,
                             self.bin_icon.width(),
                             self.bin_icon.height(),
                             self.bin_icon.as_slice());
            } else if string.ends_with(".bmp") {
                window.image(0,
                             32 * row as isize,
                             self.image_icon.width(),
                             self.image_icon.height(),
                             self.image_icon.as_slice());
            } else if string.ends_with(".rs") || string.ends_with(".asm") || string.ends_with(".list") {
                window.image(0,
                             32 * row as isize,
                             self.source_icon.width(),
                             self.source_icon.height(),
                             self.source_icon.as_slice());
            } else if string.ends_with(".sh") || string.ends_with(".lua") {
                window.image(0,
                             32 * row as isize,
                             self.script_icon.width(),
                             self.script_icon.height(),
                             self.script_icon.as_slice());
            } else if string.ends_with(".md") || string.ends_with(".txt") {
                window.image(0,
                             32 * row as isize,
                             self.text_icon.width(),
                             self.text_icon.height(),
                             self.text_icon.as_slice());
            } else {
                window.image(0,
                             32 * row as isize,
                             self.file_icon.width(),
                             self.file_icon.height(),
                             self.file_icon.as_slice());
            }

            let mut col = 0;
            for c in string.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }
            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        {
            let mut resource = File::open(path);

            let mut vec: Vec<u8> = Vec::new();
            resource.read_to_end(&mut vec);

            for file in unsafe { String::from_utf8_unchecked(vec) }.split('\n') {
                if width < 40 + (file.len() + 1) * 8 {
                    width = 40 + (file.len() + 1) * 8;
                }
                self.files.push(file.to_string());
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path);

        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 {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Option::Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            Option::None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

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

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                match self.files.get(self.selected as usize) {
                                    Option::Some(file) => {
                                        File::exec(&(path.to_string() + &file));
                                    },
                                    Option::None => (),
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

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


<commit_before><commit_msg>implemented popd command line options<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for #22037<commit_after>// Copyright 2015 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.

trait A {
    type Output;
    fn a(&self) -> <Self as A>::X;
//~^ ERROR: use of undeclared associated type `A::X`
}

impl A for u32 {
    type Output = u32;
    fn a(&self) -> u32 {
        0
    }
}

fn main() {
    let a: u32 = 0;
    let b: u32 = a.a();
}
<|endoftext|>


<commit_before><commit_msg>Add Vector documentation<commit_after><|endoftext|>


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

use target::Target;

pub fn target() -> Target {
    let mut base = super::android_base::opts();
    base.cpu = "pentium4".to_string();
    base.max_atomic_width = 64;

    Target {
        llvm_target: "i686-linux-android".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
        arch: "x86".to_string(),
        target_os: "android".to_string(),
        target_env: "gnu".to_string(),
        target_vendor: "unknown".to_string(),
        options: base,
    }
}
<commit_msg>Update i686-linux-android features to match android ABI.<commit_after>// Copyright 2014 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.

use target::Target;

pub fn target() -> Target {
    let mut base = super::android_base::opts();

    base.max_atomic_width = 64;

    // http://developer.android.com/ndk/guides/abis.html#x86
    base.cpu = "pentiumpro".to_string();
    base.features = "+mmx,+sse,+sse2,+sse3,+ssse3".to_string();

    Target {
        llvm_target: "i686-linux-android".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
        arch: "x86".to_string(),
        target_os: "android".to_string(),
        target_env: "gnu".to_string(),
        target_vendor: "unknown".to_string(),
        options: base,
    }
}
<|endoftext|>


<commit_before>#![cfg(all(feature = "elastictranscoder", feature = "s3"))]

extern crate env_logger;
#[macro_use]
extern crate log;
extern crate rand;
extern crate rusoto_core;
extern crate rusoto_elastictranscoder;
extern crate rusoto_s3;

use std::clone::Clone;
use std::ops::{Deref, DerefMut};

use rand::Rng;
use rusoto_core::Region;
use rusoto_elastictranscoder::{Ets, EtsClient};
use rusoto_s3::{S3, S3Client, CreateBucketRequest, DeleteBucketRequest};

const AWS_ETS_WEB_PRESET_ID: &'static str = "1351620000001-100070";
const AWS_ETS_WEB_PRESET_NAME: &'static str = "System preset: Web";
const AWS_REGION: Region = Region::UsEast1;
const AWS_SERVICE_RANDOM_SUFFIX_LENGTH: usize = 20;

struct TestEtsClient {
    region: Region,

    client: EtsClient,

    s3_client: Option<S3Client>,
    input_bucket: Option<String>,
    output_bucket: Option<String>,
}

impl TestEtsClient {
    /// Creates a new `EtsClient` for a test.
    fn new(region: Region) -> TestEtsClient {
        TestEtsClient {
            region: region.clone(),
            client: EtsClient::simple(region),
            s3_client: None,
            input_bucket: None,
            output_bucket: None,
        }
    }

    fn create_s3_client(&mut self) {
        self.s3_client = Some(S3Client::simple(self.region.clone()));
    }

    fn create_bucket(&mut self) -> String {
        let bucket_name = generate_unique_name("ets-bucket-1");

        let create_bucket_req =
            CreateBucketRequest { bucket: bucket_name.to_owned(), ..Default::default() };

        let result = self.s3_client
            .as_ref()
            .unwrap()
            .create_bucket(&create_bucket_req).sync();

        let mut location = result.unwrap()
            .location
            .unwrap();
        // A `Location` is identical to a `BucketName` except that it has a
        // forward slash prepended to it, so we need to remove it.
        location.remove(0);
        info!("Created S3 bucket: {}", location);
        location
    }
}

impl Deref for TestEtsClient {
    type Target = EtsClient;
    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

impl DerefMut for TestEtsClient {
    fn deref_mut<'a>(&'a mut self) -> &'a mut EtsClient {
        &mut self.client
    }
}

impl Drop for TestEtsClient {
    fn drop(&mut self) {
        self.s3_client.take().map(|s3_client| {
            self.input_bucket.take().map(|bucket| {

                let delete_bucket_req =
                    DeleteBucketRequest { bucket: bucket.to_owned(), ..Default::default() };

                match s3_client.delete_bucket(&delete_bucket_req).sync() {
                    Ok(_) => info!("Deleted S3 bucket: {}", bucket),
                    Err(e) => error!("Failed to delete S3 bucket: {}", e),
                };
            });
            self.output_bucket.take().map(|bucket| {

                let delete_bucket_req =
                    DeleteBucketRequest { bucket: bucket.to_owned(), ..Default::default() };

                match s3_client.delete_bucket(&delete_bucket_req).sync() {
                    Ok(_) => info!("Deleted S3 bucket: {}", bucket),
                    Err(e) => error!("Failed to delete S3 bucket: {}", e),
                };
            });
        });
    }
}

// TODO: once Rust has proper support for testing frameworks, this code will
// need to be refactored so that it is only called once, instead of per test
// case.
fn initialize() {
    let _ = env_logger::try_init();
}

fn create_client() -> TestEtsClient {
    TestEtsClient::new(AWS_REGION)
}

/// Generates a random name for an AWS service by appending a random sequence of
/// ASCII characters to the specified prefix.
fn generate_unique_name(prefix: &str) -> String {
    format!("{}-{}",
            prefix,
            rand::thread_rng()
                .gen_ascii_chars()
                .take(AWS_SERVICE_RANDOM_SUFFIX_LENGTH)
                .collect::<String>())
}

#[test]
#[should_panic(expected = "Role cannot be blank")]
fn create_pipeline_without_arn() {
    use rusoto_elastictranscoder::CreatePipelineRequest;

    initialize();

    let mut client = create_client();
    client.create_s3_client();
    client.input_bucket = Some(client.create_bucket());
    client.output_bucket = Some(client.create_bucket());

    let request = CreatePipelineRequest {
        input_bucket: client.input_bucket.as_ref().cloned().unwrap(),
        output_bucket: client.output_bucket.as_ref().cloned(),
        ..CreatePipelineRequest::default()
    };
    let response = client.create_pipeline(&request).sync();

    response.unwrap();
}

#[test]
fn create_preset() {
    use rusoto_elastictranscoder::{AudioCodecOptions, AudioParameters, CreatePresetRequest,
                                    DeletePresetRequest};

    initialize();

    let client = create_client();

    let name = generate_unique_name("ets-preset-1");
    let request = CreatePresetRequest {
        audio: Some(AudioParameters {
            channels: Some("2".to_owned()),
            codec: Some("flac".to_owned()),
            codec_options: Some(AudioCodecOptions {
                bit_depth: Some("24".to_owned()),
                ..AudioCodecOptions::default()
            }),
            sample_rate: Some("96000".to_owned()),
            ..AudioParameters::default()
        }),
        container: "flac".to_owned(),
        description: Some("This is an example FLAC preset".to_owned()),
        name: name.clone(),
        ..CreatePresetRequest::default()
    };
    let response = client.create_preset(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    assert!(response.preset.is_some());

    let preset = response.preset.unwrap();

    assert_eq!(preset.container, Some("flac".to_owned()));
    assert_eq!(preset.description,
               Some("This is an example FLAC preset".to_owned()));
    assert_eq!(preset.name, Some(name));
    assert!(preset.id.is_some());

    let id = preset.id.unwrap();

    info!("Created preset with id: {:?}", &id);

    // Cleanup

    let request = DeletePresetRequest { id: id };
    client.delete_preset(&request).sync().ok();
}

#[test]
fn delete_preset() {
    use rusoto_elastictranscoder::{AudioCodecOptions, AudioParameters, CreatePresetRequest,
                                    DeletePresetRequest};

    initialize();

    let client = create_client();

    let name = generate_unique_name("ets-preset-1");
    let request = CreatePresetRequest {
        audio: Some(AudioParameters {
            channels: Some("2".to_owned()),
            codec: Some("flac".to_owned()),
            codec_options: Some(AudioCodecOptions {
                bit_depth: Some("24".to_owned()),
                ..AudioCodecOptions::default()
            }),
            sample_rate: Some("96000".to_owned()),
            ..AudioParameters::default()
        }),
        container: "flac".to_owned(),
        description: Some("This is an example FLAC preset".to_owned()),
        name: name.clone(),
        ..CreatePresetRequest::default()
    };
    let response = client.create_preset(&request).sync().unwrap();
    let preset = response.preset.unwrap();
    let id = preset.id.unwrap();

    let request = DeletePresetRequest { id: id.clone() };
    let response = client.delete_preset(&request).sync();

    assert!(response.is_ok());
    info!("Deleted preset with id: {:?}", &id);
}

#[test]
fn list_jobs_by_status() {
    use rusoto_elastictranscoder::ListJobsByStatusRequest;

    initialize();

    let client = create_client();

    let status = "Submitted".to_owned();
    let request =
        ListJobsByStatusRequest { status: status.clone(), ..ListJobsByStatusRequest::default() };
    let response = client.list_jobs_by_status(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    info!("Got list of jobs with status \"{}\": {:?}",
          &status,
          response.jobs);
}

#[test]
fn list_pipelines() {
    use rusoto_elastictranscoder::ListPipelinesRequest;

    initialize();

    let client = create_client();

    let request = ListPipelinesRequest::default();
    let response = client.list_pipelines(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    info!("Got list of pipelines: {:?}", response.pipelines);
}

#[test]
fn list_presets() {
    use rusoto_elastictranscoder::ListPresetsRequest;

    initialize();

    let client = create_client();

    let request = ListPresetsRequest::default();
    let response = client.list_presets(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    assert!(response.presets.is_some());

    let presets = response.presets.unwrap();
    info!("Got list of presets.");
    for preset in presets.iter() {
        info!("Preset: {:?}", preset.name);
    }

    let web_preset = presets.iter()
        .filter(|x| x.id == Some(AWS_ETS_WEB_PRESET_ID.to_owned()))
        .next();

    assert!(web_preset.is_some());

    let web_preset = web_preset.unwrap();

    assert_eq!(web_preset.id, Some(AWS_ETS_WEB_PRESET_ID.to_owned()));
    assert_eq!(web_preset.name, Some(AWS_ETS_WEB_PRESET_NAME.to_owned()));
}

#[test]
fn read_preset() {
    use rusoto_elastictranscoder::ReadPresetRequest;

    initialize();

    let client = create_client();

    let request = ReadPresetRequest { id: AWS_ETS_WEB_PRESET_ID.to_owned() };
    let response = client.read_preset(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    assert!(response.preset.is_some());

    let preset = response.preset.unwrap();
    info!("Got preset: {:?}", preset.name);

    assert_eq!(preset.id, Some(AWS_ETS_WEB_PRESET_ID.to_owned()));
    assert_eq!(preset.name, Some(AWS_ETS_WEB_PRESET_NAME.to_owned()));
}
<commit_msg>Fix elastictranscoder test by complying with new S3 standards.<commit_after>#![cfg(all(feature = "elastictranscoder", feature = "s3"))]

extern crate env_logger;
#[macro_use]
extern crate log;
extern crate rand;
extern crate rusoto_core;
extern crate rusoto_elastictranscoder;
extern crate rusoto_s3;

use std::clone::Clone;
use std::ops::{Deref, DerefMut};

use rand::Rng;
use rusoto_core::Region;
use rusoto_elastictranscoder::{Ets, EtsClient};
use rusoto_s3::{S3, S3Client, CreateBucketRequest, DeleteBucketRequest};

const AWS_ETS_WEB_PRESET_ID: &'static str = "1351620000001-100070";
const AWS_ETS_WEB_PRESET_NAME: &'static str = "System preset: Web";
const AWS_REGION: Region = Region::UsEast1;
const AWS_SERVICE_RANDOM_SUFFIX_LENGTH: usize = 20;

struct TestEtsClient {
    region: Region,

    client: EtsClient,

    s3_client: Option<S3Client>,
    input_bucket: Option<String>,
    output_bucket: Option<String>,
}

impl TestEtsClient {
    /// Creates a new `EtsClient` for a test.
    fn new(region: Region) -> TestEtsClient {
        TestEtsClient {
            region: region.clone(),
            client: EtsClient::simple(region),
            s3_client: None,
            input_bucket: None,
            output_bucket: None,
        }
    }

    fn create_s3_client(&mut self) {
        self.s3_client = Some(S3Client::simple(self.region.clone()));
    }

    fn create_bucket(&mut self) -> String {
        let bucket_name = generate_unique_name("ets-bucket-1");

        let create_bucket_req =
            CreateBucketRequest { bucket: bucket_name.to_owned(), ..Default::default() };

        let result = self.s3_client
            .as_ref()
            .unwrap()
            .create_bucket(&create_bucket_req).sync();

        let mut location = result.unwrap()
            .location
            .unwrap();
        // A `Location` is identical to a `BucketName` except that it has a
        // forward slash prepended to it, so we need to remove it.
        location.remove(0);
        info!("Created S3 bucket: {}", location);
        location
    }
}

impl Deref for TestEtsClient {
    type Target = EtsClient;
    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

impl DerefMut for TestEtsClient {
    fn deref_mut<'a>(&'a mut self) -> &'a mut EtsClient {
        &mut self.client
    }
}

impl Drop for TestEtsClient {
    fn drop(&mut self) {
        self.s3_client.take().map(|s3_client| {
            self.input_bucket.take().map(|bucket| {

                let delete_bucket_req =
                    DeleteBucketRequest { bucket: bucket.to_owned(), ..Default::default() };

                match s3_client.delete_bucket(&delete_bucket_req).sync() {
                    Ok(_) => info!("Deleted S3 bucket: {}", bucket),
                    Err(e) => error!("Failed to delete S3 bucket: {}", e),
                };
            });
            self.output_bucket.take().map(|bucket| {

                let delete_bucket_req =
                    DeleteBucketRequest { bucket: bucket.to_owned(), ..Default::default() };

                match s3_client.delete_bucket(&delete_bucket_req).sync() {
                    Ok(_) => info!("Deleted S3 bucket: {}", bucket),
                    Err(e) => error!("Failed to delete S3 bucket: {}", e),
                };
            });
        });
    }
}

// TODO: once Rust has proper support for testing frameworks, this code will
// need to be refactored so that it is only called once, instead of per test
// case.
fn initialize() {
    let _ = env_logger::try_init();
}

fn create_client() -> TestEtsClient {
    TestEtsClient::new(AWS_REGION)
}

/// Generates a random name for an AWS service by appending a random sequence of
/// ASCII characters to the specified prefix.
/// Keeps it lower case to work with S3 requirements as of 3/1/2018.
fn generate_unique_name(prefix: &str) -> String {
    format!("{}-{}",
            prefix,
            rand::thread_rng()
                .gen_ascii_chars()
                .take(AWS_SERVICE_RANDOM_SUFFIX_LENGTH)
                .collect::<String>())
    .to_lowercase()
}

#[test]
#[should_panic(expected = "Role cannot be blank")]
fn create_pipeline_without_arn() {
    use rusoto_elastictranscoder::CreatePipelineRequest;

    initialize();

    let mut client = create_client();
    client.create_s3_client();
    client.input_bucket = Some(client.create_bucket());
    client.output_bucket = Some(client.create_bucket());

    let request = CreatePipelineRequest {
        input_bucket: client.input_bucket.as_ref().cloned().unwrap(),
        output_bucket: client.output_bucket.as_ref().cloned(),
        ..CreatePipelineRequest::default()
    };
    let response = client.create_pipeline(&request).sync();

    response.unwrap();
}

#[test]
fn create_preset() {
    use rusoto_elastictranscoder::{AudioCodecOptions, AudioParameters, CreatePresetRequest,
                                    DeletePresetRequest};

    initialize();

    let client = create_client();

    let name = generate_unique_name("ets-preset-1");
    let request = CreatePresetRequest {
        audio: Some(AudioParameters {
            channels: Some("2".to_owned()),
            codec: Some("flac".to_owned()),
            codec_options: Some(AudioCodecOptions {
                bit_depth: Some("24".to_owned()),
                ..AudioCodecOptions::default()
            }),
            sample_rate: Some("96000".to_owned()),
            ..AudioParameters::default()
        }),
        container: "flac".to_owned(),
        description: Some("This is an example FLAC preset".to_owned()),
        name: name.clone(),
        ..CreatePresetRequest::default()
    };
    let response = client.create_preset(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    assert!(response.preset.is_some());

    let preset = response.preset.unwrap();

    assert_eq!(preset.container, Some("flac".to_owned()));
    assert_eq!(preset.description,
               Some("This is an example FLAC preset".to_owned()));
    assert_eq!(preset.name, Some(name));
    assert!(preset.id.is_some());

    let id = preset.id.unwrap();

    info!("Created preset with id: {:?}", &id);

    // Cleanup

    let request = DeletePresetRequest { id: id };
    client.delete_preset(&request).sync().ok();
}

#[test]
fn delete_preset() {
    use rusoto_elastictranscoder::{AudioCodecOptions, AudioParameters, CreatePresetRequest,
                                    DeletePresetRequest};

    initialize();

    let client = create_client();

    let name = generate_unique_name("ets-preset-1");
    let request = CreatePresetRequest {
        audio: Some(AudioParameters {
            channels: Some("2".to_owned()),
            codec: Some("flac".to_owned()),
            codec_options: Some(AudioCodecOptions {
                bit_depth: Some("24".to_owned()),
                ..AudioCodecOptions::default()
            }),
            sample_rate: Some("96000".to_owned()),
            ..AudioParameters::default()
        }),
        container: "flac".to_owned(),
        description: Some("This is an example FLAC preset".to_owned()),
        name: name.clone(),
        ..CreatePresetRequest::default()
    };
    let response = client.create_preset(&request).sync().unwrap();
    let preset = response.preset.unwrap();
    let id = preset.id.unwrap();

    let request = DeletePresetRequest { id: id.clone() };
    let response = client.delete_preset(&request).sync();

    assert!(response.is_ok());
    info!("Deleted preset with id: {:?}", &id);
}

#[test]
fn list_jobs_by_status() {
    use rusoto_elastictranscoder::ListJobsByStatusRequest;

    initialize();

    let client = create_client();

    let status = "Submitted".to_owned();
    let request =
        ListJobsByStatusRequest { status: status.clone(), ..ListJobsByStatusRequest::default() };
    let response = client.list_jobs_by_status(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    info!("Got list of jobs with status \"{}\": {:?}",
          &status,
          response.jobs);
}

#[test]
fn list_pipelines() {
    use rusoto_elastictranscoder::ListPipelinesRequest;

    initialize();

    let client = create_client();

    let request = ListPipelinesRequest::default();
    let response = client.list_pipelines(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    info!("Got list of pipelines: {:?}", response.pipelines);
}

#[test]
fn list_presets() {
    use rusoto_elastictranscoder::ListPresetsRequest;

    initialize();

    let client = create_client();

    let request = ListPresetsRequest::default();
    let response = client.list_presets(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    assert!(response.presets.is_some());

    let presets = response.presets.unwrap();
    info!("Got list of presets.");
    for preset in presets.iter() {
        info!("Preset: {:?}", preset.name);
    }

    let web_preset = presets.iter()
        .filter(|x| x.id == Some(AWS_ETS_WEB_PRESET_ID.to_owned()))
        .next();

    assert!(web_preset.is_some());

    let web_preset = web_preset.unwrap();

    assert_eq!(web_preset.id, Some(AWS_ETS_WEB_PRESET_ID.to_owned()));
    assert_eq!(web_preset.name, Some(AWS_ETS_WEB_PRESET_NAME.to_owned()));
}

#[test]
fn read_preset() {
    use rusoto_elastictranscoder::ReadPresetRequest;

    initialize();

    let client = create_client();

    let request = ReadPresetRequest { id: AWS_ETS_WEB_PRESET_ID.to_owned() };
    let response = client.read_preset(&request).sync();

    assert!(response.is_ok());

    let response = response.unwrap();

    assert!(response.preset.is_some());

    let preset = response.preset.unwrap();
    info!("Got preset: {:?}", preset.name);

    assert_eq!(preset.id, Some(AWS_ETS_WEB_PRESET_ID.to_owned()));
    assert_eq!(preset.name, Some(AWS_ETS_WEB_PRESET_NAME.to_owned()));
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1348<commit_after>// https://leetcode.com/problems/tweet-counts-per-frequency/
struct TweetCounts {}

impl TweetCounts {
    fn new() -> Self {
        todo!()
    }

    fn record_tweet(&mut self, tweet_name: String, time: i32) {
        todo!()
    }

    fn get_tweet_counts_per_frequency(
        &self,
        freq: String,
        tweet_name: String,
        start_time: i32,
        end_time: i32,
    ) -> Vec<i32> {
        todo!()
    }
}

fn main() {
    let mut tweet_counts = TweetCounts::new();
    tweet_counts.record_tweet("tweet3".to_string(), 0);
    tweet_counts.record_tweet("tweet3".to_string(), 60);
    tweet_counts.record_tweet("tweet3".to_string(), 10);
    tweet_counts.get_tweet_counts_per_frequency("minute".to_string(), "tweet3".to_string(), 0, 59); // [2]
    tweet_counts.get_tweet_counts_per_frequency("minute".to_string(), "tweet3".to_string(), 0, 60); // [2,1]
    tweet_counts.record_tweet("tweet3".to_string(), 120);
    tweet_counts.get_tweet_counts_per_frequency("hour".to_string(), "tweet3".to_string(), 0, 210);
    // [4]
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1526<commit_after>// https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/
pub fn min_number_operations(target: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", min_number_operations(vec![1, 2, 3, 2, 1])); // 3
    println!("{}", min_number_operations(vec![3, 1, 1, 2])); // 4
    println!("{}", min_number_operations(vec![3, 1, 5, 4, 2])); // 7
}
<|endoftext|>


<commit_before><commit_msg>Quadruple the kernel heap size<commit_after><|endoftext|>


<commit_before><commit_msg>ICH: Add test case for InlineAsm hashes.<commit_after>// Copyright 2016 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.

// This test case tests the incremental compilation hash (ICH) implementation
// for inline asm.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![feature(asm)]
#![crate_type="rlib"]

// Change template -------------------------------------------------------------
#[cfg(cfail1)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_template(a: i32) -> i32 {
    let c: i32;
    unsafe {
        asm!("add 1, $0"
             : "=r"(c)
             : "0"(a)
             :
             :
             );
    }
    c
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_template(a: i32) -> i32 {
    let c: i32;
    unsafe {
        asm!("add 2, $0"
             : "=r"(c)
             : "0"(a)
             :
             :
             );
    }
    c
}

// Change output -------------------------------------------------------------
#[cfg(cfail1)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_output(a: i32) -> i32 {
    let mut _out1: i32 = 0;
    let mut _out2: i32 = 0;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out1)
             : "0"(a)
             :
             :
             );
    }
    _out1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_output(a: i32) -> i32 {
    let mut _out1: i32 = 0;
    let mut _out2: i32 = 0;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out2)
             : "0"(a)
             :
             :
             );
    }
    _out1
}

// Change input -------------------------------------------------------------
#[cfg(cfail1)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_input(_a: i32, _b: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_a)
             :
             :
             );
    }
    _out
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_input(_a: i32, _b: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_b)
             :
             :
             );
    }
    _out
}

// Change input constraint -----------------------------------------------------
#[cfg(cfail1)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_input_constraint(_a: i32, _b: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_a), "r"(_b)
             :
             :
             );
    }
    _out
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_input_constraint(_a: i32, _b: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "r"(_a), "0"(_b)
             :
             :
             );
    }
    _out
}

// Change clobber --------------------------------------------------------------
#[cfg(cfail1)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_clobber(_a: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_a)
             :
             :
             );
    }
    _out
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_clobber(_a: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_a)
             : "eax"
             :
             );
    }
    _out
}

// Change options --------------------------------------------------------------
#[cfg(cfail1)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_options(_a: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_a)
             :
             :
             );
    }
    _out
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn change_options(_a: i32) -> i32 {
    let _out;
    unsafe {
        asm!("add 1, $0"
             : "=r"(_out)
             : "0"(_a)
             :
             : "volatile"
             );
    }
    _out
}

<|endoftext|>


<commit_before><commit_msg>dom: Unindent Document::set_activity.<commit_after><|endoftext|>


<commit_before><commit_msg>Regression test for #17728<commit_after>// Copyright 2014 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.

use std::fmt::{Show, Formatter, Error};
use std::collections::HashMap;

trait HasInventory {
    fn getInventory<'s>(&'s self) -> &'s mut Inventory;
    fn addToInventory(&self, item: &Item);
    fn removeFromInventory(&self, itemName: &str) -> bool;
}

trait TraversesWorld {
    fn attemptTraverse(&self, room: &Room, directionStr: &str) -> Result<&Room, &str> {
        let direction = str_to_direction(directionStr);
        let maybe_room = room.direction_to_room.find(&direction);
        //~^ ERROR cannot infer an appropriate lifetime for autoref due to conflicting requirements
        match maybe_room {
            Some(entry) => Ok(entry),
            _ => Err("Direction does not exist in room.")
        }
    }
}

#[deriving(Show, Eq, PartialEq, Hash)]
enum RoomDirection {
    West,
    East,
    North,
    South,
    Up,
    Down,
    In,
    Out,

    None
}

struct Room {
    description: String,
    items: Vec<Item>,
    direction_to_room: HashMap<RoomDirection, Room>,
}

impl Room {
    fn new(description: &'static str) -> Room {
        Room {
            description: description.to_string(),
            items: Vec::new(),
            direction_to_room: HashMap::new()
        }
    }

    fn add_direction(&mut self, direction: RoomDirection, room: Room) {
        self.direction_to_room.insert(direction, room);
    }
}

struct Item {
    name: String,
}

struct Inventory {
    items: Vec<Item>,
}

impl Inventory {
    fn new() -> Inventory {
        Inventory {
            items: Vec::new()
        }
    }
}

struct Player {
    name: String,
    inventory: Inventory,
}

impl Player {
    fn new(name: &'static str) -> Player {
        Player {
            name: name.to_string(),
            inventory: Inventory::new()
        }
    }
}

impl TraversesWorld for Player {
}

impl Show for Player {
    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
        formatter.write_str("Player{ name:");
        formatter.write_str(self.name.as_slice());
        formatter.write_str(" }");
        Ok(())
    }
}

fn str_to_direction(to_parse: &str) -> RoomDirection {
    match to_parse {
        "w" | "west" => RoomDirection::West,
        "e" | "east" => RoomDirection::East,
        "n" | "north" => RoomDirection::North,
        "s" | "south" => RoomDirection::South,
        "in" => RoomDirection::In,
        "out" => RoomDirection::Out,
        "up" => RoomDirection::Up,
        "down" => RoomDirection::Down,
        _ => None //~ ERROR mismatched types
    }
}

fn main() {
    let mut player = Player::new("Test player");
    let mut room = Room::new("A test room");
    println!("Made a player: {}", player);
    println!("Direction parse: {}", str_to_direction("east"));
    match player.attemptTraverse(&room, "west") {
        Ok(_) => println!("Was able to move west"),
        Err(msg) => println!("Not able to move west: {}", msg)
    };
}
<|endoftext|>


<commit_before><commit_msg>simple std io<commit_after>// Accept value from standard input.

use std::io; // imports io library from standard library

fn main() {
    let mut val = String::new(); //creates new, empty  String

    io::stdin().read_line(&mut val)
             .ok()
             .expect("Failed to read value");

    println!("Entered value is: {} ",val);
}
<|endoftext|>


<commit_before><commit_msg>02 - formatted print<commit_after>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31i);
    // The `i` suffix indicates the compiler that this literal has type: signed
    // pointer size integer, see next chapter for more details

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:t} people know binary, the other half don't", 1i, 2i);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond", "James");
}
<|endoftext|>


<commit_before><commit_msg>Add example/examples.rs<commit_after>extern crate bluetooth_serial_port;
extern crate mio;
use bluetooth_serial_port::{BtProtocol, BtSocket};
use std::io::{Read, Write};
use mio::{Poll, PollOpt, Token, Ready};

fn main() {
    // scan for devices
    let devices = bluetooth_serial_port::scan_devices().unwrap();
    if devices.len() == 0 { panic!("No devices found"); }

    // "device.addr" is the MAC address of the device
    let device = &devices[0];
    println!("Connecting to `{}` ({})", device.name, device.addr.to_string());

    // create and connect the RFCOMM socket
    let mut socket = BtSocket::new(BtProtocol::RFCOMM).unwrap();
    socket.connect(device.addr).unwrap();

    // BtSocket implements the `Read` and `Write` traits (they're blocking)
    let mut buffer = [0; 10];
    let num_bytes_read = socket.read(&mut buffer[..]).unwrap();
    let num_bytes_written = socket.write(&buffer[0..num_bytes_read]).unwrap();
    println!("Read `{}` bytes, wrote `{}` bytes", num_bytes_read, num_bytes_written);

    // BtSocket also implements `mio::Evented` for async IO
    let poll = Poll::new().unwrap();
    poll.register(&socket, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge() | PollOpt::oneshot()).unwrap();
    // loop { ... poll events and wait for socket to be readable/writable ... }
}
<|endoftext|>


<commit_before><commit_msg>Add problem #11<commit_after>use std;

fn find_max_row(row: [uint], prod_len: uint) -> uint {
    if vec::len(row) < prod_len {
        ret 0u;
    }
    let max = 0u;
    uint::range(0u, vec::len(row) - prod_len) { |i|
        let prod = 1u;
        uint::range(0u, prod_len) { |j|
            prod *= row[i + j];
        }
        max = uint::max(max, prod);
    }
    ret max;
}

fn find_max_grid(grid: [[uint]], prod_len: uint) -> uint {
    vec::foldl(0u, grid) { |max, row|
        uint::max(max, find_max_row(row, prod_len))
    }
}

fn find_max_v(grid: [[uint]], prod_len: uint) -> uint {
    if vec::is_empty(grid) {
        ret 0u;
    }

    let max = 0u;
    uint::range(0u, vec::len(grid[0])) { |i|
        max = uint::max(max, find_max_row(vec::map(grid) { |row| row[i] }, prod_len));
    }
    ret max;
}

fn find_max_d(grid: [[uint]], prod_len: uint) -> uint {
    if vec::is_empty(grid) {
        ret 0u;
    }
    let num_row = vec::len(grid);
    let num_col = vec::len(grid[0]);
    let max = 0u;
    int::range(-(num_row as int) + 1, num_col as int) { |i|
        let tl_br = vec::filter_map(vec::enum_uints(0u, uint::min(num_row, num_col) - 1u)) { |d|
            let (x, y) = (i + (d as int), d);
            if x < 0 || x as uint >= num_col || y >= num_row {
                ret none;
            }
            ret some(grid[y][x]);
        };
        max = uint::max(max, find_max_row(tl_br, prod_len));

        let bl_tr = vec::filter_map(vec::enum_uints(0u, uint::min(num_row, num_col) - 1u)) { |d|
            let (x, y) = (d, (num_col as int - 1 - i) - (d as int));
            if x >= num_col || y < 0 || y as uint >= num_row {
                ret none;
            }
            ret some(grid[y][x]);
        };
        max = uint::max(max, find_max_row(bl_tr, prod_len));
    }
    ret max;
}

fn main() {
    let input = "
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
";

    let grid = vec::map(str::lines(str::trim(input))) { |row|
        vec::map(str::split_char(row, ' ')) { |cell|
            alt uint::from_str(cell) {
              some(x) { x }
              none    { fail }
            }
        }
    };
    let max = find_max_grid(grid, 4u);
    max = uint::max(max, find_max_v(grid, 4u));
    max = uint::max(max, find_max_d(grid, 4u));
    std::io::println(#fmt("%u", max));
}
<|endoftext|>


<commit_before><commit_msg>Add problem #41<commit_after>extern mod euler;
use euler::calc::{ permutate_num };
use euler::prime::{ Prime };

fn main() {
    let ps = Prime();
    for permutate_num(&[7, 6, 5, 4, 3, 2, 1], 7, 0, 9999999) |num, _rest| {
        if ps.is_prime(num) {
            io::println(fmt!("answer: %u", num));
            break;
        }
    }
}
<|endoftext|>


<commit_before>use programs::common::*;

pub struct Application {
    output: String,
    scroll: Point,
    wrap: bool
}

impl SessionItem for Application {
    fn main(&mut self, url: URL){
        let mut window = Window::new(Point::new((rand() % 400 + 50) as isize, (rand() % 300 + 50) as isize), Size::new(576, 400), "HTTP Server".to_string());

        macro_rules! println {
            ($text:expr) => ({
                self.output.vec.push_all(&$text.vec);
                self.output.vec.push('\n');
                self.draw_content(&mut window);
            });
        }

        println!("Starting HTTP Server".to_string());

        loop {
            let mut resource = URL::from_string(&"tcp:///80".to_string()).open();
            match resource.stat(){
                ResourceType::File => {
                    println!("Incoming stream from ".to_string() + resource.url().to_string());

                    let mut data: Vec<u8> = Vec::new();
                    resource.read_to_end(&mut data);
                    println!(String::from_utf8(&data));
                    resource.write("Test".to_string().to_utf8().as_slice());
                },
                _ => ()
            }

            match window.poll() {
                EventOption::Key(key_event) => {
                    if key_event.pressed{
                        if key_event.scancode == 1 {
                            break;
                        }
                    }
                },
                EventOption::None => sys_yield(),
                _ => ()
            }
        }

        println!("Closed HTTP Server".to_string());

        loop {
            match window.poll() {
                EventOption::Key(key_event) => {
                    if key_event.pressed{
                        if key_event.scancode == 1 {
                            break;
                        }
                    }
                },
                EventOption::None => sys_yield(),
                _ => ()
            }
        }
    }
}

impl Application {
    pub fn new() -> Application {
        return Application {
            output: String::new(),
            scroll: Point::new(0, 0),
            wrap: true
        };
    }

    fn draw_content(&mut self, window: &mut Window){
        let scroll = self.scroll;

        let mut col = -scroll.x;
        let cols = window.content.width as isize / 8;
        let mut row = -scroll.y;
        let rows = window.content.height as isize / 16;

        {
            let content = &window.content;
            content.set(Color::new(0, 0, 0));

            for c in self.output.chars(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                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{
                        content.char(Point::new(8 * col, 16 * row), c, Color::new(224, 224, 224));
                    }
                    col += 1;
                }
            }

            if col > -scroll.x {
                col = -scroll.x;
                row += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll.x;
                row += 1;
            }

            content.flip();

            RedrawEvent {
                redraw: REDRAW_ALL
            }.to_event().trigger();
        }

        if row >= rows {
            self.scroll.y += row - rows + 1;

            self.draw_content(window);
        }
    }
}
<commit_msg>Add http response headers<commit_after>use programs::common::*;

pub struct Application {
    output: String,
    scroll: Point,
    wrap: bool
}

impl SessionItem for Application {
    fn main(&mut self, url: URL){
        let mut window = Window::new(Point::new((rand() % 400 + 50) as isize, (rand() % 300 + 50) as isize), Size::new(576, 400), "HTTP Server".to_string());

        macro_rules! println {
            ($text:expr) => ({
                self.output.vec.push_all(&$text.vec);
                self.output.vec.push('\n');
                self.draw_content(&mut window);
            });
        }

        println!("Starting HTTP Server".to_string());

        let html = "Test".to_string().to_utf8();

        let mut response = ("HTTP/1.1 200 OK\r\n".to_string()
                + "Content-Type: text/html; charset=UTF-8\r\n"
                + "Content-Length: " + html.len() + "\r\n"
                + "Connection: Close\r\n"
                + "\r\n").to_utf8();
        response.push_all(&html);

        loop {
            {
                let mut resource = URL::from_string(&"tcp:///80".to_string()).open();
                match resource.stat(){
                    ResourceType::File => {
                        println!("Incoming stream from ".to_string() + resource.url().to_string());

                        let mut data: Vec<u8> = Vec::new();
                        resource.read_to_end(&mut data);
                        println!(String::from_utf8(&data));
                        resource.write(response.as_slice());
                    },
                    _ => ()
                }
            }

            match window.poll() {
                EventOption::Key(key_event) => {
                    if key_event.pressed{
                        if key_event.scancode == 1 {
                            break;
                        }
                    }
                },
                EventOption::None => sys_yield(),
                _ => ()
            }
        }

        println!("Closed HTTP Server".to_string());

        loop {
            match window.poll() {
                EventOption::Key(key_event) => {
                    if key_event.pressed{
                        if key_event.scancode == 1 {
                            break;
                        }
                    }
                },
                EventOption::None => sys_yield(),
                _ => ()
            }
        }
    }
}

impl Application {
    pub fn new() -> Application {
        return Application {
            output: String::new(),
            scroll: Point::new(0, 0),
            wrap: true
        };
    }

    fn draw_content(&mut self, window: &mut Window){
        let scroll = self.scroll;

        let mut col = -scroll.x;
        let cols = window.content.width as isize / 8;
        let mut row = -scroll.y;
        let rows = window.content.height as isize / 16;

        {
            let content = &window.content;
            content.set(Color::new(0, 0, 0));

            for c in self.output.chars(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                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{
                        content.char(Point::new(8 * col, 16 * row), c, Color::new(224, 224, 224));
                    }
                    col += 1;
                }
            }

            if col > -scroll.x {
                col = -scroll.x;
                row += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll.x;
                row += 1;
            }

            content.flip();

            RedrawEvent {
                redraw: REDRAW_ALL
            }.to_event().trigger();
        }

        if row >= rows {
            self.scroll.y += row - rows + 1;

            self.draw_content(window);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>:green_heart: Add the test of private method<commit_after><|endoftext|>