text:
# A0142255M
###### \java\seedu\tache\commons\events\storage\DataFileLocationChangedEvent.java
``` java

package seedu.tache.commons.events.storage;

import seedu.tache.commons.events.BaseEvent;

/**
 * Indicates that the directory of the data file has been changed.
 */
public class DataFileLocationChangedEvent extends BaseEvent {

    public String newLocation;

    public DataFileLocationChangedEvent(String newLocation) {
        assert newLocation != null;
        this.newLocation = newLocation;
    }

    @Override
    public String toString() {
        return newLocation;
    }

}
```
###### \java\seedu\tache\commons\events\ui\CalendarNextRequestEvent.java
``` java
package seedu.tache.commons.events.ui;

import seedu.tache.commons.events.BaseEvent;

/**
 * Indicates a request to view the next day / week / month at the calendar.
 */
public class CalendarNextRequestEvent extends BaseEvent {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
```
###### \java\seedu\tache\commons\events\ui\CalendarPreviousRequestEvent.java
``` java
package seedu.tache.commons.events.ui;

import seedu.tache.commons.events.BaseEvent;

/**
 * Indicates a request to view the previous day / week / month at the calendar.
 */
public class CalendarPreviousRequestEvent extends BaseEvent {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
```
###### \java\seedu\tache\commons\events\ui\CalendarViewRequestEvent.java
``` java
package seedu.tache.commons.events.ui;

import seedu.tache.commons.events.BaseEvent;

/**
 * Indicates a request to view events at the calendar in a day / week / month view.
 */
public class CalendarViewRequestEvent extends BaseEvent {

    public final String view;

    public CalendarViewRequestEvent(String view) {
        this.view = view;
    }

    public String getView() {
        return view;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
```
###### \java\seedu\tache\commons\events\ui\FilteredTaskListUpdatedEvent.java
``` java
package seedu.tache.commons.events.ui;

import javafx.collections.ObservableList;
import seedu.tache.commons.events.BaseEvent;
import seedu.tache.model.task.ReadOnlyTask;

/**
 * Indicates that the filtered list is changed.
 * For example, the user types "list completed" to show all completed tasks only.
 */
public class FilteredTaskListUpdatedEvent extends BaseEvent {

    public final ObservableList<ReadOnlyTask> filteredTaskList;

    public FilteredTaskListUpdatedEvent(ObservableList<ReadOnlyTask> filteredTaskList) {
        this.filteredTaskList = filteredTaskList;
    }

    public ObservableList<ReadOnlyTask> getFilteredTaskList() {
        return filteredTaskList;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }

}
```
###### \java\seedu\tache\commons\events\ui\TaskListTypeChangedEvent.java
``` java
package seedu.tache.commons.events.ui;

import seedu.tache.commons.events.BaseEvent;

/**
 * Indicates that the task list type is changed.
 */
public class TaskListTypeChangedEvent extends BaseEvent {

    public final String newTaskListType;

    public TaskListTypeChangedEvent(String newTaskListType) {
        this.newTaskListType = newTaskListType;
    }

    public String getTaskListType() {
        return newTaskListType;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }

}
```
###### \java\seedu\tache\logic\commands\FindCommand.java
``` java
    @Override
    public CommandResult execute() {
        model.updateFilteredTaskList(keywords);
        return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
    }

}
```
###### \java\seedu\tache\logic\commands\HelpCommand.java
``` java
    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows usage instructions of specific commands. "
            + "Help window will be displayed if no command is specified.\n"
            + "Parameters (Optional): add, clear, complete, delete, edit etc.\n"
            + "Example: " + COMMAND_WORD + " add";
```
###### \java\seedu\tache\logic\commands\NextCommand.java
``` java

package seedu.tache.logic.commands;

import seedu.tache.commons.core.EventsCenter;
import seedu.tache.commons.events.ui.CalendarNextRequestEvent;

/**
 * Displays the next day / week/ month at the calendar.
 */
public class NextCommand extends Command {

    public static final String COMMAND_WORD = "next";
    public static final String SHORT_COMMAND_WORD = "n";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ":Displays the next day/week/month at the calendar.\n"
            + "Example: " + COMMAND_WORD;

    public static final String MESSAGE_SUCCESS = "Next day/week/month displayed at the calendar.";

    @Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new CalendarNextRequestEvent());
        return new CommandResult(MESSAGE_SUCCESS);
    }

}

```
###### \java\seedu\tache\logic\commands\PrevCommand.java
``` java

package seedu.tache.logic.commands;

import seedu.tache.commons.core.EventsCenter;
import seedu.tache.commons.events.ui.CalendarPreviousRequestEvent;

/**
 * Displays the previous day / week/ month at the calendar.
 */
public class PrevCommand extends Command {

    public static final String COMMAND_WORD = "prev";
    public static final String SHORT_COMMAND_WORD = "p";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ":Displays the previous day/week/month at the calendar.\n"
            + "Example: " + COMMAND_WORD;

    public static final String MESSAGE_SUCCESS = "Previous day/week/month displayed at the calendar.";

    @Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new CalendarPreviousRequestEvent());
        return new CommandResult(MESSAGE_SUCCESS);
    }

}

```
###### \java\seedu\tache\logic\commands\ViewCommand.java
``` java

package seedu.tache.logic.commands;

import seedu.tache.commons.core.EventsCenter;
import seedu.tache.commons.events.ui.CalendarViewRequestEvent;

/**
 * Shows events (timed tasks) in the calendar in a day / week / month view.
 */
public class ViewCommand extends Command {

    public static final String COMMAND_WORD = "view";
    public static final String SHORT_COMMAND_WORD = "v";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ":Navigates calendar to a day / week / month view.\n"
            + "Example: " + COMMAND_WORD + "week";

    public static final String MESSAGE_SUCCESS = "Calendar view switched to %s view.";

    private String view;

    public ViewCommand(String view) {
        assert view != null;
        this.view = view;
    }

    @Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new CalendarViewRequestEvent(view));
        return new CommandResult(String.format(MESSAGE_SUCCESS, view));
    }

}

```
###### \java\seedu\tache\logic\Logic.java
``` java
    /**
     * Returns type of filtered task list in a String
     */
    String getFilteredTaskListType();
}
```
###### \java\seedu\tache\logic\LogicManager.java
``` java
    @Override
    public String getFilteredTaskListType() {
        return model.getFilteredTaskListType();
    }

}
```
###### \java\seedu\tache\logic\parser\CliSyntax.java
``` java
    public static final String FILTER_TIMED = "timed";
    public static final String FILTER_FLOATING = "floating";
```
###### \java\seedu\tache\logic\parser\CliSyntax.java
``` java
    /* Calendar show view options */
    public static final String VIEW_DAY = "day";
    public static final String VIEW_WEEK = "week";
    public static final String VIEW_MONTH = "month";
```
###### \java\seedu\tache\logic\parser\ViewCommandParser.java
``` java
package seedu.tache.logic.parser;

import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.tache.logic.parser.CliSyntax.VIEW_DAY;
import static seedu.tache.logic.parser.CliSyntax.VIEW_MONTH;
import static seedu.tache.logic.parser.CliSyntax.VIEW_WEEK;

import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.IncorrectCommand;
import seedu.tache.logic.commands.ViewCommand;

/**
 * Parses input arguments and creates a new ViewCommand object
 */
public class ViewCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the ViewCommand
     * and returns a ViewCommand object for execution.
     */
    public Command parse(String args) {
        String trimmedArgs = args.trim();
        if (!trimmedArgs.equals("")) {
            switch(trimmedArgs) {
            case VIEW_DAY:
            case VIEW_WEEK:
            case VIEW_MONTH:
                return new ViewCommand(trimmedArgs);
            default:
                return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ViewCommand.MESSAGE_USAGE));
            }
        } else {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ViewCommand.MESSAGE_USAGE));
        }
    }

}
```
###### \java\seedu\tache\model\Model.java
``` java
    /** Updates the filter of the filtered task list to show all timed tasks */
    void updateFilteredListToShowTimed();

```
###### \java\seedu\tache\model\ModelManager.java
``` java
    public static final String TASK_LIST_TYPE_ALL = "All Tasks";
    public static final String TASK_LIST_TYPE_COMPLETED = "Completed Tasks";
    public static final String TASK_LIST_TYPE_UNCOMPLETED = "Uncompleted Tasks";
    public static final String TASK_LIST_TYPE_TIMED = "Timed Tasks";
    public static final String TASK_LIST_TYPE_FLOATING = "Floating Tasks";
```
###### \java\seedu\tache\model\ModelManager.java
``` java
    private String filteredTaskListType = TASK_LIST_TYPE_ALL;
```
###### \java\seedu\tache\model\ModelManager.java
``` java
    @Override
    public void resetData(ReadOnlyTaskManager newData) {
        assert newData != null;
        taskManager.resetData(newData);
        updateFilteredListToShowAll();
        updateFilteredTaskListType(TASK_LIST_TYPE_ALL);
        indicateTaskManagerChanged();
    }
```
###### \java\seedu\tache\model\ModelManager.java
``` java
    /**
     * Raises events to indicate that the model has changed.
     */
    private void indicateTaskManagerChanged() {
        raise(new TaskManagerChangedEvent(taskManager));
        raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
        raise(new PopulateRecurringGhostTaskEvent(getAllRecurringGhostTasks()));
    }
```
###### \java\seedu\tache\model\ModelManager.java
``` java
    @Override
    public synchronized void addTask(Task task) throws DuplicateTaskException {
        assert task != null;
        taskManager.addTask(task);
        indicateTaskManagerChanged();
    }

```
###### \java\seedu\tache\model\ModelManager.java
``` java
    @Override
    public void updateFilteredListToShowAll() {
        filteredTasks.setPredicate(null);
        raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
        updateFilteredTaskListType(TASK_LIST_TYPE_ALL);
    }

```
###### \java\seedu\tache\model\ModelManager.java
``` java
    @Override
    public void updateFilteredListToShowTimed() {
        updateFilteredTaskList(new PredicateExpression(new ActiveTimedQualifier(true)));
        updateFilteredTaskListType(TASK_LIST_TYPE_TIMED);
    }

    @Override
    public void updateFilteredListToShowFloating() {
        updateFilteredTaskList(new PredicateExpression(new ActiveTimedQualifier(false)));
        updateFilteredTaskListType(TASK_LIST_TYPE_FLOATING);
    }

```
###### \java\seedu\tache\model\ModelManager.java
``` java
    /**
     * Provides functionality for find command and raises TaskListTypeChangedEvent to update UI.
     * Set<String> is converted to ArrayList<String> so that String can be retrieved.
     */
    @Override
    public void updateFilteredTaskList(Set<String> keywords) {
        assert keywords != null;
        updateFilteredTaskList(new PredicateExpression(new MultiQualifier(keywords)));
        updateFilteredTaskListType(TASK_LIST_TYPE_FOUND);
        retainLatestKeywords(keywords);
        raise(new TaskListTypeChangedEvent("Find \"" + StringUtil.generateStringFromKeywords(keywords) + "\""));
    }

    private void updateFilteredTaskList(Expression expression) {
        assert expression != null;
        filteredTasks.setPredicate(expression::satisfies);
        raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
    }

    @Override
    public String getFilteredTaskListType() {
        return filteredTaskListType;
    }

    private void updateFilteredTaskListType(String newFilteredTaskListType) {
        assert newFilteredTaskListType != null;
        assert !newFilteredTaskListType.equals("");
        if (!filteredTaskListType.equals(newFilteredTaskListType)) {
            raise(new TaskListTypeChangedEvent(newFilteredTaskListType));
        }
        filteredTaskListType = newFilteredTaskListType;
    }

```
###### \java\seedu\tache\model\ModelManager.java
``` java
    private class TimedQualifier implements Qualifier {
        private boolean isTimed;

        TimedQualifier(boolean isTimed) {
            this.isTimed = isTimed;
        }

        @Override
        public boolean run(ReadOnlyTask task) {
            assert task != null;
            if (isTimed) {
                return task.getTimedStatus();
            } else {
                return !task.getTimedStatus();
            }
        }

        @Override
        public String toString() {
            return "timed=" + isTimed;
        }
    }

```
###### \java\seedu\tache\model\ReadOnlyTaskManager.java
``` java
    /**
     * Returns a string that contains the no. of tasks and no. of tags.
     */
    String toString();

}
```
###### \java\seedu\tache\model\tag\UniqueTagList.java
``` java
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        forEach(builder::append);
        return builder.toString();
    }

    /**
     * Signals that an operation would have violated the 'no duplicates' property of the list.
     */
    public static class DuplicateTagException extends DuplicateDataException {
        protected DuplicateTagException() {
            super("Operation would result in duplicate tags");
        }
    }

}
```
###### \java\seedu\tache\model\task\DateTime.java
``` java
    /**
     * Returns a String which represents a moment to be parsed by FullCalendar.
     * A moment (FullCalendar terminology) refers to a point in time.
     */
    public String getDateTimeForFullCalendar() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        return sdf.format(date);
    }

    public Date getDate() {
        return date;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof DateTime // instanceof handles nulls
                && this.date.equals(((DateTime) other).getDate())); // state check
    }

    /**
     * Returns true if the date is earlier than today.
     */
    public boolean hasPassed() {
        Date today = new Date();
        return this.date.before(today);
    }

```
###### \java\seedu\tache\model\task\ReadOnlyTask.java
``` java
    /**
     * Returns true if both ReadOnlyTasks have the same state. (interfaces cannot override .equals)
     * This means that the details (e.g. name, end date) of the tasks will be identical.
     */
    default boolean isSameStateAs(ReadOnlyTask other) {
        assert other != null;
        boolean start = true;
        boolean end = true;
        if (other.getStartDateTime().isPresent() && this.getStartDateTime().isPresent()) {
            start = other.getStartDateTime().equals(this.getStartDateTime());
        }
        if (other.getEndDateTime().isPresent() && this.getEndDateTime().isPresent()) {
            end = other.getEndDateTime().equals(this.getEndDateTime());
        }
        return other == this // short circuit if same object
                || (other != null // this is first to avoid NPE below
                && other.getName().equals(this.getName())
                && start && end
                && (other.getActiveStatus() == this.getActiveStatus())
                && (other.getTimedStatus() == this.getTimedStatus())
                && (other.getRecurState().equals(this.getRecurState())));
    }
```
###### \java\seedu\tache\model\task\Task.java
``` java
    @Override
    public boolean getTimedStatus() {
        return isTimed;
    }

    public void setTimedStatus(boolean isTimed) {
        this.isTimed = isTimed;
    }

```
###### \java\seedu\tache\model\TaskManager.java
``` java
    /**
     * Returns a string showing all tasks and their details.
     */
    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        for (Task task : tasks) {
            builder.append(task.toString() + "\n");
        }
        return builder.toString();
    }
```
###### \java\seedu\tache\model\util\SampleDataUtil.java
``` java
    /**
     * Returns an array of Tasks for a sample task manager.
     */
    public static Task[] getSampleTasks() {
        try {
            Task eggsAndBread = new Task(new Name("Buy Eggs and Bread"), new UniqueTagList("HighPriority"));
            eggsAndBread.setStartDateTime(Optional.of(new DateTime("01-04-17 19:55:12")));
            Task readBook = new Task(new Name("Read Book about Software Engineering"),
                    new UniqueTagList("LowPriority"));
            readBook.setEndDateTime(Optional.of(new DateTime("21-04-17 23:59:59")));
            Task visitGrandma = new Task(new Name("Visit Grandma"), new UniqueTagList("MediumPriority"));
            visitGrandma.setStartDateTime(Optional.of(new DateTime("15-04-17 16:00:00")));
            visitGrandma.setEndDateTime(Optional.of(new DateTime("21-04-17 19:00:00")));
            return new Task[] {
                eggsAndBread, readBook, visitGrandma,
                new Task(new Name("Pay David 20 for cab"), new UniqueTagList("LowPriority")),
                new Task(new Name("Get Fit"), new UniqueTagList("LowPriority")),
                new Task(new Name("Find a girlfriend"), new UniqueTagList("LowPriority")),
                new Task(new Name("Walk the Dog"), Optional.of(new DateTime("14 April 2017")),
                            Optional.of(new DateTime("14 April 2017")), new UniqueTagList("MediumPriority"),
                                true, true, false, RecurInterval.NONE, new ArrayList<Date>()),
                new Task(new Name("Buy Medicine"), Optional.of(new DateTime("15 April 2017")),
                            Optional.empty(), new UniqueTagList("LowPriority"), true, true, false,
                            RecurInterval.NONE, new ArrayList<Date>()),
                new Task(new Name("Submit Project Proposal"), Optional.empty(),
                            Optional.of(new DateTime("17 April 2017")), new UniqueTagList("HighPriority"),
                                true, true, false, RecurInterval.NONE, new ArrayList<Date>()),
            };
        } catch (IllegalValueException e) {
            throw new AssertionError("sample data cannot be invalid", e);
        }
    }
```
###### \java\seedu\tache\storage\StorageManager.java
``` java
    /**
     * Updates the default file path of the task manager.
     * Raises a DataFileLocationChangedEvent to inform other components of this change.
     */
    @Override
    public void setTaskManagerFilePath(String newPath) {
        assert newPath != null;
        this.taskManagerStorage.setTaskManagerFilePath(newPath);
        logger.fine("File path set as: " + newPath);
        raise(new DataFileLocationChangedEvent(newPath));
    }
```
###### \java\seedu\tache\storage\XmlSerializableTaskManager.java
``` java
    /**
     * Returns a String containing the tasks and their details.
     */
    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        for (ReadOnlyTask task : getTaskList()) {
            builder.append(task.toString() + "\n");
        }
        return builder.toString();
    }

}
```
###### \java\seedu\tache\ui\CalendarPanel.java
``` java
    /**
     * Executes the script when the calendar finishes loading.
     *
     * @param script    Script to be executed.
     */
    private void loadAndExecuteScript(String script) {
        assert script != null;
        assert !script.equals("");
        WebEngine engine = calendar.getEngine();
        ReadOnlyObjectProperty<Worker.State> webViewState = engine.getLoadWorker().stateProperty();
        if (webViewState.get() == Worker.State.SUCCEEDED) {
            engine.executeScript(script);
        } else {
            engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
                @Override
                public void changed(ObservableValue<? extends Worker.State> observable,
                        Worker.State oldValue, Worker.State newValue) {
                    if (newValue != Worker.State.SUCCEEDED) {
                        return;
                    }
                    engine.executeScript(script);
                }
            });
        }
    }

    /**
     * Initializes the calendar, then adds all timed events.
     *
     * @param taskList    List of all tasks (including timed tasks).
     */
    private void loadCalendar(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        String calendarURL = MainApp.class.getResource("/html/calendar.html").toExternalForm();
        WebEngine engine = calendar.getEngine();
        engine.load(calendarURL);
        ReadOnlyObjectProperty<Worker.State> webViewState = engine.getLoadWorker().stateProperty();
        if (webViewState.get() == Worker.State.SUCCEEDED) {
            addAllEvents(taskList);
        } else {
            engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
                @Override
                public void changed(ObservableValue<? extends Worker.State> observable,
                        Worker.State oldValue, Worker.State newValue) {
                    if (newValue != Worker.State.SUCCEEDED) {
                        return;
                    }
                    addAllEvents(taskList);
                }
            });
        }
        logger.fine("Calendar loaded.");
    }

    /**
     * Returns the String that can be executed by the calendar WebEngine to add an event into the calendar.
     *
     * @param task    Task to be added as a calendar event.
     * @return    Script for calendar to add event.
     */
    private String getLoadTaskExecuteScript(ReadOnlyTask task) {
        assert task != null;
        String title = task.getName().toString();
        String start = "0";
        String end = "0"; // invalid format of datetime
        Optional<DateTime> startDateTime = task.getStartDateTime();
        Optional<DateTime> endDateTime = task.getEndDateTime();
        if (task.getStartDateTime().isPresent()) {
            start = startDateTime.get().getDateTimeForFullCalendar();
        }
        if (task.getEndDateTime().isPresent()) {
            end = endDateTime.get().getDateTimeForFullCalendar();
        }
        String status = "uncompleted";
        if (task.getActiveStatus() == false) {
            status = "completed";
        } else if (task.getEndDateTime().isPresent()) {
            if (task.getEndDateTime().get().hasPassed()) {
                status = "overdue";
            }
        } else if (task.getStartDateTime().isPresent()) {
            if (task.getStartDateTime().get().hasPassed()) {
                status = "overdue";
            }
        }
        return "add_event('" + title + "', '" + start + "', '" + end + "', '" + status + "')";
    }

    /**
     * Updates the events in the calendar whenever the task manager is modified.
     *
     * @param event    TaskManagerChangedEvent which contains the updated task list.
     */
    @Subscribe
    public void handleTaskManagerChangedEvent(TaskManagerChangedEvent event) {
        ObservableList<ReadOnlyTask> taskList = event.data.getTaskList();
        refreshCalendar(taskList);
        logger.fine("Calendar refreshed.");
    }

    /**
     * Changes the reference position of the calendar to the date associated with the selected task.
     * If the start date of the task is not present, the end date is used as reference instead.
     *
     * @param event    TaskPanelSelectionChangedEvent which contains the task selected.
     */
    @Subscribe
    public void handleTaskPanelSelectionChangedEvent(TaskPanelSelectionChangedEvent event) {
        Optional<DateTime> startDateTime = event.getNewSelection().getStartDateTime();
        Optional<DateTime> endDateTime = event.getNewSelection().getEndDateTime();
        if (startDateTime.isPresent()) {
            changeReferenceDate(startDateTime.get().getDateTimeForFullCalendar());
        } else if (endDateTime.isPresent()) {
            changeReferenceDate(endDateTime.get().getDateTimeForFullCalendar());
        }
    }

    /**
     * Changes the view of the calendar according to the task list type of the task panel.
     *
     * @param event    TaskListTypeChangedEvent which contains the updated task list type.
     */
    @Subscribe
    public void handleTaskListTypeChangedEvent(TaskListTypeChangedEvent event) {
        String taskListType = event.getTaskListType();
        if (taskListType.equals("Tasks Due Today") || taskListType.equals("Tasks Due This Week")) {
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            String referenceDate = sdf.format(today);
            changeReferenceDate(referenceDate);
            if (taskListType.equals("Tasks Due Today")) {
                changeView("day");
            } else {
                changeView("week");
            }
        } else {
            changeView("month");
        }
    }

    /**
     * Moves the calendar back (by a day / week / month).
     */
    @Subscribe
    public void handleCalendarPreviousRequestEvent(CalendarPreviousRequestEvent event) {
        loadAndExecuteScript("prev()");
        logger.fine("Calendar moved back.");
    }

    /**
     * Moves the calendar forward (by a day / week / month).
     */
    @Subscribe
    public void handleCalendarNextRequestEvent(CalendarNextRequestEvent event) {
        loadAndExecuteScript("next()");
        logger.fine("Calendar moved forward.");
    }

    /**
     * Changes the view of the calendar to day / week / month view.
     *
     * @param event    CalendarViewRequestEvent which contains the new view.
     */
    @Subscribe
    public void handleCalendarViewRequestEvent(CalendarViewRequestEvent event) {
        changeView(event.getView());
    }

    private void changeView(String view) {
        assert view != null;
        assert !view.equals("");
        loadAndExecuteScript("change_view('" + view + "')");
        logger.fine("Calendar view changed to: " + view);
    }

    /**
     * Moves the calendar to the referenceDate.
     */
    private void changeReferenceDate(String referenceDate) {
        assert referenceDate != null;
        assert !referenceDate.equals("");
        loadAndExecuteScript("change_reference_date('" + referenceDate + "')");
        logger.fine("Calendar reference date changed to: " + referenceDate);
    }

    private void addCurrentEvent(ReadOnlyTask task) {
        loadAndExecuteScript(getLoadTaskExecuteScript(task));
    }

    /**
     * Clears the calendar of all previous events, then adds all timed events from the latest taskList.
     *
     * @param taskList    Updated list of all tasks.
     */
    private void refreshCalendar(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        WebEngine engine = calendar.getEngine();
        ReadOnlyObjectProperty<Worker.State> webViewState = engine.getLoadWorker().stateProperty();
        if (webViewState.get() == Worker.State.SUCCEEDED) {
            removeAllEvents();
            addAllEvents(taskList);
        } else {
            engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
                @Override
                public void changed(ObservableValue<? extends Worker.State> observable,
                        Worker.State oldValue, Worker.State newValue) {
                    if (newValue != Worker.State.SUCCEEDED) {
                        return;
                    }
                    removeAllEvents();
                    addAllEvents(taskList);
                }
            });
        }
    }

    /**
     * Clears the calendar of all events.
     */
    private void removeAllEvents() {
        WebEngine engine = calendar.getEngine();
        engine.executeScript("remove_all()");
    }

    /**
     * Inputs all timed tasks into the calendar.
     * For deadline tasks (only have end but no start date/time), convert end date/time to start date/time.
     *
     * @param taskList    List which contains all tasks (including timed tasks).
     */
    public void addAllEvents(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        for (ReadOnlyTask task : taskList) {
            if (task.getTimedStatus()) {
                if (!task.getStartDateTime().isPresent()) {
                    Task newTask = new Task(task);
                    newTask.setStartDateTime(newTask.getEndDateTime());
                    newTask.setEndDateTime(Optional.empty());
                    task = newTask;
                }
                if (task.getRecurState().isMasterRecurring()) {
                    continue;
                }
                addCurrentEvent(task);
            }
        }
    }
```
###### \java\seedu\tache\ui\CommandBox.java
``` java
    private static ArrayList<String> userInputs = new ArrayList<String>();
    private static int currentUserInputIndex = userInputs.size();
```
###### \java\seedu\tache\ui\CommandBox.java
``` java
    /**
     * Executes the user command and adds it to the list of previous commands for retrieval.
     * Handles command success as well as command failure.
     */
    @FXML
    private void handleCommandInputChanged() {
        try {
            String userInput = commandTextField.getText();
            userInputs.add(userInput);
            currentUserInputIndex = userInputs.size();
            CommandResult commandResult = logic.execute(userInput);

            // process result of the command
            setStyleToIndicateCommandSuccess();
            commandTextField.setText("");
            logger.info("Result: " + commandResult.feedbackToUser);
            raise(new NewResultAvailableEvent(commandResult.feedbackToUser));

        } catch (CommandException e) {
            // handle command failure
            setStyleToIndicateCommandFailure();
            logger.info("Invalid command: " + commandTextField.getText());
            raise(new NewResultAvailableEvent(e.getMessage()));
        }
    }

    /**
     * Sets autocomplete functionality for user commands.
     * Uses ControlsFX Autocomplete TextField function.
     */
    private void setAutocomplete() {
        String[] possibleCommands = {"add ", "clear", "complete ", "delete ", "edit ", "exit", "find ",
                                        "help", "list", "save ", "select ", "load ", "undo", "next", "prev", "view " };
        AutoCompletionBinding<String> binding = TextFields.bindAutoCompletion(commandTextField, sr -> {
            ArrayList<String> commands = new ArrayList<String>();
            for (String str : possibleCommands) {
                String userInput = sr.getUserText();
                if ((!userInput.equals("") && str.startsWith(userInput) && !userInput.equals(str))) {
                    commands.add(str);
                }
            }
            return commands;
        });
        binding.setMaxWidth(100);
        binding.setDelay(50);
    }

    /**
     * Keeps track of previous commands executed and retrieves them with Up and Down keys.
     * Sets the caret of the text field right at the end of the command retrieved.
     */
    private void setSaveCommandHistory() {
        commandTextField.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                String userInput;
                if (userInputs.isEmpty()) {
                    return;
                }
                if (event.getCode() == KeyCode.UP && currentUserInputIndex >= 0) {
                    currentUserInputIndex--;
                    userInput = userInputs.get(currentUserInputIndex);
                    setTextAndCaret(userInput);
                }
                if (event.getCode() == KeyCode.DOWN && currentUserInputIndex < userInputs.size() - 1) {
                    currentUserInputIndex++;
                    userInput = userInputs.get(currentUserInputIndex);
                    setTextAndCaret(userInput);
                }
            }

            private void setTextAndCaret(String userInput) {
                if (userInput.length() > 0) {
                    commandTextField.setText(userInput);
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            commandTextField.positionCaret(userInput.length());
                        }
                    });
                }
            }
        });
    }
```
###### \java\seedu\tache\ui\MainWindow.java
``` java
    @FXML
    private AnchorPane taskListTypePlaceholder;

    @FXML
    private AnchorPane taskCountPlaceholder;
```
###### \java\seedu\tache\ui\MainWindow.java
``` java
    /**
     * Initializes all UI components using information from logic and config.
     */
    void fillInnerParts() {
        calendarPanel = new CalendarPanel(getCalendarPlaceholder(), logic.getFullTaskList());
        taskListPanel = new TaskListPanel(getTaskListPlaceholder(), logic.getFilteredTaskList());
        new TaskListType(getTaskListTypePlaceholder(), logic.getFilteredTaskListType());
        new TaskCount(getTaskCountPlaceholder(), logic);
        new ResultDisplay(getResultDisplayPlaceholder());
        new StatusBarFooter(getStatusbarPlaceholder(), config.getTaskManagerFilePath());
        new CommandBox(getCommandBoxPlaceholder(), logic);
    }

    private AnchorPane getCalendarPlaceholder() {
        return calendarPlaceholder;
    }
```
###### \java\seedu\tache\ui\MainWindow.java
``` java
    private AnchorPane getTaskCountPlaceholder() {
        return taskCountPlaceholder;
    }

    private AnchorPane getTaskListTypePlaceholder() {
        return taskListTypePlaceholder;
    }
```
###### \java\seedu\tache\ui\StatusBarFooter.java
``` java
    public String getSaveLocation() {
        return this.saveLocationStatus.getText();
    }

    public String getSyncStatus() {
        return this.syncStatus.getText();
    }
```
###### \java\seedu\tache\ui\StatusBarFooter.java
``` java
    /**
     * Updates the save location status bar when the data file location is changed.
     *
     * @param event    Event which contains the new data file path.
     */
    @Subscribe
    public void handleDataFileLocationChangedEvent(DataFileLocationChangedEvent event) {
        assert event != null;
        String newLocation = event.toString();
        logger.info(LogsCenter.getEventHandlingLogMessage(event, "Setting new data file location to" + newLocation));
        setSaveLocation("New Location: " + newLocation);
    }
}
```
###### \java\seedu\tache\ui\TaskCard.java
``` java
    private static final String INDICATOR_START_DATE = "Start Date: ";
    private static final String INDICATOR_START_TIME = "Start Time: ";
    private static final String INDICATOR_END_DATE = "End Date: ";
    private static final String INDICATOR_END_TIME = "End Time: ";
    private static final String FXML = "TaskListCard.fxml";

    private static final String INDICATOR_COMPLETED = "completed";
    private static final String INDICATOR_OVERDUE = "overdue";
    private static final String INDICATOR_UNCOMPLETED = "uncompleted";

    private final Logger logger = LogsCenter.getLogger(TaskCard.class);

    private String statusOfTask = INDICATOR_UNCOMPLETED;
    private boolean isMasterRecurring = false;
```
###### \java\seedu\tache\ui\TaskCard.java
``` java
    public TaskCard(ReadOnlyTask task, int displayedIndex) {
        super(FXML);
        assert task != null;
        assert displayedIndex > 0;
        id.setText(Integer.toString(displayedIndex) + ". ");
        id.setId("id"); // set property id for Label named id
        name.setText(task.getName().toString());
        name.setWrapText(true); // spill over to next line if task name is too long
        setStatusOfTask(task);
        setIsMasterRecurring(task);
        setSymbol();
        setBorderColour();
        initDatesAndTimes(task);
        initTags(task);
    }

    /**
     * Sets task status as completed, overdue or uncompleted.
     * Task status will be used to set border colour and symbol of task card later.
     */
    private void setStatusOfTask(ReadOnlyTask task) {
        assert task != null;
        if (task.getActiveStatus() == false) {
            statusOfTask = INDICATOR_COMPLETED;
        } else if (task.getEndDateTime().isPresent()) {
            DateTime taskDate = task.getEndDateTime().get();
            if (taskDate.hasPassed()) {
                statusOfTask = INDICATOR_OVERDUE;
            }
        }
    }

    /**
     * Checks if this task is the master task, if it is recurring.
     * Sets value of isMasterRecurring as true or false.
     */
    private void setIsMasterRecurring(ReadOnlyTask task) {
        assert task != null;
        isMasterRecurring = task.getRecurState().isMasterRecurring();
    }

    /**
     * Sets border colour of task card according to task status.
     */
    private void setBorderColour() {
        if (statusOfTask.equals(INDICATOR_UNCOMPLETED)) {
            cardPane.setStyle("-fx-border-color: #5f77bd"); // blue
        } else if (statusOfTask.equals(INDICATOR_OVERDUE)) {
            cardPane.setStyle("-fx-border-color: #ef044b"); // red
        } else {
            cardPane.setStyle("-fx-border-color: #14b66c"); // green
        }
    }

    /**
     * Sets symbol of task card according to task status.
     */
    private void setSymbol() {
        if (isMasterRecurring) {
            symbol.setImage(new Image(MainApp.class.getResource("/images/recurring.png").toExternalForm()));
        } else {
            if (statusOfTask.equals(INDICATOR_COMPLETED)) {
                symbol.setImage(new Image(MainApp.class.getResource("/images/tick.png").toExternalForm()));
            } else if (statusOfTask.equals(INDICATOR_OVERDUE)) {
                symbol.setImage(new Image(MainApp.class.getResource("/images/cross.png").toExternalForm()));
            }
        }
        symbol.setId("symbol");
    }

    /**
     * Sets start datetime and end datetime of  task.
     */
    private void initDatesAndTimes(ReadOnlyTask task) {
        assert task != null;
        if (task.getStartDateTime().isPresent()) {
            DateTime start = task.getStartDateTime().get();
            Label startDateLabel = new Label(INDICATOR_START_DATE + start.getDateOnly());
            startDateLabel.setId("startdate");
            datesAndTimes.getChildren().add(startDateLabel);
            Label startTimeLabel = new Label(INDICATOR_START_TIME + start.getTimeOnly());
            startTimeLabel.setId("starttime");
            datesAndTimes.getChildren().add(startTimeLabel);
            logger.fine("Start date and time added in Labels for " + task.getName().toString());
        }
        if (task.getEndDateTime().isPresent()) {
            DateTime end = task.getEndDateTime().get();
            Label endDateLabel = new Label(INDICATOR_END_DATE + end.getDateOnly());
            endDateLabel.setId("enddate");
            datesAndTimes.getChildren().add(endDateLabel);
            Label endTimeLabel = new Label(INDICATOR_END_TIME + end.getTimeOnly());
            endTimeLabel.setId("endtime");
            datesAndTimes.getChildren().add(endTimeLabel);
            logger.fine("End date and time added in Labels for " + task.getName().toString());
        }
    }

    private void initTags(ReadOnlyTask task) {
        assert task != null;
        task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
    }
}
```
###### \java\seedu\tache\ui\TaskCount.java
``` java
package seedu.tache.ui;

import java.util.logging.Logger;

import com.google.common.eventbus.Subscribe;

import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.events.ui.FilteredTaskListUpdatedEvent;
import seedu.tache.commons.util.FxViewUtil;
import seedu.tache.logic.Logic;
import seedu.tache.model.task.ReadOnlyTask;

/**
 * Count of timed and floating tasks.
 */
public class TaskCount extends UiPart<Region> {
    private static final Logger logger = LogsCenter.getLogger(TaskCount.class);
    private static final String FXML = "TaskCount.fxml";

    @FXML
    private Label timedTaskCount;
    @FXML
    private Label floatingTaskCount;

    public TaskCount(AnchorPane taskCountPlaceholder, Logic logic) {
        super(FXML);
        setTimedTaskCount(logic.getFilteredTaskList());
        setFloatingTaskCount(logic.getFilteredTaskList());
        addToPlaceholder(taskCountPlaceholder);
        registerAsAnEventHandler(this);
    }

    private void addToPlaceholder(AnchorPane placeHolder) {
        FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
        placeHolder.getChildren().add(getRoot());
    }

    private void setTimedTaskCount(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        String count = getTimedTaskCount(taskList);
        this.timedTaskCount.setText(count);
    }

    /**
     * Returns a String representing the number of timed tasks.
     *
     * @param taskList    Filtered task list displayed at task list panel.
     * @return    No. of timed tasks.
     */
    private String getTimedTaskCount(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        int count = 0;
        for (ReadOnlyTask task : taskList) {
            if (task.getTimedStatus() == true) {
                count++;
            }
        }
        return Integer.toString(count);
    }

    private void setFloatingTaskCount(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        String count = getFloatingTaskCount(taskList);
        this.floatingTaskCount.setText(count);
    }

    /**
     * Returns a String representing the number of floating tasks.
     *
     * @param taskList    Filtered task list displayed at task list panel.
     * @return    No. of floating tasks.
     */
    private String getFloatingTaskCount(ObservableList<ReadOnlyTask> taskList) {
        assert taskList != null;
        int count = 0;
        for (ReadOnlyTask task : taskList) {
            if (task.getTimedStatus() == false) {
                count++;
            }
        }
        return Integer.toString(count);
    }

    /**
     * Recalculates and sets the counts of timed and floating tasks.
     *
     * @param event    FilteredTaskListUpdatedEvent which contains updated task list.
     */
    @Subscribe
    public void handleFilteredTaskListUpdatedEvent(FilteredTaskListUpdatedEvent event) {
        ObservableList<ReadOnlyTask> taskList = event.getFilteredTaskList();
        String oldTimedCount = this.timedTaskCount.getText();
        String newTimedCount = getTimedTaskCount(taskList);
        if (oldTimedCount != newTimedCount) {
            this.timedTaskCount.setText(newTimedCount);
            logger.fine("Timed task list count changed to : '" + newTimedCount + "'");
        }
        String oldFloatingCount = this.floatingTaskCount.getText();
        String newFloatingCount = getFloatingTaskCount(taskList);
        if (oldFloatingCount != newFloatingCount) {
            this.floatingTaskCount.setText(newFloatingCount);
            logger.fine("Floating task list count changed to : '" + newFloatingCount + "'");
        }
    }

}
```
###### \java\seedu\tache\ui\TaskListType.java
``` java
package seedu.tache.ui;

import java.util.logging.Logger;

import com.google.common.eventbus.Subscribe;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.events.ui.TaskListTypeChangedEvent;
import seedu.tache.commons.util.FxViewUtil;

/**
 * A UI containing the type of tasks shown in task list.
 */
public class TaskListType extends UiPart<Region> {
    private final Logger logger = LogsCenter.getLogger(TaskListType.class);
    private static final String FXML = "TaskListType.fxml";

    @FXML
    private Label taskListType;

    public TaskListType(AnchorPane taskListTypePlaceholder, String typeOfTasks) {
        super(FXML);
        taskListType.setText(typeOfTasks);
        addToPlaceholder(taskListTypePlaceholder);
        registerAsAnEventHandler(this);
    }

    private void addToPlaceholder(AnchorPane placeHolder) {
        FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
        placeHolder.getChildren().add(getRoot());
    }

    /**
     * Updates task list type.
     *
     * @param event    TaskListTypeChangedEvent which contains new task list type.
     */
    @Subscribe
    public void handleTaskListTypeChangedEvent(TaskListTypeChangedEvent event) {
        String oldTaskListType = this.taskListType.getText();
        String newTaskListType = event.getTaskListType();
        if (oldTaskListType != newTaskListType) {
            this.taskListType.setText(newTaskListType);
            logger.fine("Task list type changed to : '" + newTaskListType + "'");
        }
    }

}
```
###### \resources\view\MainWindow.fxml
``` fxml
      <SplitPane id="splitPane" fx:id="splitPane" dividerPositions="0.3" VBox.vgrow="ALWAYS">
         <items>
            <SplitPane dividerPositions="0.3" maxWidth="300.0" orientation="VERTICAL">
              <items>
                <AnchorPane maxHeight="90.0">
                     <children>
                      <AnchorPane fx:id="taskListTypePlaceholder" minWidth="230.0" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0">
                           <padding>
                              <Insets bottom="5.0" left="10.0" right="10.0" top="5.0" />
                           </padding>
                        </AnchorPane>
                      <AnchorPane fx:id="taskCountPlaceholder" minHeight="90.0" maxWidth="60.0" prefWidth="60.0" AnchorPane.leftAnchor="210.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                           <padding>
                              <Insets bottom="5.0" left="10.0" right="10.0" top="5.0" />
                           </padding>
                        </AnchorPane>
                     </children>
                  </AnchorPane>
                <AnchorPane minWidth="300.0" prefWidth="300.0">
                     <children>
                        <VBox fx:id="taskList" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                           <padding>
                                <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
                           </padding>
                           <children>
                              <AnchorPane fx:id="taskListPanelPlaceholder" VBox.vgrow="ALWAYS" />
                           </children>
                        </VBox>
                     </children>
                  </AnchorPane>
              </items>
            </SplitPane>
            <AnchorPane fx:id="calendarPlaceholder" minWidth="380.0" prefWidth="380.0" VBox.vgrow="NEVER">
```
###### \resources\view\TacheTheme.css
``` css
.text-field {
    -fx-background-color: #5f77bd;
    -fx-font-size: 12pt;
    -fx-font-family: "Segoe UI Semibold";
    -fx-prompt-text-fill: black;
    -fx-text-fill: white;
    -fx-highlight-fill: #06314c;
}

.split-pane {
    -fx-border-radius: 1;
    -fx-border-width: 1;
    -fx-background-color: white;
}

.anchor-pane {
     -fx-background-color: white;
}

.anchor-pane-with-border {
     -fx-background-color: white;
     -fx-border-color: #039ed3;
     -fx-border-width: 3px;
}

.result-display {
    -fx-text-fill: #5f77bd;
    -fx-font-family: Segoe UI Light;
    -fx-font-size: 15px;
}

.status-bar-footer {
    -fx-background-color: white;
}

.status-bar .label {
    -fx-text-fill: #5f77bd;
    -fx-font-size: 15px;
}

.menu-bar {
    -fx-background-color: white;
}

.menu-item:focused {
    -fx-background-color: #c3cfe2;
}

.menu-bar .label {
    -fx-font-size: 14pt;
    -fx-font-family: "Segoe UI Semibold";
    -fx-text-fill: #5f77bd;
}

.menu:hover {
    -fx-background-color: #c3cfe2;
}

.task-list-header {
    -fx-background-color: white;
}

.task-list-header .label {
    -fx-font-size: 15pt;
    -fx-font-family: "Segoe UI Semibold";
    -fx-text-fill: #5f77bd;
    -fx-alignment: center;
}

.task-card-id-and-name .label {
    -fx-text-fill: #5f77bd;
    -fx-font-size: 12pt;
}

.task-card-date-time .label {
    -fx-font-size: 10pt;
    -fx-font-family: "Segoe UI Light";
    -fx-text-fill: black;
}

.list-cell:selected {
    -fx-background-color: #c3cfe2;
}

#cardPane {
    -fx-border-width: 3 3 3 3;
}

#cardPane:active {
    -fx-background-color: gray;
}

#tags {
    -fx-hgap: 7;
    -fx-vgap: 3;
}

#tags .label {
    -fx-text-fill: white;
    -fx-background-color: #5f77bd;
    -fx-padding: 1 3 1 3;
    -fx-border-radius: 2;
    -fx-background-radius: 2;
    -fx-font-size: 11;
}

.error {
    -fx-background-color: #ef044b;
}

```
###### \resources\view\TaskCount.fxml
``` fxml

<?import javafx.scene.control.Label?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxWidth="60.0" minHeight="70.0" prefHeight="70.0" prefWidth="60.0" styleClass="task-list-header"
       xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <ImageView fitHeight="35.0" fitWidth="35.0" pickOnBounds="true" preserveRatio="true" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0">
         <image>
            <Image url="@../images/clock.png" />
         </image>
      </ImageView>
      <Label fx:id="timedTaskCount" minHeight="35.0" minWidth="25.0" prefHeight="35.0" prefWidth="25.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
      <ImageView fitHeight="35.0" fitWidth="35.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0">
         <image>
            <Image url="@../images/task.png" />
         </image>
      </ImageView>
      <Label fx:id="floatingTaskCount" minHeight="35.0" minWidth="25.0" prefHeight="35.0" prefWidth="25.0" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="0.0" />
   </children>
</AnchorPane>
```
###### \resources\view\TaskListCard.fxml
``` fxml
                        <HBox alignment="CENTER_LEFT" spacing="5" styleClass="task-card-id-and-name">
                            <children>
                                <HBox>
                                    <Label fx:id="id" minWidth="28.0" />
                                    <AnchorPane prefWidth="200.0" minWidth="200.0">
                                       <children>
                                         <Label fx:id="name" maxWidth="170.0" text="\$first" />
                                         <AnchorPane minHeight="15.0" minWidth="15.0" prefHeight="20.0" prefWidth="20.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                                       <children>
                                         <ImageView fx:id="symbol" fitHeight="15.0" fitWidth="15.0" pickOnBounds="true" preserveRatio="true" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="0.0" />
                                    </children>
                                 </AnchorPane>
                              </children>
                           </AnchorPane>
                                </HBox>
                            </children>
                        </HBox>
                        <FlowPane fx:id="tags" />
                        <FlowPane fx:id="datesAndTimes" styleClass="task-card-date-time" maxWidth = "100.0"/>
```
###### \resources\view\TaskListType.fxml
``` fxml

<?import java.net.URL?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane fx:id="taskListTypePlaceholder" styleClass="task-list-header" xmlns="http://javafx.com/javafx/8.0.111"
    xmlns:fx="http://javafx.com/fxml/1">
    <stylesheets>
        <URL value="@TacheTheme.css" />
    </stylesheets>
    <Label fx:id="taskListType" maxWidth="200" prefWidth="200" minHeight="80"/>
</AnchorPane>
```


