<commit_before>// references
var review  = require('./manager').review;
var manager = require('./manager').response;

// middleware between response and controller
var Zappy = function(controller, schema){
  this.cx = controller;
  this.sc = schema;
};

Zappy.prototype.Get = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.List({}, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.GetOne = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.FindById(req.params.id, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.Del = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.DeleteById(req.params.id, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.Post = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.Create(req.params, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.Put = function(req, res){
  delete req.body._id;
  review({ req: req, res: res, zap: this, schema: true }, function(err, opt){
    opt.zap.cx.UpdateById(req.params.id, {$set: req.body}, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

module.exports.Zappy = Zappy;
<commit_msg>Cleaning req.body<commit_after>// references
var review  = require('./manager').review;
var manager = require('./manager').response;

// middleware between response and controller
var Zappy = function(controller, schema){
  this.cx = controller;
  this.sc = schema;
};

Zappy.prototype.Get = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.List({}, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.GetOne = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.FindById(req.params.id, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.Del = function(req, res){
  delete req.body;
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.DeleteById(req.params.id, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.Post = function(req, res){
  review({ req: req, res: res, zap: this }, function(err, opt){
    opt.zap.cx.Create(req.params, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

Zappy.prototype.Put = function(req, res){
  delete req.body._id;
  review({ req: req, res: res, zap: this, schema: true }, function(err, opt){
    opt.zap.cx.UpdateById(req.params.id, {$set: req.body}, function(err, rsp){
      manager(req, res, err, rsp);
    });
  });
};

module.exports.Zappy = Zappy;
<|endoftext|>


<commit_before>/*
  all functions dealing with the calendar that aren't
  automatically created server-side.
*/

function ajaxCall(form) {
    /*
      Creates an ajax call depending on what
      called the function.

      Server-side there is a view at domain/ajax/
      which is designed to intercept all ajax
      calls.

      The idea is that you define a function,
      add it to the ajax view's dict of functions
      along with a tag denoting it's name, and
      then pass the string to the 'form_type'
      json you sent to that view.

      In this particular ajax request function
      we're pulling out form data depending on
      what form calls the ajaxCall
    */

    "use strict";

    $.ajaxSetup({type: 'POST'});
    var pre = '';
    if (form === "delete") {
        pre = "#change_";
    } else {
        pre = "#" + form + "_";
    }

    if (!validateTimePair(pre+'starttime', pre+'endtime')) {
        alert("Start Time before End Time");
        return false;
    }

    if (  $(pre + 'daytype').val() !== "WKDAY" ) {
        return;
    }

    var formData = {
        "form_type" : form,
        "entry_date" : $(pre + 'entrydate').val(),
        "start_time" : $(pre + 'starttime').val(),
        "end_time" : $(pre + 'endtime').val(),
        "daytype" : $(pre + 'daytype').val(),
        "hidden-id" : $('#hidden_id').val(),
        "breaks": $(pre + "breaks").val()
    };

    // no point in making invalid ajax requests
    if (!formData.entry_date || !formData.start_time || !formData.end_time) {
        return false;
    }

    $.ajax({
        url: "/ajax/",
        data: formData,
        dataType: "json",
        success: function (data) {
            if (data.success === true) {
                $("#calendar-entry").fadeToggle("slow", function() {
                    $("#calendar-entry").html(data.calendar);
                    $(".table-links").css({"color": "white"});
                });
                $("#calendar-entry").fadeToggle("slow");
            } else {
                alert(data.error);
            }
        }
    }
          );

    return false; // so the form doesn't do it's regular action
}

function onOptionChange(element) {

    /*
      When specific options are selected
      there is no need to give working times
      considering that the person wasn't at
      work
    */

    "use strict";

    var pre = "#" + element + "_";
    var preSet$ = $(pre + "starttime," +
                   pre + "endtime," +
                   pre + "breaks");
    var optionBoxVal = $(pre + "daytype").val();
    // these are the types that will have their
    // form elements disabled if selected
    var disabledTypes = [
        "SICKD", "HOLIS", "MEDIC", "SPECI",
        "PUABS", "TRAIN", "DAYOD", "RETRN"
    ]

    if ( $.inArray(optionBoxVal, disabledTypes) > -1 ) {

        $(pre + "starttime").val('00:00');
        $(pre + "endtime").val('00:01');
        $(pre + "breaks").val('00:00');

        // disable the boxes because there's no need to
        // use them since we've put the values in for them
        preSet$.each(function () {
            $(this).attr("disabled", "disabled");
        });
        return true;
    } else {
        // otherwise, we clear the box in case the values
        // were filled previously
        preSet$.each(function () {
            $(this).val('');
        });
        // and remove the disabled attribute
        preSet$.each(function () {
            $(this).removeAttr("disabled");
        });
        return true;
    }
}

function addTimePicker(element, state) {

    /*
      adds a jQuery TimePicker to `element`
      with an initial state of `state`.
      this is an impure function and returns
      undefined.
    */

    "use strict";

    $(element).timepicker({
        showHour: true,
        stepMinute: 5
    });

    $(element).val('');

    if (!state) {
        $(element).timepicker("disable");
    }

}

function addDatePicker(element, state) {

    /*
      adds a jQuery datePicker to `element`
      with an initial state of `state`.
      this is an impoure function and returns
      undefined.
    */

    "use strict";

    $(element).datepicker().val('');
    $(element).datepicker("option", "dateFormat", 'yy-mm-dd');

    if (!state) {
        $(element).datepicker("disable");
    }

}

$(function () {

    /*
      jQuery onload function which adds a
      few widgets to the page along with
      their initial state.
    */

    "use strict";

    addTimePicker("#change_starttime", false);
    addTimePicker("#change_endtime", false);
    addTimePicker("#add_starttime", true);
    addTimePicker("#add_endtime", true);
    addDatePicker("#change_entrydate", false);
    addDatePicker("#add_entrydate", true);

    $("#add_daytype").change(function () {
        onOptionChange('add')
    });
    $("#change_daytype").change(function () {
        onOptionChange('change')
    });

    $("#add_breaks")
        .timepicker({
            showHour: false
        })
        .val('');

    $("#change_breaks")
        .timepicker({
            showHour: false
        })
        .val('');

    onOptionChange('add');
    onOptionChange('change');
});

function deleteEntry() {

    /*
      Deletes a calendar entry
    */

    "use strict";

    if ($("#change_daytype").val() !== "WKDAY") {
        return;
    }

    var answer = confirm("Are you sure?");
    if (answer) {
        return ajaxCall("delete");
    } else {
        return false;
    }
}

function toggleChangeEntries(st_hour, st_min, full_st,
                             fi_hour, fi_min, full_fi,
                             entry_date, daytype,
                             change_id, breakLength,
                             breakLength_full) {

    /*
      When an entry is clicked, it will fill out the
      change form so that the user can enter a new
      set of information instead.
    */

    "use strict";

    // change the ID field
    $("#hidden_id").val(change_id);

    // if we've previously clicked an empty cell
    // the add_entry date will have a date in it
    $("#add_entrydate").val('');

    // re-enable the form and enter the times
    $("#change_starttime").timepicker("enable");
    $("#change_endtime").timepicker("enable");
    $("#change_breaks").timepicker("enable");

    $("#change_entrydate").val(entry_date);
    $("#change_daytype").val(daytype);

    $("#change_starttime").timepicker("destroy");
    $("#change_endtime").timepicker("destroy");
    $("#change_breaks").timepicker("destroy");

    $("#change_starttime").timepicker({
        showHour: true,
        hour: st_hour,
        minute: st_min,
        stepMinute: 5
    });

    $("#change_endtime").timepicker({
        showHour: true,
        hour: fi_hour,
        minute: fi_min,
        stepMinute: 5
    });

    $("#change_breaks").timepicker({
        hour: 0,
        minute: breakLength,
        showHour: false,
        stepMinute: 5
    });

    // it seems programmatically changing the option box
    // doesn't fire the signal, so we just fire it ourselves
    onOptionChange("change");

    // zero out the add form
    $("#add_starttime").val('');
    $("#add_endtime").val('');
    $("#add_breaks").val('');

    // put the dates into the change boxes
    $("#change_starttime").val(full_st);
    $("#change_endtime").val(full_fi);
    $("#change_breaks").val(breakLength_full);

}

function hideEntries(date) {
    $("#add_entrydate").val(date);
    $("#add_starttime").val('');
    $("#add_endtime").val('');
    $("#add_breaks").val('');

    $("#change_starttime").val('');
    $("#change_entrydate").val('');
    $("#change_endtime").val('');
    $("#change_breaks").val('');

    $("#add_starttime").timepicker("destroy");
    $("#add_endtime").timepicker("destroy");
    $("#add_breaks").timepicker("destroy");

    $("#add_starttime").timepicker({
        showHour: true,
        hour: 0,
        minute: 0,
        stepMinute: 5
    });

    $("#add_endtime").timepicker({
        showHour: true,
        hour: 0,
        minute: 0,
        stepMinute: 5
    });

    $("#add_breaks").timepicker({
        showHour: false,
        hour: 0,
        minute: 0,
        stepMinute: 5
    });

    onOptionChange("add");
    onOptionChange("change");
}

$(function () {
    $(".table-links").css({"color": "white"});
});<commit_msg>Changed order of validation checks to a more logical one<commit_after>/*
  all functions dealing with the calendar that aren't
  automatically created server-side.
*/

function ajaxCall(form) {
    /*
      Creates an ajax call depending on what
      called the function.

      Server-side there is a view at domain/ajax/
      which is designed to intercept all ajax
      calls.

      The idea is that you define a function,
      add it to the ajax view's dict of functions
      along with a tag denoting it's name, and
      then pass the string to the 'form_type'
      json you sent to that view.

      In this particular ajax request function
      we're pulling out form data depending on
      what form calls the ajaxCall
    */

    "use strict";

    $.ajaxSetup({type: 'POST'});
    var pre = '';
    if (form === "delete") {
        pre = "#change_";
    } else {
        pre = "#" + form + "_";
    }

    if (  $(pre + 'daytype').val() !== "WKDAY" ) {
        return;
    }

    if ($(pre+'starttime').val() === $(pre+'endtime').val() {
        alert("Length of working time invalid")
    }

    if (!validateTimePair(pre+'starttime', pre+'endtime')) {
        alert("Start Time before End Time");
        return false;
    }

    var formData = {
        "form_type" : form,
        "entry_date" : $(pre + 'entrydate').val(),
        "start_time" : $(pre + 'starttime').val(),
        "end_time" : $(pre + 'endtime').val(),
        "daytype" : $(pre + 'daytype').val(),
        "hidden-id" : $('#hidden_id').val(),
        "breaks": $(pre + "breaks").val()
    };

    // no point in making invalid ajax requests
    if (!formData.entry_date || !formData.start_time || !formData.end_time) {
        return false;
    }

    $.ajax({
        url: "/ajax/",
        data: formData,
        dataType: "json",
        success: function (data) {
            if (data.success === true) {
                $("#calendar-entry").fadeToggle("slow", function() {
                    $("#calendar-entry").html(data.calendar);
                    $(".table-links").css({"color": "white"});
                });
                $("#calendar-entry").fadeToggle("slow");
            } else {
                alert(data.error);
            }
        }
    }
          );

    return false; // so the form doesn't do it's regular action
}

function onOptionChange(element) {

    /*
      When specific options are selected
      there is no need to give working times
      considering that the person wasn't at
      work
    */

    "use strict";

    var pre = "#" + element + "_";
    var preSet$ = $(pre + "starttime," +
                   pre + "endtime," +
                   pre + "breaks");
    var optionBoxVal = $(pre + "daytype").val();
    // these are the types that will have their
    // form elements disabled if selected
    var disabledTypes = [
        "SICKD", "HOLIS", "MEDIC", "SPECI",
        "PUABS", "TRAIN", "DAYOD", "RETRN"
    ]

    if ( $.inArray(optionBoxVal, disabledTypes) > -1 ) {

        $(pre + "starttime").val('00:00');
        $(pre + "endtime").val('00:01');
        $(pre + "breaks").val('00:00');

        // disable the boxes because there's no need to
        // use them since we've put the values in for them
        preSet$.each(function () {
            $(this).attr("disabled", "disabled");
        });
        return true;
    } else {
        // otherwise, we clear the box in case the values
        // were filled previously
        preSet$.each(function () {
            $(this).val('');
        });
        // and remove the disabled attribute
        preSet$.each(function () {
            $(this).removeAttr("disabled");
        });
        return true;
    }
}

function addTimePicker(element, state) {

    /*
      adds a jQuery TimePicker to `element`
      with an initial state of `state`.
      this is an impure function and returns
      undefined.
    */

    "use strict";

    $(element).timepicker({
        showHour: true,
        stepMinute: 5
    });

    $(element).val('');

    if (!state) {
        $(element).timepicker("disable");
    }

}

function addDatePicker(element, state) {

    /*
      adds a jQuery datePicker to `element`
      with an initial state of `state`.
      this is an impoure function and returns
      undefined.
    */

    "use strict";

    $(element).datepicker().val('');
    $(element).datepicker("option", "dateFormat", 'yy-mm-dd');

    if (!state) {
        $(element).datepicker("disable");
    }

}

$(function () {

    /*
      jQuery onload function which adds a
      few widgets to the page along with
      their initial state.
    */

    "use strict";

    addTimePicker("#change_starttime", false);
    addTimePicker("#change_endtime", false);
    addTimePicker("#add_starttime", true);
    addTimePicker("#add_endtime", true);
    addDatePicker("#change_entrydate", false);
    addDatePicker("#add_entrydate", true);

    $("#add_daytype").change(function () {
        onOptionChange('add')
    });
    $("#change_daytype").change(function () {
        onOptionChange('change')
    });

    $("#add_breaks")
        .timepicker({
            showHour: false
        })
        .val('');

    $("#change_breaks")
        .timepicker({
            showHour: false
        })
        .val('');

    onOptionChange('add');
    onOptionChange('change');
});

function deleteEntry() {

    /*
      Deletes a calendar entry
    */

    "use strict";

    if ($("#change_daytype").val() !== "WKDAY") {
        return;
    }

    var answer = confirm("Are you sure?");
    if (answer) {
        return ajaxCall("delete");
    } else {
        return false;
    }
}

function toggleChangeEntries(st_hour, st_min, full_st,
                             fi_hour, fi_min, full_fi,
                             entry_date, daytype,
                             change_id, breakLength,
                             breakLength_full) {

    /*
      When an entry is clicked, it will fill out the
      change form so that the user can enter a new
      set of information instead.
    */

    "use strict";

    // change the ID field
    $("#hidden_id").val(change_id);

    // if we've previously clicked an empty cell
    // the add_entry date will have a date in it
    $("#add_entrydate").val('');

    // re-enable the form and enter the times
    $("#change_starttime").timepicker("enable");
    $("#change_endtime").timepicker("enable");
    $("#change_breaks").timepicker("enable");

    $("#change_entrydate").val(entry_date);
    $("#change_daytype").val(daytype);

    $("#change_starttime").timepicker("destroy");
    $("#change_endtime").timepicker("destroy");
    $("#change_breaks").timepicker("destroy");

    $("#change_starttime").timepicker({
        showHour: true,
        hour: st_hour,
        minute: st_min,
        stepMinute: 5
    });

    $("#change_endtime").timepicker({
        showHour: true,
        hour: fi_hour,
        minute: fi_min,
        stepMinute: 5
    });

    $("#change_breaks").timepicker({
        hour: 0,
        minute: breakLength,
        showHour: false,
        stepMinute: 5
    });

    // it seems programmatically changing the option box
    // doesn't fire the signal, so we just fire it ourselves
    onOptionChange("change");

    // zero out the add form
    $("#add_starttime").val('');
    $("#add_endtime").val('');
    $("#add_breaks").val('');

    // put the dates into the change boxes
    $("#change_starttime").val(full_st);
    $("#change_endtime").val(full_fi);
    $("#change_breaks").val(breakLength_full);

}

function hideEntries(date) {
    $("#add_entrydate").val(date);
    $("#add_starttime").val('');
    $("#add_endtime").val('');
    $("#add_breaks").val('');

    $("#change_starttime").val('');
    $("#change_entrydate").val('');
    $("#change_endtime").val('');
    $("#change_breaks").val('');

    $("#add_starttime").timepicker("destroy");
    $("#add_endtime").timepicker("destroy");
    $("#add_breaks").timepicker("destroy");

    $("#add_starttime").timepicker({
        showHour: true,
        hour: 0,
        minute: 0,
        stepMinute: 5
    });

    $("#add_endtime").timepicker({
        showHour: true,
        hour: 0,
        minute: 0,
        stepMinute: 5
    });

    $("#add_breaks").timepicker({
        showHour: false,
        hour: 0,
        minute: 0,
        stepMinute: 5
    });

    onOptionChange("add");
    onOptionChange("change");
}

$(function () {
    $(".table-links").css({"color": "white"});
});<|endoftext|>


<commit_before>$( document ).ready( function() {

    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#expenseForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, checkbox, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to /form.php
        request = $.ajax({
            url: "/expenses/add",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it added!");

            $('#successbox').html('
Expense added successfully :)
');
            $('#successbox').css('display','block');

            setTimeout(function(){
                $('#successbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );

            $('#failbox').html('
Error adding expenses :(
');
            $('#failbox').css('display','block');

            // Load List of Expenses
            $.ajax({
                  url:"/expenses/listing",
                  cache:0,
                  success:function(result){
                         document.getElementById("expenseListing").innerHTML=result;
                   }
            });

            setTimeout(function(){
                $('#failbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default posting of form
        event.preventDefault();
    });

    // Bind to the submit event of our form
    $("#deleteForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to form
        request = $.ajax({
            url: "/expenses/delete",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it deleted!");

            $('#successbox').html('
Expense removed successfully :)
');
            $('#successbox').css('display','block');

            // Load List of Expenses
            $.ajax({
                  url:"/expenses/listing",
                  cache:0,
                  success:function(result){
                         document.getElementById("expenseListing").innerHTML=result;
                   }
            });

            setTimeout(function(){
                $('#successbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);
        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );

            $('#failbox').html('
Error removing expenses :(
');
            $('#failbox').css('display','block');

            setTimeout(function(){
                $('#failbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default posting of form
        event.preventDefault();

    });

    // Refresh list of expenses
    $.ajax({
          url:"/expenses/listing",
          cache:0,
          success:function(result){
                 document.getElementById("expenseListing").innerHTML=result;
           }
    });

    // Get Date
    $(".date-picker").datepicker();
    $(".date-picker").datepicker("option", "dateFormat", "yy-mm-dd");

    $(".date-picker").on("change", function () {
        var id = $(this).attr("id");
        var val = $("label[for='" + id + "']").text();
        $("#msg").text(val + " changed");
    });

    $('#expensesTable tr').click(function(event) {
        $(this).toggleClass('selected');
        if (event.target.type !== 'checkbox') {
          $(':checkbox', this).trigger('click');
        }
    });
});

/*
$(document).ready( function() {
    // Get Date
    $(".date-picker").datepicker();
    $(".date-picker").datepicker("option", "dateFormat", "yy-mm-dd");

    $(".date-picker").on("change", function () {
        var id = $(this).attr("id");
        var val = $("label[for='" + id + "']").text();
        $("#msg").text(val + " changed");
    });
});

$( document ).ready( function() {

    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#manageExpensesForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to form
        request = $.ajax({
            url: "/expenses/delete",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it deleted!");

            $('#successbox').html('
Expense removed successfully :)
');
            $('#successbox').css('display','block');

            setTimeout(function(){
                $('#successbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );

            $('#failbox').html('
Error removing expenses :(
');
            $('#failbox').css('display','block');

            setTimeout(function(){
                $('#failbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default posting of form
        event.preventDefault();

        // Load List of Expenses
        $.ajax({
              url:"/expenses/listing",
              cache:0,
              success:function(result){
                     document.getElementById("expenseListing").innerHTML=result;
               }
        });

    });

});

$(document).ready( function() {
    // Refresh list of expenses
    $.ajax({
          url:"/expenses/listing",
          cache:0,
          success:function(result){
                 document.getElementById("expenseListing").innerHTML=result;
           }
    });
});
*/<commit_msg>haaaands<commit_after>$( document ).ready( function() {

    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#expenseForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, checkbox, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to /form.php
        request = $.ajax({
            url: "/expenses/add",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it added!");

            $('#successbox').html('
Expense added successfully :)
');
            $('#successbox').css('display','block');

            // Load List of Expenses
            $.ajax({
                  url:"/expenses/listing",
                  cache:0,
                  success:function(result){
                         document.getElementById("expenseListing").innerHTML=result;
                   }
            });

            setTimeout(function(){
                $('#successbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );

            $('#failbox').html('
Error adding expenses :(
');
            $('#failbox').css('display','block');

            // Load List of Expenses
            $.ajax({
                  url:"/expenses/listing",
                  cache:0,
                  success:function(result){
                         document.getElementById("expenseListing").innerHTML=result;
                   }
            });

            setTimeout(function(){
                $('#failbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default posting of form
        event.preventDefault();
    });

    // Bind to the submit event of our form
    $("#deleteForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to form
        request = $.ajax({
            url: "/expenses/delete",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it deleted!");

            $('#successbox').html('
Expense removed successfully :)
');
            $('#successbox').css('display','block');

            // Load List of Expenses
            $.ajax({
                  url:"/expenses/listing",
                  cache:0,
                  success:function(result){
                         document.getElementById("expenseListing").innerHTML=result;
                   }
            });

            setTimeout(function(){
                $('#successbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);
        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );

            $('#failbox').html('
Error removing expenses :(
');
            $('#failbox').css('display','block');

            setTimeout(function(){
                $('#failbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default posting of form
        event.preventDefault();

    });

    // Refresh list of expenses
    $.ajax({
          url:"/expenses/listing",
          cache:0,
          success:function(result){
                 document.getElementById("expenseListing").innerHTML=result;
           }
    });

    // Get Date
    $(".date-picker").datepicker();
    $(".date-picker").datepicker("option", "dateFormat", "yy-mm-dd");

    $(".date-picker").on("change", function () {
        var id = $(this).attr("id");
        var val = $("label[for='" + id + "']").text();
        $("#msg").text(val + " changed");
    });

    $('#expensesTable tr').click(function(event) {
        $(this).toggleClass('selected');
        if (event.target.type !== 'checkbox') {
          $(':checkbox', this).trigger('click');
        }
    });
});

/*
$(document).ready( function() {
    // Get Date
    $(".date-picker").datepicker();
    $(".date-picker").datepicker("option", "dateFormat", "yy-mm-dd");

    $(".date-picker").on("change", function () {
        var id = $(this).attr("id");
        var val = $("label[for='" + id + "']").text();
        $("#msg").text(val + " changed");
    });
});

$( document ).ready( function() {

    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#manageExpensesForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to form
        request = $.ajax({
            url: "/expenses/delete",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it deleted!");

            $('#successbox').html('
Expense removed successfully :)
');
            $('#successbox').css('display','block');

            setTimeout(function(){
                $('#successbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );

            $('#failbox').html('
Error removing expenses :(
');
            $('#failbox').css('display','block');

            setTimeout(function(){
                $('#failbox').delay( 2000 ).hide( "drop", { direction: "right" }, "slow" );
            }, 3000);

        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default posting of form
        event.preventDefault();

        // Load List of Expenses
        $.ajax({
              url:"/expenses/listing",
              cache:0,
              success:function(result){
                     document.getElementById("expenseListing").innerHTML=result;
               }
        });

    });

});

$(document).ready( function() {
    // Refresh list of expenses
    $.ajax({
          url:"/expenses/listing",
          cache:0,
          success:function(result){
                 document.getElementById("expenseListing").innerHTML=result;
           }
    });
});
*/<|endoftext|>


<commit_before>$(function() {
	$('#loginForm').submit(function(event) {
		$.ajax({
			data: JSON.stringify({
				username: $('#username').val(),
				password: $('#password').val()
			}),
			url: '/login',
			contentType: 'application/json;charset=UTF-8',
			type: 'POST',
			success: function(response) {
				window.location.replace('/');
			}
		});
		event.preventDefault();
	});

	$('#registerForm').submit(function(event) {
		$.ajax({
			data: JSON.stringify({
				username: $('#registerUsername').val(),
				password: $('#registerPassword').val(),
				email: $('#registerEmail').val()
			}),
			url: '/register',
			contentType: 'application/json;charset=UTF-8',
			type: 'POST',
			success: function(response) {
				window.location.replace('/');
			}
		});
		event.preventDefault();
	});
});<commit_msg>todos<commit_after>$(function() {
	$('#loginForm').submit(function(event) {
		$.ajax({
			data: JSON.stringify({
				username: $('#username').val(),
				password: $('#password').val()
			}),
			url: '/login',
			contentType: 'application/json;charset=UTF-8',
			type: 'POST',
			success: function(response) {
				window.location.replace('/');
				// TODO if response is 201
			}
		});
		event.preventDefault();
	});

	$('#registerForm').submit(function(event) {
		$.ajax({
			data: JSON.stringify({
				username: $('#registerUsername').val(),
				password: $('#registerPassword').val(),
				email: $('#registerEmail').val()
			}),
			url: '/register',
			contentType: 'application/json;charset=UTF-8',
			type: 'POST',
			success: function(response) {
				window.location.replace('/');
				// TODO if response is 201
			}
		});
		event.preventDefault();
	});
});<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

var frandom01 = Math.random;

/**
 * @param {Number} initial
 * @param {Number} walkspeed
 * @param {Number} min
 * @param {Number} max
 */
function scalarRandomWalk( initial, walkspeed, min, max)
{
    var next = initial + (((frandom01() * 2) - 1) * walkspeed);
    if (next < min) { return min; }
    if (next > max) { return max; }
    return next;
}

/**
 * @param {number} alpha
 * @param {number} x0
 * @param {number} x1
 * @returns {number}
 */
function interpolate( alpha, x0, x1 )
{
    return x0 + (( x1 - x0 ) * alpha);
}

/**
 * @param {number} x
 * @param {number} in0
 * @param {number} in1
 * @param {number} out0
 * @param {number} out1
 * @returns {number}
 */
function map( x, in0, in1, out0, out1 )
{
    var relative = (x - in0) / (in1 - in0);

    return interpolate( relative, out0, out1 );
}

function nop(){}

function apply()
{
    var addins = Array.prototype.slice.call(arguments, 0)
      , basic = addins.shift()
      , add
      ;

    for( var i = 0, ii = addins.length; i < ii; ++ i )
    {
        add = addins[i];
        for( var k in add )
        {
            if ( Object.hasOwnProperty.call( add, k ) )
            {
                basic[k] = add[k];
            }
        }
    }

    return basic;
}

function applyIf()
{
    var addins = Array.prototype.slice.call(arguments, 0)
      , basic = addins.shift()
      , add
      ;

    for( var i = 0, ii = addins.length; i < ii; ++ i )
    {
        add = addins[i];
        for( var k in add )
        {
            if ( !Object.hasOwnProperty.call( basic, k ) && Object.hasOwnProperty.call( add, k ) )
            {
                basic[k] = add[k];
            }
        }
    }

    return basic;
}

function abstract()
{
    throw "Abstract method has to be implemented in subclass";
}

/**
 * @param {Function} [base] class to apply from
 * @param {Object} child definition of class methods and properties
 * @return {Function} the created class
 */
function clazz( base, child )
{
    if( !child )
    {
        child = base;
        base = nop;
    }

    if ( !Object.hasOwnProperty.call(child, "constructor" ) )
    {
        child.constructor = function()
        {
            base.apply(this, arguments);
        };
    }

    var cls = child.constructor
      , $super = base.prototype
      , cp = cls.prototype = Object.create( $super )
      ;

    apply( cp, $super );
    apply( cp, child );

    return cls;
}

if ( typeof define !== 'function' ) {
    /*jshint latedef:false */
    var define = require( 'amdefine' )( module );
}

define( function( require ) {
    'use strict';
    return {
        frandom01: frandom01,
        scalarRandomWalk: scalarRandomWalk,
        interpolate: interpolate,
        map: map,
        nop: nop,
        apply: apply,
        applyIf: applyIf,
        clazz: clazz,
        abstract: abstract
    };
});<commit_msg> - fixed jshint issue<commit_after>/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

var frandom01 = Math.random;

/**
 * @param {Number} initial
 * @param {Number} walkspeed
 * @param {Number} min
 * @param {Number} max
 */
function scalarRandomWalk( initial, walkspeed, min, max)
{
    var next = initial + (((frandom01() * 2) - 1) * walkspeed);
    if (next < min) { return min; }
    if (next > max) { return max; }
    return next;
}

/**
 * @param {number} alpha
 * @param {number} x0
 * @param {number} x1
 * @returns {number}
 */
function interpolate( alpha, x0, x1 )
{
    return x0 + (( x1 - x0 ) * alpha);
}

/**
 * @param {number} x
 * @param {number} in0
 * @param {number} in1
 * @param {number} out0
 * @param {number} out1
 * @returns {number}
 */
function map( x, in0, in1, out0, out1 )
{
    var relative = (x - in0) / (in1 - in0);

    return interpolate( relative, out0, out1 );
}

function nop(){}

function apply()
{
    var addins = Array.prototype.slice.call(arguments, 0)
      , basic = addins.shift()
      , add
      ;

    for( var i = 0, ii = addins.length; i < ii; ++ i )
    {
        add = addins[i];
        for( var k in add )
        {
            if ( Object.hasOwnProperty.call( add, k ) )
            {
                basic[k] = add[k];
            }
        }
    }

    return basic;
}

function applyIf()
{
    var addins = Array.prototype.slice.call(arguments, 0)
      , basic = addins.shift()
      , add
      ;

    for( var i = 0, ii = addins.length; i < ii; ++ i )
    {
        add = addins[i];
        for( var k in add )
        {
            if ( !Object.hasOwnProperty.call( basic, k ) && Object.hasOwnProperty.call( add, k ) )
            {
                basic[k] = add[k];
            }
        }
    }

    return basic;
}

function abstract()
{
    throw "Abstract method has to be implemented in subclass";
}

/**
 * @param {Function} [base] class to apply from
 * @param {Object} child definition of class methods and properties
 * @return {Function} the created class
 */
function clazz( base, child )
{
    if( !child )
    {
        child = base;
        base = nop;
    }

    if ( !Object.hasOwnProperty.call(child, "constructor" ) )
    {
        child.constructor = function()
        {
            base.apply(this, arguments);
        };
    }

    var cls = child.constructor
      , $super = base.prototype
      , cp = cls.prototype = Object.create( $super )
      ;

    apply( cp, $super );
    apply( cp, child );

    return cls;
}

if ( typeof define !== 'function' ) {
    /*jshint latedef:false */
    var define = require( 'amdefine' )( module );
}

define( function() {
    'use strict';
    return {
        frandom01: frandom01,
        scalarRandomWalk: scalarRandomWalk,
        interpolate: interpolate,
        map: map,
        nop: nop,
        apply: apply,
        applyIf: applyIf,
        clazz: clazz,
        abstract: abstract
    };
});<|endoftext|>


<commit_before>import path from 'path';
import _ from 'lodash';
import async from 'async';
import log from 'loglevel';
import sanitizeFilenameLib from 'sanitize-filename';

import inferIcon from './../infer/inferIcon';
import inferTitle from './../infer/inferTitle';
import inferOs from './../infer/inferOs';
import inferUserAgent from './../infer/inferUserAgent';
import normalizeUrl from './normalizeUrl';
import packageJson from './../../package.json';

const {inferPlatform, inferArch} = inferOs;

const PLACEHOLDER_APP_DIR = path.join(__dirname, '../../', 'app');
const ELECTRON_VERSION = '0.37.2';

const DEFAULT_APP_NAME = 'APP';

/**
 * @callback optionsCallback
 * @param error
 * @param options augmented options
 */

/**
 * Extracts only desired keys from inpOptions and augments it with defaults
 * @param inpOptions
 * @param {optionsCallback} callback
 */
function optionsFactory(inpOptions, callback) {

    const options = {
        dir: PLACEHOLDER_APP_DIR,
        name: inpOptions.name,
        targetUrl: normalizeUrl(inpOptions.targetUrl),
        platform: inpOptions.platform || inferPlatform(),
        arch: inpOptions.arch || inferArch(),
        version: inpOptions.electronVersion || ELECTRON_VERSION,
        nativefierVersion: packageJson.version,
        out: inpOptions.out || process.cwd(),
        overwrite: inpOptions.overwrite,
        asar: inpOptions.conceal || false,
        icon: inpOptions.icon,
        counter: inpOptions.counter || false,
        width: inpOptions.width || 1280,
        height: inpOptions.height || 800,
        showMenuBar: inpOptions.showMenuBar || false,
        userAgent: inpOptions.userAgent,
        ignoreCertificate: inpOptions.ignoreCertificate || false,
        insecure: inpOptions.insecure || false,
        flashPluginDir: inpOptions.flashPath || inpOptions.flash || null,
        inject: inpOptions.inject || null,
        ignore: 'src',
        fullScreen: inpOptions.fullScreen || false,
        maximize: inpOptions.maximize || false,
        verbose: inpOptions.verbose
    };

    if (options.verbose) {
        log.setLevel('trace');
    } else {
        log.setLevel('error');
    }

    if (options.flashPluginDir) {
        options.insecure = true;
    }

    if (inpOptions.honest) {
        options.userAgent = null;
    }

    if (options.platform.toLowerCase() === 'windows') {
        options.platform = 'win32';
    }

    if (options.platform.toLowerCase() === 'osx' || options.platform.toLowerCase() === 'mac') {
        options.platform = 'darwin';
    }

    async.waterfall([
        callback => {
            if (options.userAgent) {
                callback();
                return;
            }
            inferUserAgent(options.version, options.platform)
                .then(userAgent => {
                    options.userAgent = userAgent;
                    callback();
                })
                .catch(callback);
        },
        callback => {
            if (options.icon) {
                callback();
                return;
            }
            inferIcon(options.targetUrl, options.platform)
                .then(pngPath => {
                    options.icon = pngPath;
                    callback();
                })
                .catch(error => {
                    log.warn('Cannot automatically retrieve the app icon:', error);
                    callback();
                });
        },
        callback => {
            // length also checks if its the commanderJS function or a string
            if (options.name && options.name.length > 0) {
                callback();
                return;
            }

            inferTitle(options.targetUrl, function(error, pageTitle) {
                if (error) {
                    log.warn(`Unable to automatically determine app name, falling back to '${DEFAULT_APP_NAME}'`);
                    options.name = DEFAULT_APP_NAME;
                } else {
                    options.name = pageTitle.trim();
                }
                if (options.platform === 'linux') {
                    // spaces will cause problems with Ubuntu when pinned to the dock
                    options.name = _.kebabCase(options.name);
                }
                callback();
            });
        }
    ], error => {
        callback(error, sanitizeOptions(options));
    });
}

function sanitizeFilename(str) {
    const cleaned = sanitizeFilenameLib(str);
    // remove non ascii
    return cleaned.replace(/[^\x00-\x7F]/, '');
}

function sanitizeOptions(options) {
    options.name = sanitizeFilename(options.name);
    return options;
}

export default optionsFactory;
<commit_msg>Add an option to hide window frame<commit_after>import path from 'path';
import _ from 'lodash';
import async from 'async';
import log from 'loglevel';
import sanitizeFilenameLib from 'sanitize-filename';

import inferIcon from './../infer/inferIcon';
import inferTitle from './../infer/inferTitle';
import inferOs from './../infer/inferOs';
import inferUserAgent from './../infer/inferUserAgent';
import normalizeUrl from './normalizeUrl';
import packageJson from './../../package.json';

const {inferPlatform, inferArch} = inferOs;

const PLACEHOLDER_APP_DIR = path.join(__dirname, '../../', 'app');
const ELECTRON_VERSION = '0.37.2';

const DEFAULT_APP_NAME = 'APP';

/**
 * @callback optionsCallback
 * @param error
 * @param options augmented options
 */

/**
 * Extracts only desired keys from inpOptions and augments it with defaults
 * @param inpOptions
 * @param {optionsCallback} callback
 */
function optionsFactory(inpOptions, callback) {

    const options = {
        dir: PLACEHOLDER_APP_DIR,
        name: inpOptions.name,
        targetUrl: normalizeUrl(inpOptions.targetUrl),
        platform: inpOptions.platform || inferPlatform(),
        arch: inpOptions.arch || inferArch(),
        version: inpOptions.electronVersion || ELECTRON_VERSION,
        nativefierVersion: packageJson.version,
        out: inpOptions.out || process.cwd(),
        overwrite: inpOptions.overwrite,
        asar: inpOptions.conceal || false,
        icon: inpOptions.icon,
        counter: inpOptions.counter || false,
        width: inpOptions.width || 1280,
        height: inpOptions.height || 800,
        showMenuBar: inpOptions.showMenuBar || false,
        userAgent: inpOptions.userAgent,
        ignoreCertificate: inpOptions.ignoreCertificate || false,
        insecure: inpOptions.insecure || false,
        flashPluginDir: inpOptions.flashPath || inpOptions.flash || null,
        inject: inpOptions.inject || null,
        ignore: 'src',
        fullScreen: inpOptions.fullScreen || false,
        maximize: inpOptions.maximize || false,
        hideWindowFrame: inpOptions.hideWindowFrame,
        verbose: inpOptions.verbose
    };

    if (options.verbose) {
        log.setLevel('trace');
    } else {
        log.setLevel('error');
    }

    if (options.flashPluginDir) {
        options.insecure = true;
    }

    if (inpOptions.honest) {
        options.userAgent = null;
    }

    if (options.platform.toLowerCase() === 'windows') {
        options.platform = 'win32';
    }

    if (options.platform.toLowerCase() === 'osx' || options.platform.toLowerCase() === 'mac') {
        options.platform = 'darwin';
    }

    async.waterfall([
        callback => {
            if (options.userAgent) {
                callback();
                return;
            }
            inferUserAgent(options.version, options.platform)
                .then(userAgent => {
                    options.userAgent = userAgent;
                    callback();
                })
                .catch(callback);
        },
        callback => {
            if (options.icon) {
                callback();
                return;
            }
            inferIcon(options.targetUrl, options.platform)
                .then(pngPath => {
                    options.icon = pngPath;
                    callback();
                })
                .catch(error => {
                    log.warn('Cannot automatically retrieve the app icon:', error);
                    callback();
                });
        },
        callback => {
            // length also checks if its the commanderJS function or a string
            if (options.name && options.name.length > 0) {
                callback();
                return;
            }

            inferTitle(options.targetUrl, function(error, pageTitle) {
                if (error) {
                    log.warn(`Unable to automatically determine app name, falling back to '${DEFAULT_APP_NAME}'`);
                    options.name = DEFAULT_APP_NAME;
                } else {
                    options.name = pageTitle.trim();
                }
                if (options.platform === 'linux') {
                    // spaces will cause problems with Ubuntu when pinned to the dock
                    options.name = _.kebabCase(options.name);
                }
                callback();
            });
        }
    ], error => {
        callback(error, sanitizeOptions(options));
    });
}

function sanitizeFilename(str) {
    const cleaned = sanitizeFilenameLib(str);
    // remove non ascii
    return cleaned.replace(/[^\x00-\x7F]/, '');
}

function sanitizeOptions(options) {
    options.name = sanitizeFilename(options.name);
    return options;
}

export default optionsFactory;
<|endoftext|>


<commit_before>/* eslint-disable react/require-default-props */
/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2018
 */

import React from 'react';
import { View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import { ReportSideBar } from '../widgets/ReportSideBar';
import { ReportChart } from '../widgets/ReportChart';

import globalStyles from '../globalStyles';
import { DashboardActions } from '../actions/index';

const DashboardPageComponent = ({ reports, currentReport, switchReport }) => {
  const { pageContentContainer, container, pageTopSectionContainer } = globalStyles;
  const pageContainer = StyleSheet.flatten([pageTopSectionContainer, { paddingHorizontal: 0 }]);

  return (
    <View style={pageContentContainer}>
      <View style={container}>
        <View style={pageContainer}>
          <ReportSideBar
            reports={reports}
            onPressItem={switchReport}
            currentReport={currentReport}
            dimensions={localStyles.sidebarDimensions}
          />
          <ReportChart report={currentReport} />
        </View>
      </View>
    </View>
  );
};

const localStyles = StyleSheet.create({
  sidebarDimensions: {
    width: '25%',
    height: '100%',
  },
});

const mapStateToProps = state => {
  const { dashboard } = state;
  const { reports, currentReport } = dashboard;
  return { reports, currentReport };
};

const mapDispatchToProps = dispatch => {
  const switchReport = report => dispatch(DashboardActions.switchReport(report));
  return { dispatch, switchReport };
};

DashboardPageComponent.defaultProps = {
  currentReport: null,
};

DashboardPageComponent.propTypes = {
  reports: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
  currentReport: PropTypes.object,
  switchReport: PropTypes.func.isRequired,
};

export const DashboardPage = connect(mapStateToProps, mapDispatchToProps)(DashboardPageComponent);
<commit_msg>No reports message added<commit_after>/* eslint-disable react/require-default-props */
/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2018
 */

import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import { ReportSideBar } from '../widgets/ReportSideBar';
import { ReportChart } from '../widgets/ReportChart';

import globalStyles from '../globalStyles';

import { DashboardActions } from '../actions/index';

const DashboardPageComponent = ({ reports, currentReport, switchReport }) => {
  const { pageContentContainer, container, pageTopSectionContainer } = globalStyles;
  const pageContainer = StyleSheet.flatten([pageTopSectionContainer, { paddingHorizontal: 0 }]);

  if (reports.length) {
    return (
      <View style={pageContentContainer}>
        <View style={container}>
          <View style={pageContainer}>
            <ReportSideBar
              reports={reports}
              onPressItem={switchReport}
              currentReport={currentReport}
              dimensions={localStyles.sidebarDimensions}
            />
            <ReportChart report={currentReport} />
          </View>
        </View>
      </View>
    );
  }
  return (
    <View style={pageContentContainer}>
      <View style={container}>
        <View style={localStyles.centeredText}>
          <Text style={localStyles.noReportsText}>No Reports to show</Text>
        </View>
      </View>
    </View>
  );
};

const localStyles = StyleSheet.create({
  sidebarDimensions: {
    width: '25%',
    height: '100%',
  },
  centeredText: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noReportsText: {
    fontFamily: globalStyles.APP_FONT_FAMILY,
    color: globalStyles.GREY,
    fontWeight: 'bold',
    fontSize: 20,
  },
});

const mapStateToProps = state => {
  const { dashboard } = state;
  const { reports, currentReport } = dashboard;
  return { reports, currentReport };
};

const mapDispatchToProps = dispatch => {
  const switchReport = report => dispatch(DashboardActions.switchReport(report));
  return { dispatch, switchReport };
};

DashboardPageComponent.defaultProps = {
  currentReport: null,
};

DashboardPageComponent.propTypes = {
  reports: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
  currentReport: PropTypes.object,
  switchReport: PropTypes.func.isRequired,
};

export const DashboardPage = connect(mapStateToProps, mapDispatchToProps)(DashboardPageComponent);
<|endoftext|>


<commit_before>import React, { Fragment } from 'react';
import PropTypes from 'prop-types';

import Header from '../components/Header';
import Body from '../components/Body';
import Footer from '../components/Footer';

import withData from '../lib/withData';
import withIntl from '../lib/withIntl';
import withLoggedInUser from '../lib/withLoggedInUser';

import sponsorPageHtml from '../static/sponsor-page/index.html';
import sponsorPageScript from '../static/sponsor-page/js/scripts.js';
import sponsorPageStyle from '../static/sponsor-page/css/styles.css';

class MarketingPage extends React.Component {
  static getInitialProps({ query: { pageSlug } }) {
    return { pageSlug };
  }

  static propTypes = {
    getLoggedInUser: PropTypes.func.isRequired, // from withLoggedInUser
    pageSlug: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  async componentDidMount() {
    this.props.getLoggedInUser().then(LoggedInUser => {
      this.setState({ LoggedInUser });
    });
  }

  render() {
    const { pageSlug } = this.props;
    const { LoggedInUser } = this.state;

    let html, script, style, className;

    if (pageSlug === 'become-a-sponsor') {
      html = sponsorPageHtml;
      script = sponsorPageScript;
      style = sponsorPageStyle;
      className = 'sponsorPage';
    }

    return (
      <Fragment>


<commit_before>const Autoloader = require('specla-autoloader');
require('colors');

const help = {
  name: 'help',
  description: 'Print the help manual',

  handle(){
    console.log(`\n ${'{'.gray.bold} ${'Specla'.bold} ${'}'.gray.bold}`, ` v${packageInfo.version}\n`);

    this.printUsage();
    this.printOptions();
    this.printCommands();
  },

  printUsage(){
    console.log(` Usage:`.gray);
    console.log(`   specla [command] [options] [arguments] \n`);
  },

  printOptions(){
    console.log(` Available Options:`.gray);
    console.log(`   -h, --help   Get help`);
    console.log(``);
  },

  printCommands(){

    console.log(` Available Commands:`.gray);

    let commands = new Autoloader(['../../commands'])
      .setRootDir(__dirname)
      .namespaced()['..']['..']
      .commands;

    for(let command in commands){
      console.log(`   # ${command}`);
      this.getCommand(commands[command]);
    }
  },

  getCommand(command){
    if(command.name === undefined){
      return this.getSubCommand(command);
    }

    console.log(`      ${command.name}`);
  },

  getSubCommand(commands){
    for(let command in commands){
      this.getCommand(commands[command]);
    }
  },
};

module.exports = help;
<commit_msg>Added colors<commit_after>const Autoloader = require('specla-autoloader');
const pkgInfo = require('../../../package.json');
require('colors');

const help = {
  name: 'help',
  description: 'Print the help manual',

  handle(){
    console.log(`\n ${'{'.gray.bold} ${'Specla'.bold} ${'}'.gray.bold}`, ` v${pkgInfo.version}\n`);

    this.printUsage();
    this.printOptions();
    this.printCommands();
  },

  printUsage(){
    console.log(` Usage:`.gray);
    console.log(`   specla [command] [options] [arguments] \n`);
  },

  printOptions(){
    console.log(` Available Options:`.gray);
    console.log(`   -h, --help   Get help`);
    console.log(``);
  },

  printCommands(){

    console.log(` Available Commands:`.gray);

    let commands = new Autoloader(['../../commands'])
      .setRootDir(__dirname)
      .namespaced()['..']['..']
      .commands;

    for(let command in commands){
      console.log(`   # ${command}`);
      this.getCommand(commands[command]);
    }
  },

  getCommand(command){
    if(command.name === undefined){
      return this.getSubCommand(command);
    }

    console.log(`      ${command.name}`);
  },

  getSubCommand(commands){
    for(let command in commands){
      this.getCommand(commands[command]);
    }
  },
};

module.exports = help;
<|endoftext|>


<commit_before>import * as actions from '../../actions';
import { acceptSequenceDeletion } from './acceptSequenceDeletion';
import { disablePartLooping } from './disablePartLooping';
import { disposePart } from './disposePart';
import { reloadSequence } from './reloadSequence';
import { setPartEventsByNoteId } from './setPartEventsByNoteId';
import { setPartEvents } from './setPartEvents';
import { startPart } from './startPart';
import { stopPart } from './stopPart';

export default function effects(getState, action, shared) {
  switch (action.type) {
    case actions.NOTE_ADDED:
    case actions.NOTE_DELETED:
    case actions.NOTE_POINT_ADDED:
    case actions.NOTE_POINT_DELETED:
    case actions.NOTE_POINT_X_EDITED:
    case actions.NOTE_POINT_Y_EDITED:
      setPartEventsByNoteId(getState, action, shared);
      break;
    case actions.SEQUENCE_ADDED:
      setPartEvents(getState, action, shared);
      startPart(getState, action, shared);
      disablePartLooping(getState, action, shared);
      break;
    case actions.SEQUENCE_DELETION_REQUESTED:
      disposePart(getState, action, shared);
      acceptSequenceDeletion(getState, action, shared);
      break;
    case actions.SEQUENCE_MEASURE_COUNT_EDITED:
      reloadSequence(getState, action, shared);
      break;
    case actions.SEQUENCE_POSITION_EDITED:
      stopPart(getState, action, shared);
      startPart(getState, action, shared);
      disablePartLooping(getState, action, shared);
      break;
    default:
  }
}
<commit_msg>fix: Update handling of SEQUENCE_POSITION_EDITED to work properly.<commit_after>import * as actions from '../../actions';
import { acceptSequenceDeletion } from './acceptSequenceDeletion';
import { disablePartLooping } from './disablePartLooping';
import { disposePart } from './disposePart';
import { reloadSequence } from './reloadSequence';
import { setPartEventsByNoteId } from './setPartEventsByNoteId';
import { setPartEvents } from './setPartEvents';
import { startPart } from './startPart';

export default function effects(getState, action, shared) {
  switch (action.type) {
    case actions.NOTE_ADDED:
    case actions.NOTE_DELETED:
    case actions.NOTE_POINT_ADDED:
    case actions.NOTE_POINT_DELETED:
    case actions.NOTE_POINT_X_EDITED:
    case actions.NOTE_POINT_Y_EDITED:
      setPartEventsByNoteId(getState, action, shared);
      break;
    case actions.SEQUENCE_ADDED:
      setPartEvents(getState, action, shared);
      startPart(getState, action, shared);
      disablePartLooping(getState, action, shared);
      break;
    case actions.SEQUENCE_DELETION_REQUESTED:
      disposePart(getState, action, shared);
      acceptSequenceDeletion(getState, action, shared);
      break;
    case actions.SEQUENCE_MEASURE_COUNT_EDITED:
      reloadSequence(getState, action, shared);
      break;
    case actions.SEQUENCE_POSITION_EDITED:
      reloadSequence(getState, action, shared);
      break;
    default:
  }
}
<|endoftext|>


<commit_before>var userIds = ['GeorgMeier'].map(u => u.toLowerCase());
var perfType = 'bullet';
var perf = {
  "gl": {
    "r": 2500,
    "d": 150,
    "v": 0.06
  },
  "nb": NumberInt(0),
  "re": [ ]
};

userIds.forEach(id => {
  var user = db.user4.findOne({_id:id});
  if (user && (!user.perfs[perfType] || !user.perfs[perfType].nb))
    db.user4.update({_id:id},{$set:{['perfs.' + perfType]: perf}});
  db.tournament_player.update(
    {uid:id,r:1500,m:1500},
    {$set:{r:NumberInt(perf.gl.r),m:NumberInt(perf.gl.r)}},
    {multi:1});
});
<commit_msg>tweak gm bootstrap script<commit_after>var userIds = ['sasha'].map(u => u.toLowerCase());
var perfTypes = ['bullet', 'blitz', 'rapid', 'classical'];
var perf = {
  "gl": {
    "r": 2700,
    "d": 150,
    "v": 0.06
  },
  "nb": NumberInt(0),
  "re": [ ]
};
var updateTournaments = false;

userIds.forEach(id => {
  var user = db.user4.findOne({_id:id});
  perfTypes.forEach(pt => {
    if (user && (!user.perfs[pt] || !user.perfs[pt].nb))
      db.user4.update({_id:id},{$set:{['perfs.' + pt]: perf}});
  });
  if (updateTournaments) db.tournament_player.update(
    {uid:id,r:1500,m:1500},
    {$set:{r:NumberInt(perf.gl.r),m:NumberInt(perf.gl.r)}},
    {multi:1});
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const async = require('async');
const ms = require('ms');
const storj = require('storj-lib');
const program = require('commander');
const Config = require('../lib/config');
const Storage = require('storj-service-storage-models');
const { Client: ComplexClient } = require('storj-complex');

program.version(require('../package').version);
program.option('-c, --config <path_to_config_file>', 'path to the config file');
program.option('-d, --datadir <path_to_datadir>', 'path to the data directory');
program.parse(process.argv);

const logger = require('../lib/logger');
const config = new Config(process.env.NODE_ENV || 'develop', program.config,
                          program.datadir);
const { mongoUrl, mongoOpts } = config.storage;
const storage = new Storage(mongoUrl, mongoOpts, { logger });
const network = new ComplexClient(config.complex);
const cursor = storage.models.Shard.find({}).cursor();
const counter = { processed: 0, renewed: 0, errored: 0 };

const NOW = Date.now();
const HOURS_24 = ms('24h');

cursor
  .on('error', handleCursorError)
  .on('data', handleCursorData)
  .on('close', handleCursorClose);

/**
 * Prints the error and continues processing cursor
 * @function
 * @param {error} error
 */
function handleCursorError(err) {
  logger.warn(err.message);
}

/**
 * Prints close event + cleanup + report
 * @function
 */
function handleCursorClose() {
  logger.info('shard renewal job completed');
  logger.info('total contracts processed: %i', counter.processed);
  logger.info('total contracts renewwed: %i', counter.renewed);
  logger.info('total contracts errored: %i', counter.errored);
}

/**
 * Inspects the contract to ensure it's still valid and in use
 * If the end time is within 24 hours, renew it for another 3 months
 * @function
 * @param {object} shard
 */
function handleCursorData(shard) {
  let needsRenewal = [];

  cursor.pause();

  for (let contractInfo of shard.contracts) {
    let { contract: contractObj, nodeID } = contractInfo;
    let contract = new storj.Contract(contractObj);
    let willExpireNext24 = (contract.get('store_end') - HOURS_24) <= NOW;

    if (willExpireNext24) {
      needsRenewal.push([nodeID, contract]);
    }
  }

  let renewalContracts = needsRenewal.map(([nodeId, contract]) => {
    contract.set('store_begin', NOW);
    contract.set('store_end', NOW + ms('90d'));

    return [nodeId, contract];
  });

  async.map(renewalContracts, lookupFarmer, maybeRenewContracts);
}

function lookupFarmer([nodeId, contract], next) {
  storage.models.Contact.findOne({ _id: nodeId }, (err, contact) => {
    if (err || !contact) {
      counter.errored++;
      return next(null, null);
    }

    next(null , [storj.Contact(contact.toObject()), contract]);
  });
}

function maybeRenewContracts(err, results) {
  let canBeRenewed = results.filter((result) => !!result);

  async.parallelLimit(canBeRenewed, 6, checkIfNeedsRenew,
                      () => cursor.resume());
}

function finishProcessingContract(done) {
  counter.processed++;
  done();
}

function checkIfNeedsRenew([contact, contract], done) {
  let shardHash = contract.get('data_hash');

  async.waterfall(
    [
      (next) => getPointerObjects(shardHash, next),
      (pointers, next) => getAssociatedFrames(pointers, next),
      (frames, next) => getParentBucketEntries(frames, next),
      (entries, next) => renewContract([contact, contract], entries, next)
    ],
    () => finishProcessingContract(done)
  );
}

function getPointerObjects(shardHash, next) {
  storage.models.Pointer.find({ hash: shardHash }, (err, pointers) => {
    next(err || pointers.length === 0, pointers);
  });
}

function getAssociatedFrames(pointers, next) {
  storage.models.Frame.find({
    $in: {
      pointers: pointers.map((pointer) => pointer._id)
    }
  }, (err, frames) => {
    next(err || frames.length === 0, frames);
  });
}

function getParentBucketEntries(frames, next) {
  storage.models.BucketEntry.find({
    $in: {
      frame: frames.map((frame) => frame._id)
    }
  }, (err, entries) => {
    next(err || entries === 0, entries);
  });
}

function renewContract([contact, contract], entries, next) {
  network.renewContract(contract, contact, (err) => {
    if (err) {
      counter.errored++;
    } else {
      counter.renewed++;
    }

    next();
  });
}
<commit_msg>update cursor query<commit_after>#!/usr/bin/env node

'use strict';

const async = require('async');
const ms = require('ms');
const storj = require('storj-lib');
const program = require('commander');
const Config = require('../lib/config');
const Storage = require('storj-service-storage-models');
const { Client: ComplexClient } = require('storj-complex');

program.version(require('../package').version);
program.option('-c, --config <path_to_config_file>', 'path to the config file');
program.option('-d, --datadir <path_to_datadir>', 'path to the data directory');
program.parse(process.argv);

const NOW = Date.now();
const HOURS_24 = ms('24h');

const logger = require('../lib/logger');
const config = new Config(process.env.NODE_ENV || 'develop', program.config,
                          program.datadir);
const { mongoUrl, mongoOpts } = config.storage;
const storage = new Storage(mongoUrl, mongoOpts, { logger });
const network = new ComplexClient(config.complex);
const cursor = storage.models.Shard.find({
  $gte: { 'contracts.contract.store_end': NOW - HOURS_24 },
  $lte: { 'contracts.contract.store_end': NOW + HOURS_24 }
}).cursor();
const counter = { processed: 0, renewed: 0, errored: 0 };

cursor
  .on('error', handleCursorError)
  .on('data', handleCursorData)
  .on('close', handleCursorClose);

/**
 * Prints the error and continues processing cursor
 * @function
 * @param {error} error
 */
function handleCursorError(err) {
  logger.warn(err.message);
}

/**
 * Prints close event + cleanup + report
 * @function
 */
function handleCursorClose() {
  logger.info('shard renewal job completed');
  logger.info('total contracts processed: %i', counter.processed);
  logger.info('total contracts renewwed: %i', counter.renewed);
  logger.info('total contracts errored: %i', counter.errored);
}

/**
 * Inspects the contract to ensure it's still valid and in use
 * If the end time is within 24 hours, renew it for another 3 months
 * @function
 * @param {object} shard
 */
function handleCursorData(shard) {
  let needsRenewal = [];

  cursor.pause();

  for (let contractInfo of shard.contracts) {
    let { contract: contractObj, nodeID } = contractInfo;
    let contract = new storj.Contract(contractObj);
    let willExpireNext24 = (contract.get('store_end') - HOURS_24) <= NOW;

    if (willExpireNext24) {
      needsRenewal.push([nodeID, contract]);
    }
  }

  let renewalContracts = needsRenewal.map(([nodeId, contract]) => {
    contract.set('store_begin', NOW);
    contract.set('store_end', NOW + ms('90d'));

    return [nodeId, contract];
  });

  async.map(renewalContracts, lookupFarmer, maybeRenewContracts);
}

function lookupFarmer([nodeId, contract], next) {
  storage.models.Contact.findOne({ _id: nodeId }, (err, contact) => {
    if (err || !contact) {
      counter.errored++;
      return next(null, null);
    }

    next(null , [storj.Contact(contact.toObject()), contract]);
  });
}

function maybeRenewContracts(err, results) {
  let canBeRenewed = results.filter((result) => !!result);

  async.parallelLimit(canBeRenewed, 6, checkIfNeedsRenew,
                      () => cursor.resume());
}

function finishProcessingContract(done) {
  counter.processed++;
  done();
}

function checkIfNeedsRenew([contact, contract], done) {
  let shardHash = contract.get('data_hash');

  async.waterfall(
    [
      (next) => getPointerObjects(shardHash, next),
      (pointers, next) => getAssociatedFrames(pointers, next),
      (frames, next) => getParentBucketEntries(frames, next),
      (entries, next) => renewContract([contact, contract], entries, next)
    ],
    () => finishProcessingContract(done)
  );
}

function getPointerObjects(shardHash, next) {
  storage.models.Pointer.find({ hash: shardHash }, (err, pointers) => {
    next(err || pointers.length === 0, pointers);
  });
}

function getAssociatedFrames(pointers, next) {
  storage.models.Frame.find({
    $in: {
      pointers: pointers.map((pointer) => pointer._id)
    }
  }, (err, frames) => {
    next(err || frames.length === 0, frames);
  });
}

function getParentBucketEntries(frames, next) {
  storage.models.BucketEntry.find({
    $in: {
      frame: frames.map((frame) => frame._id)
    }
  }, (err, entries) => {
    next(err || entries === 0, entries);
  });
}

function renewContract([contact, contract], entries, next) {
  network.renewContract(contract, contact, (err) => {
    if (err) {
      counter.errored++;
    } else {
      counter.renewed++;
    }

    next();
  });
}
<|endoftext|>