text:
namespace TSqlBuilder.Converters
{
    interface IOneWayConverter<in TType>
    {
        string Convert(TType data);
    }
}

redpajama_set_name: RedPajamaGithub


text: #Это папка принадлежит Trambling grass © Все права защищены.


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Represents virtual root node for all submissions
 *
 * Workshop submission uses two fileareas: submission_content for editor's embeded media
 * and submission_attachment for attachments. In both, the itemid represents the submission id.
 * This container is used to display the list of all submissions in these areas (ie when
 * these areas are browsed with itemid == null).
 */
class workshop_file_info_submissions_container extends file_info {
    protected $course;
    protected $cm;
    protected $areas;
    protected $filearea;

    public function __construct($browser, $course, $cm, $context, $areas, $filearea) {
        parent::__construct($browser, $context);
        $this->course   = $course;
        $this->cm       = $cm;
        $this->areas    = $areas;
        $this->filearea = $filearea;
    }

    /**
     * Returns list of standard virtual file/directory identification.
     * The difference from stored_file parameters is that null values
     * are allowed in all fields
     * @return array with keys contextid, filearea, itemid, filepath and filename
     */
    public function get_params() {
        return array('contextid'=>$this->context->id,
                     'component'=>'mod_workshop',
                     'filearea' =>$this->filearea,
                     'itemid'   =>null,
                     'filepath' =>null,
                     'filename' =>null);
    }

    /**
     * Returns localised visible name.
     * @return string
     */
    public function get_visible_name() {
        return $this->areas[$this->filearea];
    }

    /**
     * Can I add new files or directories?
     * @return bool
     */
    public function is_writable() {
        return false;
    }

    /**
     * Is directory?
     * @return bool
     */
    public function is_directory() {
        return true;
    }

    /**
     * Returns list of children nodes
     *
     * @return array of file_info instances
     */
    public function get_children() {
        return $this->get_filtered_children('*', false, true);
    }

    /**
     * Helper function to return files matching extensions or their count
     *
     * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
     * @param bool|int $countonly if false returns the children, if an int returns just the
     *    count of children but stops counting when $countonly number of children is reached
     * @param bool $returnemptyfolders if true returns items that don't have matching files inside
     * @return array|int array of file_info instances or the count
     */
    private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) {
        global $DB;
        $params = array('contextid' => $this->context->id,
            'component' => 'mod_workshop',
            'filearea' => $this->filearea);
        $sql = 'SELECT DISTINCT itemid
                    FROM {files}
                    WHERE contextid = :contextid
                    AND component = :component
                    AND filearea = :filearea';
        if (!$returnemptyfolders) {
            $sql .= ' AND filename <> :emptyfilename';
            $params['emptyfilename'] = '.';
        }
        list($sql2, $params2) = $this->build_search_files_sql($extensions);
        $sql .= ' '.$sql2;
        $params = array_merge($params, $params2);
        if ($countonly !== false) {
            $sql .= ' ORDER BY itemid DESC';
        }

        $rs = $DB->get_recordset_sql($sql, $params);
        $children = array();
        foreach ($rs as $record) {
            if (($child = $this->browser->get_file_info($this->context, 'mod_workshop', $this->filearea, $record->itemid))
                    && ($returnemptyfolders || $child->count_non_empty_children($extensions))) {
                $children[] = $child;
                if ($countonly !== false && count($children) >= $countonly) {
                    break;
                }
            }
        }
        $rs->close();
        if ($countonly !== false) {
            return count($children);
        }
        return $children;
    }

    /**
     * Returns list of children which are either files matching the specified extensions
     * or folders that contain at least one such file.
     *
     * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
     * @return array of file_info instances
     */
    public function get_non_empty_children($extensions = '*') {
        return $this->get_filtered_children($extensions, false);
    }

    /**
     * Returns the number of children which are either files matching the specified extensions
     * or folders containing at least one such file.
     *
     * NOTE: We don't need the exact number of non empty children if it is >=2
     * In this function 1 is never returned to avoid skipping the single subfolder
     *
     * @param string|array $extensions, for example '*' or array('.gif','.jpg')
     * @param int $limit stop counting after at least $limit non-empty children are found
     * @return int
     */
    public function count_non_empty_children($extensions = '*', $limit = 1) {
        return $this->get_filtered_children($extensions, $limit);
    }

    /**
     * Returns parent file_info instance
     * @return file_info or null for root
     */
    public function get_parent() {
        return $this->browser->get_file_info($this->context);
    }
}

/**
 * Represents virtual root node for all files in overall feedbacks
 *
 * Overall feedback uses two fileareas: overallfeedback_content for editor's embeded media
 * and overallfeedback_attachment for attachments. In both, the itemid represents the assessment id.
 * This container is used to display the list of all submissions in these areas (ie when
 * these areas are browsed with itemid == null).
 */
class workshop_file_info_overallfeedback_container extends file_info {
    protected $course;
    protected $cm;
    protected $areas;
    protected $filearea;

    public function __construct($browser, $course, $cm, $context, $areas, $filearea) {
        parent::__construct($browser, $context);
        $this->course   = $course;
        $this->cm       = $cm;
        $this->areas    = $areas;
        $this->filearea = $filearea;
    }

    /**
     * Returns list of standard virtual file/directory identification
     *
     * The difference from stored_file parameters is that null values
     * are allowed in all fields.
     *
     * @return array with keys contextid, filearea, itemid, filepath and filename
     */
    public function get_params() {
        return array('contextid' => $this->context->id,
                     'component' => 'mod_workshop',
                     'filearea' => $this->filearea,
                     'itemid' => null,
                     'filepath' => null,
                     'filename' => null);
    }

    /**
     * Returns localised visible name
     *
     * @return string
     */
    public function get_visible_name() {
        return $this->areas[$this->filearea];
    }

    /**
     * Can I add new files or directories?
     *
     * @return bool
     */
    public function is_writable() {
        return false;
    }

    /**
     * Is directory?
     *
     * @return bool
     */
    public function is_directory() {
        return true;
    }

    /**
     * Returns list of children nodes
     *
     * @return array of file_info instances
     */
    public function get_children() {
        return $this->get_filtered_children('*', false, true);
    }

    /**
     * Helper function to return files matching extensions or their count
     *
     * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
     * @param bool|int $countonly if false returns the children, if an int returns just the
     *    count of children but stops counting when $countonly number of children is reached
     * @param bool $returnemptyfolders if true returns items that don't have matching files inside
     * @return array|int array of file_info instances or the count
     */
    private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) {
        global $DB;

        $params = array('contextid' => $this->context->id,
            'component' => 'mod_workshop',
            'filearea' => $this->filearea);
        $sql = "SELECT DISTINCT itemid
                  FROM {files}
                 WHERE contextid = :contextid
                       AND component = :component
                       AND filearea = :filearea";
        if (!$returnemptyfolders) {
            $sql .= " AND filename <> :emptyfilename";
            $params['emptyfilename'] = '.';
        }
        list($sql2, $params2) = $this->build_search_files_sql($extensions);
        $sql .= ' '.$sql2;
        $params = array_merge($params, $params2);
        if ($countonly !== false) {
            $sql .= " ORDER BY itemid DESC";
        }

        $rs = $DB->get_recordset_sql($sql, $params);
        $children = array();
        foreach ($rs as $record) {
            if (($child = $this->browser->get_file_info($this->context, 'mod_workshop', $this->filearea, $record->itemid))
                    && ($returnemptyfolders || $child->count_non_empty_children($extensions))) {
                $children[] = $child;
                if ($countonly !== false && count($children) >= $countonly) {
                    break;
                }
            }
        }
        $rs->close();
        if ($countonly !== false) {
            return count($children);
        }
        return $children;
    }

    /**
     * Returns list of children which are either files matching the specified extensions
     * or folders that contain at least one such file.
     *
     * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
     * @return array of file_info instances
     */
    public function get_non_empty_children($extensions = '*') {
        return $this->get_filtered_children($extensions, false);
    }

    /**
     * Returns the number of children which are either files matching the specified extensions
     * or folders containing at least one such file.
     *
     * NOTE: We don't need the exact number of non empty children if it is >=2
     * In this function 1 is never returned to avoid skipping the single subfolder
     *
     * @param string|array $extensions, for example '*' or array('.gif','.jpg')
     * @param int $limit stop counting after at least $limit non-empty children are found
     * @return int
     */
    public function count_non_empty_children($extensions = '*', $limit = 1) {
        return $this->get_filtered_children($extensions, $limit);
    }

    /**
     * Returns parent file_info instance
     * @return file_info or null for root
     */
    public function get_parent() {
        return $this->browser->get_file_info($this->context);
    }
}


text:
import roslib
roslib.load_manifest('turtle_kinect')
import rospy

import tf
import turtlesim.msg

def handle_turtle_pose(msg, turtlename):
    br = tf.TransformBroadcaster()
    br.sendTransform((msg.x, msg.y, 0),
                     tf.transformations.quaternion_from_euler(0, 0, msg.theta),
                     rospy.Time.now(),
                     turtlename,
                     "world")

if __name__ == '__main__':
    rospy.init_node('turtle_tf_broadcaster')
    turtlename = rospy.get_param('~turtle')
    rospy.loginfo(turtlename)
    rospy.Subscriber('/%s/pose' % turtlename,
                     turtlesim.msg.Pose,
                     handle_turtle_pose,
                     turtlename)
    rospy.spin()


text:
// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// ---
// Author: Sanjay Ghemawat

#include <config.h>
#include <errno.h>                      // for EAGAIN, errno
#include <fcntl.h>                      // for open, O_RDWR
#include <stddef.h>                     // for size_t, NULL, ptrdiff_t
#if defined HAVE_STDINT_H
#include <stdint.h>                     // for uintptr_t, intptr_t
#elif defined HAVE_INTTYPES_H
#include <inttypes.h>
#else
#include <sys/types.h>
#endif
#ifdef HAVE_MMAP
#include <sys/mman.h>                   // for munmap, mmap, MADV_DONTNEED, etc
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>                     // for sbrk, getpagesize, off_t
#endif
#include <new>                          // for operator new
#include <gperftools/malloc_extension.h>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "base/spinlock.h"              // for SpinLockHolder, SpinLock, etc
#include "common.h"
#include "internal_logging.h"

// On systems (like freebsd) that don't define MAP_ANONYMOUS, use the old
// form of the name instead.
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif

// MADV_FREE is specifically designed for use by malloc(), but only
// FreeBSD supports it; in linux we fall back to the somewhat inferior
// MADV_DONTNEED.
#if !defined(MADV_FREE) && defined(MADV_DONTNEED)
# define MADV_FREE  MADV_DONTNEED
#endif

// Solaris has a bug where it doesn't declare madvise() for C++.
//    http://www.opensolaris.org/jive/thread.jspa?threadID=21035&tstart=0
#if defined(__sun) && defined(__SVR4)
# include <sys/types.h>    // for caddr_t
  extern "C" { extern int madvise(caddr_t, size_t, int); }
#endif

// Set kDebugMode mode so that we can have use C++ conditionals
// instead of preprocessor conditionals.
#ifdef NDEBUG
static const bool kDebugMode = false;
#else
static const bool kDebugMode = true;
#endif

// TODO(sanjay): Move the code below into the tcmalloc namespace
using tcmalloc::kLog;
using tcmalloc::Log;

// Anonymous namespace to avoid name conflicts on "CheckAddressBits".
namespace {

// Check that no bit is set at position ADDRESS_BITS or higher.
template <int ADDRESS_BITS> bool CheckAddressBits(uintptr_t ptr) {
  return (ptr >> ADDRESS_BITS) == 0;
}

// Specialize for the bit width of a pointer to avoid undefined shift.
template <> bool CheckAddressBits<8 * sizeof(void*)>(uintptr_t ptr) {
  return true;
}

#if defined(OS_LINUX) && defined(__x86_64__)
#define ASLR_IS_SUPPORTED
#endif

#if defined(ASLR_IS_SUPPORTED)
// From libdieharder, public domain library by Bob Jenkins (rngav.c).
// Described at http://burtleburtle.net/bob/rand/smallprng.html.
// Not cryptographically secure, but good enough for what we need.
typedef uint32_t u4;
struct ranctx {
  u4 a;
  u4 b;
  u4 c;
  u4 d;
};

#define rot(x,k) (((x)<<(k))|((x)>>(32-(k))))

u4 ranval(ranctx* x) {
  /* xxx: the generator being tested */
  u4 e = x->a - rot(x->b, 27);
  x->a = x->b ^ rot(x->c, 17);
  x->b = x->c + x->d;
  x->c = x->d + e;
  x->d = e + x->a;
  return x->d;
}

void raninit(ranctx* x, u4 seed) {
  u4 i;
  x->a = 0xf1ea5eed;
  x->b = x->c = x->d = seed;
  for (i = 0; i < 20; ++i) {
    (void) ranval(x);
  }
}

// If the kernel cannot honor the hint in arch_get_unmapped_area_topdown, it
// will simply ignore it. So we give a hint that has a good chance of
// working.
// The mmap top-down allocator will normally allocate below TASK_SIZE - gap,
// with a gap that depends on the max stack size. See x86/mm/mmap.c. We
// should make allocations that are below this area, which would be
// 0x7ffbf8000000.
// We use 0x3ffffffff000 as the mask so that we only "pollute" half of the
// address space. In the unlikely case where fragmentation would become an
// issue, the kernel will still have another half to use.
const uint64_t kRandomAddressMask = 0x3ffffffff000ULL;

#endif  // defined(ASLR_IS_SUPPORTED)

// Give a random "hint" that is suitable for use with mmap(). This cannot make
// mmap fail, as the kernel will simply not follow the hint if it can't.
// However, this will create address space fragmentation.  Currently, we only
// implement it on x86_64, where we have a 47 bits userland address space and
// fragmentation is not an issue.
void* GetRandomAddrHint() {
#if !defined(ASLR_IS_SUPPORTED)
  return NULL;
#else
  // Note: we are protected by the general TCMalloc_SystemAlloc spinlock. Given
  // the nature of what we're doing, it wouldn't be critical if we weren't for
  // ctx, but it is for the "initialized" variable.
  // It's nice to share the state between threads, because scheduling will add
  // some randomness to the succession of ranval() calls.
  static ranctx ctx;
  static bool initialized = false;
  if (!initialized) {
    initialized = true;
    // We really want this to be a stack variable and don't want any compiler
    // optimization. We're using its address as a poor-man source of
    // randomness.
    volatile char c;
    // Pre-initialize our seed with a "random" address in case /dev/urandom is
    // not available.
    uint32_t seed = (reinterpret_cast<uint64_t>(&c) >> 32) ^
                    reinterpret_cast<uint64_t>(&c);
    int urandom_fd = open("/dev/urandom", O_RDONLY);
    if (urandom_fd >= 0) {
      ssize_t len;
      len = read(urandom_fd, &seed, sizeof(seed));
      ASSERT(len == sizeof(seed));
      int ret = close(urandom_fd);
      ASSERT(ret == 0);
    }
    raninit(&ctx, seed);
  }
  uint64_t random_address = (static_cast<uint64_t>(ranval(&ctx)) << 32) |
                            ranval(&ctx);
  // A a bit-wise "and" won't bias our random distribution.
  random_address &= kRandomAddressMask;
  return reinterpret_cast<void*>(random_address);
#endif  // ASLR_IS_SUPPORTED
}

// Allocate |length| bytes of memory using mmap(). The memory will be
// readable and writeable, but not executable.
// Like mmap(), we will return MAP_FAILED on failure.
// |is_aslr_enabled| controls address space layout randomization. When true, we
// will put the first mapping at a random address and will then try to grow it.
// If it's not possible to grow an existing mapping, a new one will be created.
void* AllocWithMmap(size_t length, bool is_aslr_enabled) {
  // Note: we are protected by the general TCMalloc_SystemAlloc spinlock.
  static void* address_hint = NULL;
#if defined(ASLR_IS_SUPPORTED)
  if (is_aslr_enabled &&
      (!address_hint ||
       reinterpret_cast<uint64_t>(address_hint) & ~kRandomAddressMask)) {
    address_hint = GetRandomAddrHint();
  }
#endif  // ASLR_IS_SUPPORTED

  // address_hint is likely to make us grow an existing mapping.
  void* result = mmap(address_hint, length, PROT_READ|PROT_WRITE,
                      MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#if defined(ASLR_IS_SUPPORTED)
  if (result == address_hint) {
    // If mmap() succeeded at a address_hint, our next mmap() will try to grow
    // the current mapping as long as it's compatible with our ASLR mask.
    // This has been done for performance reasons, see crbug.com/173371.
    // It should be possible to strike a better balance between performance
    // and security but will be done at a later date.
    // If this overflows, it could only set address_hint to NULL, which is
    // what we want (and can't happen on the currently supported architecture).
    address_hint = static_cast<char*>(result) + length;
  } else {
    // mmap failed or a collision prevented the kernel from honoring the hint,
    // reset the hint.
    address_hint = NULL;
  }
#endif  // ASLR_IS_SUPPORTED
  return result;
}

}  // Anonymous namespace to avoid name conflicts on "CheckAddressBits".

COMPILE_ASSERT(kAddressBits <= 8 * sizeof(void*),
               address_bits_larger_than_pointer_size);

// Structure for discovering alignment
union MemoryAligner {
  void*  p;
  double d;
  size_t s;
} CACHELINE_ALIGNED;

static SpinLock spinlock(SpinLock::LINKER_INITIALIZED);

#if defined(HAVE_MMAP) || defined(MADV_FREE)
#ifdef HAVE_GETPAGESIZE
static size_t pagesize = 0;
#endif
#endif

// The current system allocator
SysAllocator* sys_alloc = NULL;

// Configuration parameters.
DEFINE_int32(malloc_devmem_start,
             EnvToInt("TCMALLOC_DEVMEM_START", 0),
             "Physical memory starting location in MB for /dev/mem allocation."
             "  Setting this to 0 disables /dev/mem allocation");
DEFINE_int32(malloc_devmem_limit,
             EnvToInt("TCMALLOC_DEVMEM_LIMIT", 0),
             "Physical memory limit location in MB for /dev/mem allocation."
             "  Setting this to 0 means no limit.");
DEFINE_bool(malloc_skip_sbrk,
            EnvToBool("TCMALLOC_SKIP_SBRK", false),
            "Whether sbrk can be used to obtain memory.");
DEFINE_bool(malloc_skip_mmap,
            EnvToBool("TCMALLOC_SKIP_MMAP", false),
            "Whether mmap can be used to obtain memory.");

DEFINE_bool(malloc_random_allocator,
#if defined(ASLR_IS_SUPPORTED)
            EnvToBool("TCMALLOC_ASLR", true),
#else
            EnvToBool("TCMALLOC_ASLR", false),
#endif
            "Whether to randomize the address space via mmap().");

// static allocators
class SbrkSysAllocator : public SysAllocator {
public:
  SbrkSysAllocator() : SysAllocator() {
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
};
static char sbrk_space[sizeof(SbrkSysAllocator)];

class MmapSysAllocator : public SysAllocator {
public:
  MmapSysAllocator() : SysAllocator() {
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
};
static char mmap_space[sizeof(MmapSysAllocator)];

class DevMemSysAllocator : public SysAllocator {
public:
  DevMemSysAllocator() : SysAllocator() {
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
};

class DefaultSysAllocator : public SysAllocator {
 public:
  DefaultSysAllocator() : SysAllocator() {
    for (int i = 0; i < kMaxAllocators; i++) {
      failed_[i] = true;
      allocs_[i] = NULL;
      names_[i] = NULL;
    }
  }
  void SetChildAllocator(SysAllocator* alloc, unsigned int index,
                         const char* name) {
    if (index < kMaxAllocators && alloc != NULL) {
      allocs_[index] = alloc;
      failed_[index] = false;
      names_[index] = name;
    }
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);

 private:
  static const int kMaxAllocators = 2;
  bool failed_[kMaxAllocators];
  SysAllocator* allocs_[kMaxAllocators];
  const char* names_[kMaxAllocators];
};
static char default_space[sizeof(DefaultSysAllocator)];
static const char sbrk_name[] = "SbrkSysAllocator";
static const char mmap_name[] = "MmapSysAllocator";

void* SbrkSysAllocator::Alloc(size_t size, size_t *actual_size,
                              size_t alignment) {
#ifndef HAVE_SBRK
  return NULL;
#else
  // Check if we should use sbrk allocation.
  // FLAGS_malloc_skip_sbrk starts out as false (its uninitialized
  // state) and eventually gets initialized to the specified value.  Note
  // that this code runs for a while before the flags are initialized.
  // That means that even if this flag is set to true, some (initial)
  // memory will be allocated with sbrk before the flag takes effect.
  if (FLAGS_malloc_skip_sbrk) {
    return NULL;
  }

  // sbrk will release memory if passed a negative number, so we do
  // a strict check here
  if (static_cast<ptrdiff_t>(size + alignment) < 0) return NULL;

  // This doesn't overflow because TCMalloc_SystemAlloc has already
  // tested for overflow at the alignment boundary.
  size = ((size + alignment - 1) / alignment) * alignment;

  // "actual_size" indicates that the bytes from the returned pointer
  // p up to and including (p + actual_size - 1) have been allocated.
  if (actual_size) {
    *actual_size = size;
  }

  // Check that we we're not asking for so much more memory that we'd
  // wrap around the end of the virtual address space.  (This seems
  // like something sbrk() should check for us, and indeed opensolaris
  // does, but glibc does not:
  //    http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libc/port/sys/sbrk.c?a=true
  //    http://sourceware.org/cgi-bin/cvsweb.cgi/~checkout~/libc/misc/sbrk.c?rev=1.1.2.1&content-type=text/plain&cvsroot=glibc
  // Without this check, sbrk may succeed when it ought to fail.)
  if (reinterpret_cast<intptr_t>(sbrk(0)) + size < size) {
    return NULL;
  }

  void* result = sbrk(size);
  if (result == reinterpret_cast<void*>(-1)) {
    return NULL;
  }

  // Is it aligned?
  uintptr_t ptr = reinterpret_cast<uintptr_t>(result);
  if ((ptr & (alignment-1)) == 0)  return result;

  // Try to get more memory for alignment
  size_t extra = alignment - (ptr & (alignment-1));
  void* r2 = sbrk(extra);
  if (reinterpret_cast<uintptr_t>(r2) == (ptr + size)) {
    // Contiguous with previous result
    return reinterpret_cast<void*>(ptr + extra);
  }

  // Give up and ask for "size + alignment - 1" bytes so
  // that we can find an aligned region within it.
  result = sbrk(size + alignment - 1);
  if (result == reinterpret_cast<void*>(-1)) {
    return NULL;
  }
  ptr = reinterpret_cast<uintptr_t>(result);
  if ((ptr & (alignment-1)) != 0) {
    ptr += alignment - (ptr & (alignment-1));
  }
  return reinterpret_cast<void*>(ptr);
#endif  // HAVE_SBRK
}

void* MmapSysAllocator::Alloc(size_t size, size_t *actual_size,
                              size_t alignment) {
#ifndef HAVE_MMAP
  return NULL;
#else
  // Check if we should use mmap allocation.
  // FLAGS_malloc_skip_mmap starts out as false (its uninitialized
  // state) and eventually gets initialized to the specified value.  Note
  // that this code runs for a while before the flags are initialized.
  // Chances are we never get here before the flags are initialized since
  // sbrk is used until the heap is exhausted (before mmap is used).
  if (FLAGS_malloc_skip_mmap) {
    return NULL;
  }

  // Enforce page alignment
  if (pagesize == 0) pagesize = getpagesize();
  if (alignment < pagesize) alignment = pagesize;
  size_t aligned_size = ((size + alignment - 1) / alignment) * alignment;
  if (aligned_size < size) {
    return NULL;
  }
  size = aligned_size;

  // "actual_size" indicates that the bytes from the returned pointer
  // p up to and including (p + actual_size - 1) have been allocated.
  if (actual_size) {
    *actual_size = size;
  }

  // Ask for extra memory if alignment > pagesize
  size_t extra = 0;
  if (alignment > pagesize) {
    extra = alignment - pagesize;
  }

  // Note: size + extra does not overflow since:
  //            size + alignment < (1<<NBITS).
  // and        extra <= alignment
  // therefore  size + extra < (1<<NBITS)
  void* result = AllocWithMmap(size + extra, FLAGS_malloc_random_allocator);
  if (result == reinterpret_cast<void*>(MAP_FAILED)) {
    return NULL;
  }

  // Adjust the return memory so it is aligned
  uintptr_t ptr = reinterpret_cast<uintptr_t>(result);
  size_t adjust = 0;
  if ((ptr & (alignment - 1)) != 0) {
    adjust = alignment - (ptr & (alignment - 1));
  }

  // Return the unused memory to the system
  if (adjust > 0) {
    munmap(reinterpret_cast<void*>(ptr), adjust);
  }
  if (adjust < extra) {
    munmap(reinterpret_cast<void*>(ptr + adjust + size), extra - adjust);
  }

  ptr += adjust;
  return reinterpret_cast<void*>(ptr);
#endif  // HAVE_MMAP
}

void* DevMemSysAllocator::Alloc(size_t size, size_t *actual_size,
                                size_t alignment) {
#ifndef HAVE_MMAP
  return NULL;
#else
  static bool initialized = false;
  static off_t physmem_base;  // next physical memory address to allocate
  static off_t physmem_limit; // maximum physical address allowed
  static int physmem_fd;      // file descriptor for /dev/mem

  // Check if we should use /dev/mem allocation.  Note that it may take
  // a while to get this flag initialized, so meanwhile we fall back to
  // the next allocator.  (It looks like 7MB gets allocated before
  // this flag gets initialized -khr.)
  if (FLAGS_malloc_devmem_start == 0) {
    // NOTE: not a devmem_failure - we'd like TCMalloc_SystemAlloc to
    // try us again next time.
    return NULL;
  }

  if (!initialized) {
    physmem_fd = open("/dev/mem", O_RDWR);
    if (physmem_fd < 0) {
      return NULL;
    }
    physmem_base = FLAGS_malloc_devmem_start*1024LL*1024LL;
    physmem_limit = FLAGS_malloc_devmem_limit*1024LL*1024LL;
    initialized = true;
  }

  // Enforce page alignment
  if (pagesize == 0) pagesize = getpagesize();
  if (alignment < pagesize) alignment = pagesize;
  size_t aligned_size = ((size + alignment - 1) / alignment) * alignment;
  if (aligned_size < size) {
    return NULL;
  }
  size = aligned_size;

  // "actual_size" indicates that the bytes from the returned pointer
  // p up to and including (p + actual_size - 1) have been allocated.
  if (actual_size) {
    *actual_size = size;
  }

  // Ask for extra memory if alignment > pagesize
  size_t extra = 0;
  if (alignment > pagesize) {
    extra = alignment - pagesize;
  }

  // check to see if we have any memory left
  if (physmem_limit != 0 &&
      ((size + extra) > (physmem_limit - physmem_base))) {
    return NULL;
  }

  // Note: size + extra does not overflow since:
  //            size + alignment < (1<<NBITS).
  // and        extra <= alignment
  // therefore  size + extra < (1<<NBITS)
  void *result = mmap(0, size + extra, PROT_WRITE|PROT_READ,
                      MAP_SHARED, physmem_fd, physmem_base);
  if (result == reinterpret_cast<void*>(MAP_FAILED)) {
    return NULL;
  }
  uintptr_t ptr = reinterpret_cast<uintptr_t>(result);

  // Adjust the return memory so it is aligned
  size_t adjust = 0;
  if ((ptr & (alignment - 1)) != 0) {
    adjust = alignment - (ptr & (alignment - 1));
  }

  // Return the unused virtual memory to the system
  if (adjust > 0) {
    munmap(reinterpret_cast<void*>(ptr), adjust);
  }
  if (adjust < extra) {
    munmap(reinterpret_cast<void*>(ptr + adjust + size), extra - adjust);
  }

  ptr += adjust;
  physmem_base += adjust + size;

  return reinterpret_cast<void*>(ptr);
#endif  // HAVE_MMAP
}

void* DefaultSysAllocator::Alloc(size_t size, size_t *actual_size,
                                 size_t alignment) {
  for (int i = 0; i < kMaxAllocators; i++) {
    if (!failed_[i] && allocs_[i] != NULL) {
      void* result = allocs_[i]->Alloc(size, actual_size, alignment);
      if (result != NULL) {
        return result;
      }
      failed_[i] = true;
    }
  }
  // After both failed, reset "failed_" to false so that a single failed
  // allocation won't make the allocator never work again.
  for (int i = 0; i < kMaxAllocators; i++) {
    failed_[i] = false;
  }
  return NULL;
}

static bool system_alloc_inited = false;
void InitSystemAllocators(void) {
  MmapSysAllocator *mmap = new (mmap_space) MmapSysAllocator();
  SbrkSysAllocator *sbrk = new (sbrk_space) SbrkSysAllocator();

  // In 64-bit debug mode, place the mmap allocator first since it
  // allocates pointers that do not fit in 32 bits and therefore gives
  // us better testing of code's 64-bit correctness.  It also leads to
  // less false negatives in heap-checking code.  (Numbers are less
  // likely to look like pointers and therefore the conservative gc in
  // the heap-checker is less likely to misinterpret a number as a
  // pointer).
  DefaultSysAllocator *sdef = new (default_space) DefaultSysAllocator();
  // Unfortunately, this code runs before flags are initialized. So
  // we can't use FLAGS_malloc_random_allocator.
#if defined(ASLR_IS_SUPPORTED)
  // Our only random allocator is mmap.
  sdef->SetChildAllocator(mmap, 0, mmap_name);
#else
  if (kDebugMode && sizeof(void*) > 4) {
    sdef->SetChildAllocator(mmap, 0, mmap_name);
    sdef->SetChildAllocator(sbrk, 1, sbrk_name);
  } else {
    sdef->SetChildAllocator(sbrk, 0, sbrk_name);
    sdef->SetChildAllocator(mmap, 1, mmap_name);
  }
#endif  // ASLR_IS_SUPPORTED
  sys_alloc = sdef;
}

void* TCMalloc_SystemAlloc(size_t size, size_t *actual_size,
                           size_t alignment) {
  // Discard requests that overflow
  if (size + alignment < size) return NULL;

  SpinLockHolder lock_holder(&spinlock);

  if (!system_alloc_inited) {
    InitSystemAllocators();
    system_alloc_inited = true;
  }

  // Enforce minimum alignment
  if (alignment < sizeof(MemoryAligner)) alignment = sizeof(MemoryAligner);

  void* result = sys_alloc->Alloc(size, actual_size, alignment);
  if (result != NULL) {
    if (actual_size) {
      CheckAddressBits<kAddressBits>(
          reinterpret_cast<uintptr_t>(result) + *actual_size - 1);
    } else {
      CheckAddressBits<kAddressBits>(
          reinterpret_cast<uintptr_t>(result) + size - 1);
    }
  }
  return result;
}

size_t TCMalloc_SystemAddGuard(void* start, size_t size) {
#ifdef HAVE_GETPAGESIZE
  if (pagesize == 0)
    pagesize = getpagesize();

  if (size < pagesize || (reinterpret_cast<size_t>(start) % pagesize) != 0)
    return 0;

  if (!mprotect(start, pagesize, PROT_NONE))
    return pagesize;
#endif

  return 0;
}

void TCMalloc_SystemRelease(void* start, size_t length) {
#ifdef MADV_FREE
  if (FLAGS_malloc_devmem_start) {
    // It's not safe to use MADV_FREE/MADV_DONTNEED if we've been
    // mapping /dev/mem for heap memory.
    return;
  }
  if (pagesize == 0) pagesize = getpagesize();
  const size_t pagemask = pagesize - 1;

  size_t new_start = reinterpret_cast<size_t>(start);
  size_t end = new_start + length;
  size_t new_end = end;

  // Round up the starting address and round down the ending address
  // to be page aligned:
  new_start = (new_start + pagesize - 1) & ~pagemask;
  new_end = new_end & ~pagemask;

  ASSERT((new_start & pagemask) == 0);
  ASSERT((new_end & pagemask) == 0);
  ASSERT(new_start >= reinterpret_cast<size_t>(start));
  ASSERT(new_end <= end);

  if (new_end > new_start) {
    // Note -- ignoring most return codes, because if this fails it
    // doesn't matter...
    while (madvise(reinterpret_cast<char*>(new_start), new_end - new_start,
                   MADV_FREE) == -1 &&
           errno == EAGAIN) {
      // NOP
    }
  }
#endif
}

void TCMalloc_SystemCommit(void* start, size_t length) {
  // Nothing to do here.  TCMalloc_SystemRelease does not alter pages
  // such that they need to be re-committed before they can be used by the
  // application.
}


text:
package selfhosting

import (
	"reflect"
	"testing"

	"k8s.io/api/core/v1"
	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
	kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
)

func TestMutatePodSpec(t *testing.T) {
	var tests = []struct {
		component string
		podSpec   *v1.PodSpec
		expected  v1.PodSpec
	}{
		{
			component: kubeadmconstants.KubeAPIServer,
			podSpec:   &v1.PodSpec{},
			expected: v1.PodSpec{
				NodeSelector: map[string]string{
					kubeadmconstants.LabelNodeRoleMaster: "",
				},
				Tolerations: []v1.Toleration{
					kubeadmconstants.MasterToleration,
				},
				DNSPolicy: v1.DNSClusterFirstWithHostNet,
			},
		},
		{
			component: kubeadmconstants.KubeControllerManager,
			podSpec:   &v1.PodSpec{},
			expected: v1.PodSpec{
				NodeSelector: map[string]string{
					kubeadmconstants.LabelNodeRoleMaster: "",
				},
				Tolerations: []v1.Toleration{
					kubeadmconstants.MasterToleration,
				},
				DNSPolicy: v1.DNSClusterFirstWithHostNet,
			},
		},
		{
			component: kubeadmconstants.KubeScheduler,
			podSpec:   &v1.PodSpec{},
			expected: v1.PodSpec{
				NodeSelector: map[string]string{
					kubeadmconstants.LabelNodeRoleMaster: "",
				},
				Tolerations: []v1.Toleration{
					kubeadmconstants.MasterToleration,
				},
				DNSPolicy: v1.DNSClusterFirstWithHostNet,
			},
		},
	}

	cfg := &kubeadmapi.MasterConfiguration{}
	for _, rt := range tests {
		mutatePodSpec(cfg, rt.component, rt.podSpec)

		if !reflect.DeepEqual(*rt.podSpec, rt.expected) {
			t.Errorf("failed mutatePodSpec:\nexpected:\n%v\nsaw:\n%v", rt.expected, *rt.podSpec)
		}
	}
}

func TestAddNodeSelectorToPodSpec(t *testing.T) {
	var tests = []struct {
		podSpec  *v1.PodSpec
		expected v1.PodSpec
	}{
		{
			podSpec: &v1.PodSpec{},
			expected: v1.PodSpec{
				NodeSelector: map[string]string{
					kubeadmconstants.LabelNodeRoleMaster: "",
				},
			},
		},
		{
			podSpec: &v1.PodSpec{
				NodeSelector: map[string]string{
					"foo": "bar",
				},
			},
			expected: v1.PodSpec{
				NodeSelector: map[string]string{
					"foo": "bar",
					kubeadmconstants.LabelNodeRoleMaster: "",
				},
			},
		},
	}

	cfg := &kubeadmapi.MasterConfiguration{}
	for _, rt := range tests {
		addNodeSelectorToPodSpec(cfg, rt.podSpec)

		if !reflect.DeepEqual(*rt.podSpec, rt.expected) {
			t.Errorf("failed addNodeSelectorToPodSpec:\nexpected:\n%v\nsaw:\n%v", rt.expected, *rt.podSpec)
		}
	}
}

func TestSetMasterTolerationOnPodSpec(t *testing.T) {
	var tests = []struct {
		podSpec  *v1.PodSpec
		expected v1.PodSpec
	}{
		{
			podSpec: &v1.PodSpec{},
			expected: v1.PodSpec{
				Tolerations: []v1.Toleration{
					kubeadmconstants.MasterToleration,
				},
			},
		},
		{
			podSpec: &v1.PodSpec{
				Tolerations: []v1.Toleration{
					{Key: "foo", Value: "bar"},
				},
			},
			expected: v1.PodSpec{
				Tolerations: []v1.Toleration{
					{Key: "foo", Value: "bar"},
					kubeadmconstants.MasterToleration,
				},
			},
		},
	}

	cfg := &kubeadmapi.MasterConfiguration{}
	for _, rt := range tests {
		setMasterTolerationOnPodSpec(cfg, rt.podSpec)

		if !reflect.DeepEqual(*rt.podSpec, rt.expected) {
			t.Errorf("failed setMasterTolerationOnPodSpec:\nexpected:\n%v\nsaw:\n%v", rt.expected, *rt.podSpec)
		}
	}
}

func TestSetRightDNSPolicyOnPodSpec(t *testing.T) {
	var tests = []struct {
		podSpec  *v1.PodSpec
		expected v1.PodSpec
	}{
		{
			podSpec: &v1.PodSpec{},
			expected: v1.PodSpec{
				DNSPolicy: v1.DNSClusterFirstWithHostNet,
			},
		},
		{
			podSpec: &v1.PodSpec{
				DNSPolicy: v1.DNSClusterFirst,
			},
			expected: v1.PodSpec{
				DNSPolicy: v1.DNSClusterFirstWithHostNet,
			},
		},
	}

	cfg := &kubeadmapi.MasterConfiguration{}
	for _, rt := range tests {
		setRightDNSPolicyOnPodSpec(cfg, rt.podSpec)

		if !reflect.DeepEqual(*rt.podSpec, rt.expected) {
			t.Errorf("failed setRightDNSPolicyOnPodSpec:\nexpected:\n%v\nsaw:\n%v", rt.expected, *rt.podSpec)
		}
	}
}


text:
package org.geneticmachine.genetic

import scala.collection.parallel.immutable.ParVector

package object selector {
  final case class ThresholdSelector[G <: GeneStrength](threshold: Double) extends Selector[ParVector[G]] {

    def apply(population: ParVector[G]): ParVector[G] = {
      population.filter { g: G =>
        g.strength > threshold
      }
    }
  }

  /**
   * Not a parallel selector!
   */
  abstract class BestSelector[G <: GeneStrength] extends Selector[ParVector[G]] {
    def apply(n: Int)(population: ParVector[G]): ParVector[G] = {
      population.toVector.sortBy { - _.strength }.take(n).par
    }
  }

  final case class NBestSelector[G <: GeneStrength](n: Int) extends BestSelector[G] {
    def apply(population: ParVector[G]): ParVector[G] = apply(n)(population)
  }

  final case class QuantileSelector[G <: GeneStrength](alpha: Double) extends BestSelector[G] {
    def apply(population: ParVector[G]): ParVector[G] = apply((population.size * alpha).toInt)(population)
  }
}