<commit_before>(function( $ ) {
    $.fn.datatableify = function(options) {
        var $this = $(this);

        var dataTable;
        var dataTableOptions = $.extend({
            searching: true,
            responsive: true,

            // Shortcut variables
            ajaxLoadUrl: null,
            ajaxOrderUrl: null
        }, options);

        var cols = [];
        var firstColumn = 0;

        // Gather column information from thead
        $this.find('thead tr th').each(function (k, v) {
            if ($(v).data('datatable-ignore')) {
                cols.push({
                    data: 'selection',
                    searchable: false,
                    searchType: 'normal',
                    sortable: false,
                    className: $(v).data('datatable-class')
                });
                firstColumn += 1;
            } else {
                cols.push({
                    data: $(v).data('datatable-id'),
                    name: $(v).data('datatable-name'),
                    searchable: $(v).data('datatable-searchable'),
                    searchType: $(v).data('datatable-search-type'),
                    searchCustom: $(v).data('datatable-search-custom'),
                    searchOptions: $(v).data('datatable-search-options'),
                    sortable: $(v).data('datatable-sortable'),
                    className: $(v).data('datatable-class')
                });
            }
        });

        dataTableOptions.columns = cols;
        dataTableOptions.order = [[firstColumn, "desc"]];

        // Ajax server side table
        if ($(this).data('datatableAjaxLoadUrl')) {
            dataTableOptions.ajaxLoadUrl = $(this).data('datatableAjaxLoadUrl');
        }

        if (dataTableOptions.ajaxLoadUrl != null) {
            dataTableOptions.processing = true;
            dataTableOptions.serverSide = true;
            dataTableOptions.ajax = {
                url: dataTableOptions.ajaxLoadUrl,
                data: function (d) {
                    $('.datatable-filter').each(function (k, v) {
                        if (!$(v).is(':checkbox') || ($(v).is(':checkbox') && $(v).is(':checked'))) {
                            var name = $(v).prop('name');
                            var value = $(v).val();

                            d[name] = value;
                        }
                    });
                }
            };
        }

        // Disable paging for order table
        if (dataTableOptions.ajaxOrderUrl != null) {
            dataTableOptions.rowReorder = true;
            dataTableOptions.paging = false;
        }

        dataTable = $this.DataTable(dataTableOptions);

        // Build Search Header
        $this.find('thead').append('

');
        $this.find('thead th').each(function (k, v) {
            if (cols[k]['searchable'] != false) {
                if (cols[k]['searchType'] == 'select' && typeof cols[k]['searchOptions'] == 'object' && Object.keys(cols[k]['searchOptions']).length > 0) {
                    $this.find('.thead-search').append('<select style="width: 100%" class="simple-search-field select_' + cols[k]['data'] + '"></select>	');
                    $this.find('.select_' + cols[k]['data']).append('<option value=""></option>');

                    for (var i in cols[k]['searchOptions']) {
                        $this.find('.select_' + cols[k]['data']).append('<option value="' + i + '">' + cols[k]['searchOptions'][i] + '</option>');
                    }
                } else if (cols[k]['searchType'] == 'date-range') {
                    $this.find('.thead-search').append('<input type="text" placeholder="From" style="width: 50%" class="date-range-search-field datepicker datatable-filter" name="' + cols[k]['data'] + '_from"/><input type="text" placeholder="To" style="width: 50%" class="date-range-search-field datepicker datatable-filter" name="' + cols[k]['data'] + '_to"/>	');
                } else if (cols[k]['searchType'] == 'date') {
                    $this.find('.thead-search').append('<input type="text" placeholder="" style="width: 100%" class="simple-search-field datepicker"/>	');
                } else if (cols[k]['searchType'] == 'custom') {
                    $this.find('.thead-search').append('' + $(cols[k]['searchCustom']).html() + '	');
                } else {
                    $this.find('.thead-search').append('<input type="text" placeholder="" style="width: 100%" class="simple-search-field"/>	');
                }
            } else {
                $this.find('.thead-search').append('	');
            }
        });

        // Apply the search
        dataTable.columns().every(function () {
            var that = this;
            var search_header = $this.find('.thead-search td:nth-child(' + parseInt(this.index() + 1) + ')');

            $('input.simple-search-field, select.simple-search-field', search_header).on('keyup change', function () {
                that
                    .search(this.value)
                    .draw();
            });
        });

        // Responsive Table
        dataTable.on('responsive-resize', function (e, datatable, columns) {
            for (i in columns) {
                if (columns[i])
                    $this.find('.thead-search td:nth-child(' + i + ')').show();
                else
                    $this.find('.thead-search td:nth-child(' + i + ')').hide();
            }
        });

        // Row Reorder
        if ($(this).data('datatableAjaxOrderUrl')) {
            dataTableOptions.ajaxOrderUrl = $(this).data('datatableAjaxOrderUrl');
        }
        if (dataTableOptions.ajaxOrderUrl != null) {
            dataTable.on('row-reorder.dt', function (dragEvent, data, nodes) {
                var rowIndex0 = data[0].node._DT_RowIndex;
                var rowData0 = dataTable.row(rowIndex0).data();
                var rowIndex1 = data[1].node._DT_RowIndex;
                var rowData1 = dataTable.row(rowIndex1).data();

                $.ajax({
                    url: dataTableOptions.ajaxOrderUrl,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        from: rowData0.id,
                        to: rowData1.id
                    }
                });

            });

            $this.addClass('table-reorderable');
        }

        return dataTable;
    };
}(jQuery));<commit_msg>Allow override of order<commit_after>(function( $ ) {
    $.fn.datatableify = function(options) {
        var $this = $(this);

        var dataTable;
        var dataTableOptions = $.extend({
            searching: true,
            responsive: true,

            // Shortcut variables
            ajaxLoadUrl: null,
            ajaxOrderUrl: null
        }, options);

        var cols = [];
        var firstColumn = 0;

        // Gather column information from thead
        $this.find('thead tr th').each(function (k, v) {
            if ($(v).data('datatable-ignore')) {
                cols.push({
                    data: 'selection',
                    searchable: false,
                    searchType: 'normal',
                    sortable: false,
                    className: $(v).data('datatable-class')
                });
                firstColumn += 1;
            } else {
                cols.push({
                    data: $(v).data('datatable-id'),
                    name: $(v).data('datatable-name'),
                    searchable: $(v).data('datatable-searchable'),
                    searchType: $(v).data('datatable-search-type'),
                    searchCustom: $(v).data('datatable-search-custom'),
                    searchOptions: $(v).data('datatable-search-options'),
                    sortable: $(v).data('datatable-sortable'),
                    className: $(v).data('datatable-class')
                });
            }
        });

        if (typeof dataTableOptions.order == 'undefined') {
            dataTableOptions.order = [[firstColumn, "desc"]];
        }
        dataTableOptions.columns = cols;

        // Ajax server side table
        if ($(this).data('datatableAjaxLoadUrl')) {
            dataTableOptions.ajaxLoadUrl = $(this).data('datatableAjaxLoadUrl');
        }

        if (dataTableOptions.ajaxLoadUrl != null) {
            dataTableOptions.processing = true;
            dataTableOptions.serverSide = true;
            dataTableOptions.ajax = {
                url: dataTableOptions.ajaxLoadUrl,
                data: function (d) {
                    $('.datatable-filter').each(function (k, v) {
                        if (!$(v).is(':checkbox') || ($(v).is(':checkbox') && $(v).is(':checked'))) {
                            var name = $(v).prop('name');
                            var value = $(v).val();

                            d[name] = value;
                        }
                    });
                }
            };
        }

        // Disable paging for order table
        if (dataTableOptions.ajaxOrderUrl != null) {
            dataTableOptions.rowReorder = true;
            dataTableOptions.paging = false;
        }

        dataTable = $this.DataTable(dataTableOptions);

        // Build Search Header
        $this.find('thead').append('

');
        $this.find('thead th').each(function (k, v) {
            if (cols[k]['searchable'] != false) {
                if (cols[k]['searchType'] == 'select' && typeof cols[k]['searchOptions'] == 'object' && Object.keys(cols[k]['searchOptions']).length > 0) {
                    $this.find('.thead-search').append('<select style="width: 100%" class="simple-search-field select_' + cols[k]['data'] + '"></select>	');
                    $this.find('.select_' + cols[k]['data']).append('<option value=""></option>');

                    for (var i in cols[k]['searchOptions']) {
                        $this.find('.select_' + cols[k]['data']).append('<option value="' + i + '">' + cols[k]['searchOptions'][i] + '</option>');
                    }
                } else if (cols[k]['searchType'] == 'date-range') {
                    $this.find('.thead-search').append('<input type="text" placeholder="From" style="width: 50%" class="date-range-search-field datepicker datatable-filter" name="' + cols[k]['data'] + '_from"/><input type="text" placeholder="To" style="width: 50%" class="date-range-search-field datepicker datatable-filter" name="' + cols[k]['data'] + '_to"/>	');
                } else if (cols[k]['searchType'] == 'date') {
                    $this.find('.thead-search').append('<input type="text" placeholder="" style="width: 100%" class="simple-search-field datepicker"/>	');
                } else if (cols[k]['searchType'] == 'custom') {
                    $this.find('.thead-search').append('' + $(cols[k]['searchCustom']).html() + '	');
                } else {
                    $this.find('.thead-search').append('<input type="text" placeholder="" style="width: 100%" class="simple-search-field"/>	');
                }
            } else {
                $this.find('.thead-search').append('	');
            }
        });

        // Apply the search
        dataTable.columns().every(function () {
            var that = this;
            var search_header = $this.find('.thead-search td:nth-child(' + parseInt(this.index() + 1) + ')');

            $('input.simple-search-field, select.simple-search-field', search_header).on('keyup change', function () {
                that
                    .search(this.value)
                    .draw();
            });
        });

        // Responsive Table
        dataTable.on('responsive-resize', function (e, datatable, columns) {
            for (i in columns) {
                if (columns[i])
                    $this.find('.thead-search td:nth-child(' + i + ')').show();
                else
                    $this.find('.thead-search td:nth-child(' + i + ')').hide();
            }
        });

        // Row Reorder
        if ($(this).data('datatableAjaxOrderUrl')) {
            dataTableOptions.ajaxOrderUrl = $(this).data('datatableAjaxOrderUrl');
        }
        if (dataTableOptions.ajaxOrderUrl != null) {
            dataTable.on('row-reorder.dt', function (dragEvent, data, nodes) {
                var rowIndex0 = data[0].node._DT_RowIndex;
                var rowData0 = dataTable.row(rowIndex0).data();
                var rowIndex1 = data[1].node._DT_RowIndex;
                var rowData1 = dataTable.row(rowIndex1).data();

                $.ajax({
                    url: dataTableOptions.ajaxOrderUrl,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        from: rowData0.id,
                        to: rowData1.id
                    }
                });

            });

            $this.addClass('table-reorderable');
        }

        return dataTable;
    };
}(jQuery));<|endoftext|>


<commit_before>const Rx = require(`rx`)
const virtualDOM = require(`virtual-dom`)
const createEventHandler = require(`createEventHandler`)
const createElement = require(`createElement`)
const render = require(`render`)

function Yolk(){}
Yolk.prototype = {Rx, virtualDOM, createEventHandler, createElement, render}

module.exports = new Yolk
<commit_msg>Freeze main library export<commit_after>const Rx = require(`rx`)
const virtualDOM = require(`virtual-dom`)
const createEventHandler = require(`createEventHandler`)
const createElement = require(`createElement`)
const render = require(`render`)

function Yolk(){}
Yolk.prototype = {Rx, virtualDOM, createEventHandler, createElement, render}

module.exports = Object.freeze(new Yolk)
<|endoftext|>


<commit_before>
var Q = require("q");

/**
 * Wraps a Node writable stream, providing an API similar to
 * Narwhal's synchronous `io` streams, except returning and
 * accepting promises for long-latency operations.
 *
 * @param stream any Node writable stream
 * @returns {Promise * Writer} a promise for the
 * text writer.
 */
module.exports = Writer;
function Writer(_stream, charset) {
    var self = Object.create(Writer.prototype);

    if (charset && _stream.setEncoding) // TODO complain about inconsistency
        _stream.setEncoding(charset);

    var begin = Q.defer();
    var drained = Q.defer();

    _stream.on("error", function (reason) {
        begin.reject(reason);
    });

    _stream.on("drain", function () {
        begin.resolve(self);
        drained.resolve();
        drained = Q.defer();
    });

    /***
     * Writes content to the stream.
     * @param {String} content
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the buffer is empty, meaning
     * that all of the content has been sent.
     */
    self.write = function (content) {
        if (!_stream.writeable && !_stream.writable)
            return Q.reject(new Error("Can't write to non-writable (possibly closed) stream"));
        if (_stream.encoding == "binary" && !(content instanceof Buffer)) {
            content = new Buffer(content);
        }
        if (!_stream.write(content)) {
            return drained.promise;
        } else {
            return Q.resolve();
        }
    };

    /***
     * Waits for all data to flush on the stream.
     *
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the buffer is empty
     */
    self.flush = function () {
        return drained.promise;
    };

    /***
     * Closes the stream, waiting for the internal buffer
     * to flush.
     *
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the stream has finished writing,
     * flushing, and closed.
     */
    self.close = function () {
        _stream.end();
        drained.resolve(); // we will get no further drain events
        return Q.resolve(); // closing not explicitly observable
    };

    /***
     * Terminates writing on a stream, closing before
     * the internal buffer drains.
     *
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the stream has finished closing.
     */
    self.destroy = function () {
        _stream.destroy();
        drained.resolve(); // we will get no further drain events
        return Q.resolve(); // destruction not explicitly observable
    };

    return Q.resolve(self); // todo returns the begin.promise
}

<commit_msg>Fix issues when writing binary data passed as array of bytes. - Reject drained promise when a write error occurs - Convert content to Buffer if content is not a string<commit_after>
var Q = require("q");

/**
 * Wraps a Node writable stream, providing an API similar to
 * Narwhal's synchronous `io` streams, except returning and
 * accepting promises for long-latency operations.
 *
 * @param stream any Node writable stream
 * @returns {Promise * Writer} a promise for the
 * text writer.
 */
module.exports = Writer;
function Writer(_stream, charset) {
    var self = Object.create(Writer.prototype);

    if (charset && _stream.setEncoding) // TODO complain about inconsistency
        _stream.setEncoding(charset);

    var begin = Q.defer();
    var drained = Q.defer();

    _stream.on("error", function (reason) {
        begin.reject(reason);
        drained.reject(reason);
        drained = Q.defer();
    });

    _stream.on("drain", function () {
        begin.resolve(self);
        drained.resolve();
        drained = Q.defer();
    });

    /***
     * Writes content to the stream.
     * @param {String} content
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the buffer is empty, meaning
     * that all of the content has been sent.
     */
    self.write = function (content) {
        if (!_stream.writeable && !_stream.writable)
            return Q.reject(new Error("Can't write to non-writable (possibly closed) stream"));
        if (typeof content !== "string") {
            content = new Buffer(content);
        }
        if (!_stream.write(content)) {
            return drained.promise;
        } else {
            return Q.resolve();
        }
    };

    /***
     * Waits for all data to flush on the stream.
     *
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the buffer is empty
     */
    self.flush = function () {
        return drained.promise;
    };

    /***
     * Closes the stream, waiting for the internal buffer
     * to flush.
     *
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the stream has finished writing,
     * flushing, and closed.
     */
    self.close = function () {
        _stream.end();
        drained.resolve(); // we will get no further drain events
        return Q.resolve(); // closing not explicitly observable
    };

    /***
     * Terminates writing on a stream, closing before
     * the internal buffer drains.
     *
     * @returns {Promise * Undefined} a promise that will
     * be resolved when the stream has finished closing.
     */
    self.destroy = function () {
        _stream.destroy();
        drained.resolve(); // we will get no further drain events
        return Q.resolve(); // destruction not explicitly observable
    };

    return Q.resolve(self); // todo returns the begin.promise
}

<|endoftext|>


<commit_before>var i2c = require('i2c');

function setTimeoutAsync(delay) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, delay);
  });
}

function AM2320(address, device) {
  this.device = device || '/dev/i2c-1';
  this.address = address || AM2320.DEFAULT_ADDRESS;
  this.initialize();
}

AM2320.DEFAULT_ADDRESS = 0x5c;

AM2320.prototype.initialize = function(callback) {
  this.wire = new i2c(this.address, {device : this.device});
}

AM2320.prototype.wakeUpDevice = function() {
  this.wire.writeBytes(0x00, [], function(err) {});
}

AM2320.prototype.setResolution = function() {
  this.wire.writeBytes(0x03, [0x00, 0x04], function(err) {
    if (err) {
      console.error(err);
    }
  });
}

AM2320.prototype._readRawResolution = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
  self.wakeUpDevice();
  setTimeoutAsync(3)
    .then(function() {
      self.setResolution();
      setTimeoutAsync(15)
        .then(function() {
          self.wire.readBytes(0x00, 0x06, function(err, res) {
            if (err) {
              reject(err);
              return;
            } else {
              resolve(res);
            }
          });
      });
    });
  });
}

AM2320.prototype.readTemperature = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self._readRawResolution()
      .then(function(value) {
        resolve((value[4] << 8 | value[5])/10.0);
      })
      .catch(function(value) {
        reject(value);
      });
  });
}

AM2320.prototype.readHumidity = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self._readRawResolution()
      .then(function(value) {
        resolve((value[2] << 8 | value[3])/10.0);
      })
      .catch(function(value) {
        reject(value);
      });
  });
}

module.exports = AM2320;

<commit_msg>Remove unused argument<commit_after>var i2c = require('i2c');

function setTimeoutAsync(delay) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, delay);
  });
}

function AM2320(address, device) {
  this.device = device || AM2320.DEFAULT_DEVICE_PATH;
  this.address = address || AM2320.DEFAULT_ADDRESS;
  this.initialize();
}

AM2320.DEFAULT_ADDRESS = 0x5c;
AM2320.DEFAULT_DEVICE_PATH = '/dev/i2c-1';

AM2320.prototype.initialize = function() {
  this.wire = new i2c(this.address, {device : this.device});
}

AM2320.prototype.wakeUpDevice = function() {
  this.wire.writeBytes(0x00, [], function(err) {});
}

AM2320.prototype.setResolution = function() {
  this.wire.writeBytes(0x03, [0x00, 0x04], function(err) {
    if (err) {
      console.error(err);
    }
  });
}

AM2320.prototype._readRawResolution = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
  self.wakeUpDevice();
  setTimeoutAsync(3)
    .then(function() {
      self.setResolution();
      setTimeoutAsync(15)
        .then(function() {
          self.wire.readBytes(0x00, 0x06, function(err, res) {
            if (err) {
              reject(err);
              return;
            } else {
              resolve(res);
            }
          });
      });
    });
  });
}

AM2320.prototype.readTemperature = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self._readRawResolution()
      .then(function(value) {
        resolve((value[4] << 8 | value[5])/10.0);
      })
      .catch(function(value) {
        reject(value);
      });
  });
}

AM2320.prototype.readHumidity = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self._readRawResolution()
      .then(function(value) {
        resolve((value[2] << 8 | value[3])/10.0);
      })
      .catch(function(value) {
        reject(value);
      });
  });
}

module.exports = AM2320;

<|endoftext|>


<commit_before>angular.module('smartCampUZApp')

    // 'auth' service manage the authentication function of the page with the server
    .factory('auth', function ($state, $http, $base64) {

        var _identity = undefined,
            _authenticated = false;

        return {
            //return true if the user is authenticated
            isAuthenticated: function () {
                if (_authenticated) {
                    return _authenticated;
                } else {
                    var tmp = angular.fromJson(localStorage.userIdentity);
                    if (tmp !== undefined) {
                        this.authenticate(tmp);
                        return _authenticated;
                    } else {
                        return false;
                    }
                }
            },

            //authenticate the [identity] user
            authenticate: function (identity, jwt) {
                _identity = identity;
                _authenticated = identity !== undefined;
                localStorage.smartJWT = angular.toJson(jwt);
                localStorage.userIdentity = angular.toJson(_identity);
            },

            //logout function
            logout: function () {
                _identity = undefined;
                _authenticated = false;
                localStorage.removeItem('smartJWT');
                localStorage.removeItem('userIdentity');
                $state.go('starter');
            },

            getUserObject: function () {
                return _identity;
            },
            getUserName: function () {
              return _identity.userName;
            },
            getEmail: function () {
                return _identity.email;
            },
            getType: function () {
              return _identity.type;
            },

            //send the login info to the server
            login: function (email, password, callbackSuccess, callbackError) {
                var that = this;
                $http({
                    method: 'POST',
                    url: 'signIn',
                    headers: {
                        'Authorization': 'Basic ' +
                        $base64.encode(email + ":" + password)
                    }
                }).success(function (data, status, headers) {
                    that.authenticate(data, headers().token);
                    callbackSuccess();
                    if (data.type == 'admin') {
                        $state.go('admin');
                    } else if (data.type == 'maintenance') {
                        $state.go('maintenance');
                    }
                }).error(function (data) {
                    callbackError(data);
                });
            }
        };
    })

    // 'reserve' service manage the reserve service of the page with the server
    .factory('reserve', function ($state, $http, userMap, auth) {

        return {
            // Get the current day
            getCurrentDate: function (callbackSuccess, callbackError) {
                $http({
                    method: 'GET',
                    url: 'currentDate'
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    var date = {month: 01, day: 23};
                    callbackSuccess(date);
                    //callbackError(data);
                });
            },
            // Get available hours of a [date]
            getAvailableHours: function (month, day, callbackSuccess, callbackError) {
                $http({
                    method: 'GET',
                    url: 'availableHours',
                    headers: {
                        month: month,
                        day: day,
                        location: userMap.getCurrentLocation().id
                    }
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    var date = [0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2];
                    callbackSuccess(date);
                    //callbackError(data);
                });
            },
            // Reserve [reserveHours] hours with specific [reserveInfo] information
            reserveHours: function (reserveInfo, reserveHours, callbackSuccess, callbackError) {
                var aux = {
                    info: reserveInfo,
                    hours: reserveHours,
                    location: userMap.getCurrentLocation().id,
                    logged: auth.isAuthenticated() ? true : false
                };
                var token = angular.fromJson(localStorage.smartJWT) !== undefined ? angular.fromJson(localStorage.smartJWT) : "";
                $http({
                    method: 'POST',
                    url: 'reserveHours',
                    headers: {'Authorization': 'Bearer ' + token},
                    data: JSON.stringify(aux)
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    callbackError(data);
                });
            }
        };
    })

    // 'feedback' service manage the feedback service of the page with the server
    .factory('feedback', function ($state, $http, userMap) {

        return {
            // Report a description of a feedback
            reportFeedback: function (description, callbackSuccess, callbackError) {
                var aux = {
                    description: description,
                    location: userMap.getCurrentLocation().id
                };
                $http({
                    method: 'POST',
                    url: 'reportFeedback',
                    data: JSON.stringify(aux)
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    callbackError(data);
                });
            },

            // List all feedback from the server
            getFeedback: function (callbackSuccess, callbackError) {
                var token = angular.fromJson(localStorage.smartJWT) !== undefined ? angular.fromJson(localStorage.smartJWT) : "";
                var aux = {
                    location: userMap.getCurrentLocation().id
                };
                $http({
                    method: 'POST',
                    url: 'listFeedback',
                    headers: {'Authorization': 'Bearer ' + token},
                    data: JSON.stringify(aux)
                }).success(function (data) {
                    callbackSuccess(data.feedbacks);
                }).error(function (data) {
                    callbackError(data);
                });
            },

            // State management of a report
            setState: function (state) {
                var token = angular.fromJson(localStorage.smartJWT) !== undefined ? angular.fromJson(localStorage.smartJWT) : "";
                $http({
                    method: 'PUT',
                    url: 'state',
                    headers: {'Authorization': 'Bearer ' + token},
                    data: JSON.stringify(state)
                }).success(function (data) {

                }).error(function (data) {

                });
            }
        };
    })

    // 'userMap' service manage the user view of the map with the server
    .factory('userMap', function ($state, $http) {

        var currentLocation = {
            id:0,
            name: ""
        };

        return {
            // Get the current location
            getCurrentLocation: function () {
                return currentLocation;
            },

            // Get the room from the given coordenates
            setLocationFromCoordenates: function (lat, lng, callbackSuccess, callbackError) {
            	$http({
                    method: 'GET',
                    url: 'locationFromCoords',
				    headers: {
				        lat: lat,
				    	lng: lng
				    }
                }).success(function (data) {
                	callbackSuccess(data);
                }).error(function (data) {
                	//callbackError(data);
                    var aux = {id: 123123, name: "L0.01"};
                    callbackSuccess(aux);
                });
            },

            // Set the current location
            setCurrentLocation: function (location) {
            	currentLocation = location;
            }
        };
    });
<commit_msg>Corrected listFeedback http request due to API<commit_after>angular.module('smartCampUZApp')

    // 'auth' service manage the authentication function of the page with the server
    .factory('auth', function ($state, $http, $base64) {

        var _identity = undefined,
            _authenticated = false;

        return {
            //return true if the user is authenticated
            isAuthenticated: function () {
                if (_authenticated) {
                    return _authenticated;
                } else {
                    var tmp = angular.fromJson(localStorage.userIdentity);
                    if (tmp !== undefined) {
                        this.authenticate(tmp);
                        return _authenticated;
                    } else {
                        return false;
                    }
                }
            },

            //authenticate the [identity] user
            authenticate: function (identity, jwt) {
                _identity = identity;
                _authenticated = identity !== undefined;
                localStorage.smartJWT = angular.toJson(jwt);
                localStorage.userIdentity = angular.toJson(_identity);
            },

            //logout function
            logout: function () {
                _identity = undefined;
                _authenticated = false;
                localStorage.removeItem('smartJWT');
                localStorage.removeItem('userIdentity');
                $state.go('starter');
            },

            getUserObject: function () {
                return _identity;
            },
            getUserName: function () {
              return _identity.userName;
            },
            getEmail: function () {
                return _identity.email;
            },
            getType: function () {
              return _identity.type;
            },

            //send the login info to the server
            login: function (email, password, callbackSuccess, callbackError) {
                var that = this;
                $http({
                    method: 'POST',
                    url: 'signIn',
                    headers: {
                        'Authorization': 'Basic ' +
                        $base64.encode(email + ":" + password)
                    }
                }).success(function (data, status, headers) {
                    that.authenticate(data, headers().token);
                    callbackSuccess();
                    if (data.type == 'admin') {
                        $state.go('admin');
                    } else if (data.type == 'maintenance') {
                        $state.go('maintenance');
                    }
                }).error(function (data) {
                    callbackError(data);
                });
            }
        };
    })

    // 'reserve' service manage the reserve service of the page with the server
    .factory('reserve', function ($state, $http, userMap, auth) {

        return {
            // Get the current day
            getCurrentDate: function (callbackSuccess, callbackError) {
                $http({
                    method: 'GET',
                    url: 'currentDate'
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    var date = {month: 01, day: 23};
                    callbackSuccess(date);
                    //callbackError(data);
                });
            },
            // Get available hours of a [date]
            getAvailableHours: function (month, day, callbackSuccess, callbackError) {
                $http({
                    method: 'GET',
                    url: 'availableHours',
                    headers: {
                        month: month,
                        day: day,
                        location: userMap.getCurrentLocation().id
                    }
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    var date = [0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2];
                    callbackSuccess(date);
                    //callbackError(data);
                });
            },
            // Reserve [reserveHours] hours with specific [reserveInfo] information
            reserveHours: function (reserveInfo, reserveHours, callbackSuccess, callbackError) {
                var aux = {
                    info: reserveInfo,
                    hours: reserveHours,
                    location: userMap.getCurrentLocation().id,
                    logged: auth.isAuthenticated() ? true : false
                };
                var token = angular.fromJson(localStorage.smartJWT) !== undefined ? angular.fromJson(localStorage.smartJWT) : "";
                $http({
                    method: 'POST',
                    url: 'reserveHours',
                    headers: {'Authorization': 'Bearer ' + token},
                    data: JSON.stringify(aux)
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    callbackError(data);
                });
            }
        };
    })

    // 'feedback' service manage the feedback service of the page with the server
    .factory('feedback', function ($state, $http, userMap) {

        return {
            // Report a description of a feedback
            reportFeedback: function (description, callbackSuccess, callbackError) {
                var aux = {
                    description: description,
                    location: userMap.getCurrentLocation().id
                };
                $http({
                    method: 'POST',
                    url: 'reportFeedback',
                    data: JSON.stringify(aux)
                }).success(function (data) {
                    callbackSuccess(data);
                }).error(function (data) {
                    callbackError(data);
                });
            },

            // List all feedback from the server
            getFeedback: function (callbackSuccess, callbackError) {
                var token = angular.fromJson(localStorage.smartJWT) !== undefined ? angular.fromJson(localStorage.smartJWT) : "";
                $http({
                    method: 'GET',
                    url: 'listFeedback',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        location: userMap.getCurrentLocation().id
                    }
                }).success(function (data) {
                    callbackSuccess(data.feedbacks);
                }).error(function (data) {
                    callbackError(data);
                });
            },

            // State management of a report
            setState: function (state) {
                var token = angular.fromJson(localStorage.smartJWT) !== undefined ? angular.fromJson(localStorage.smartJWT) : "";
                $http({
                    method: 'PUT',
                    url: 'state',
                    headers: {'Authorization': 'Bearer ' + token},
                    data: JSON.stringify(state)
                }).success(function (data) {

                }).error(function (data) {

                });
            }
        };
    })

    // 'userMap' service manage the user view of the map with the server
    .factory('userMap', function ($state, $http) {

        var currentLocation = {
            id:0,
            name: ""
        };

        return {
            // Get the current location
            getCurrentLocation: function () {
                return currentLocation;
            },

            // Get the room from the given coordenates
            setLocationFromCoordenates: function (lat, lng, callbackSuccess, callbackError) {
            	$http({
                    method: 'GET',
                    url: 'locationFromCoords',
				    headers: {
				        lat: lat,
				    	lng: lng
				    }
                }).success(function (data) {
                	callbackSuccess(data);
                }).error(function (data) {
                	//callbackError(data);
                    var aux = {id: 123123, name: "L0.01"};
                    callbackSuccess(aux);
                });
            },

            // Set the current location
            setCurrentLocation: function (location) {
            	currentLocation = location;
            }
        };
    });
<|endoftext|>


<commit_before>/*globals WebGMEGlobal*/
/*jshint node:true, mocha:true*/
/**
 * @author pmeijer / https://github.com/pmeijer
 */

var testFixture = require('../../_globals.js');

describe('Artifact', function () {
    'use strict';
    var Artifact = testFixture.requirejs('blob/Artifact'),
        rimraf = testFixture.rimraf,
        should = testFixture.should,
        superagent = testFixture.superagent,
        agent = superagent.agent(),
        BlobClient = testFixture.BlobClient,
        server,
        serverBaseUrl,

        bcParam = {};

    describe('[http]', function () {
        before(function (done) {
            // we have to set the config here
            var gmeConfig = testFixture.getGmeConfig();
            gmeConfig.server.port = 9006;
            gmeConfig.server.https.enable = false;
            serverBaseUrl = 'http://127.0.0.1:' + gmeConfig.server.port;
            bcParam.serverPort = gmeConfig.server.port;
            bcParam.server = '127.0.0.1';
            bcParam.httpsecure = gmeConfig.server.https.enable;
            server = testFixture.WebGME.standaloneServer(gmeConfig);
            server.start(function () {
                done();
            });
        });

        beforeEach(function (done) {
            rimraf('./test-tmp/blob-storage', function (err) {
                if (err) {
                    done(err);
                    return;
                }
                done();
            });
        });

        after(function (done) {
            server.stop(done);
        });

        it('should addFile', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            artifact.addFile('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(err);
                    return;
                }
                var url = bc.getViewURL(hash);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should addFiles', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {
                    'a.txt': 'tttt'
                },
                artifact = new Artifact('testartifact', bc);
            artifact.addFiles(filesToAdd, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                should.equal(hashes.length, 1);
                var url = bc.getViewURL(hashes[0]);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should addFileAsSoftLink', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            artifact.addFileAsSoftLink('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(err);
                    return;
                }
                var url = bc.getViewURL(hash);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should addFilesAsSoftLinks', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {
                    'a.txt': 'tttt'
                },
                artifact = new Artifact('testartifact', bc);
            artifact.addFilesAsSoftLinks(filesToAdd, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                should.equal(hashes.length, 1);
                var url = bc.getViewURL(hashes[0]);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should addObjectHash', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            bc.putFile('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.addObjectHash('a.txt', hash, function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    var url = bc.getViewURL(hash);
                    agent.get(url).end(function (err, res) {
                        if (err) {
                            done(err);
                            return;
                        }
                        should.equal(res.status, 200);
                        should.equal(res.text, 'tttt');
                        done();
                    });
                });
            });
        });

        it('should addObjectHashes', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {
                    'a.txt': 'tttt'
                },
                artifact = new Artifact('testartifact', bc);
            bc.putFiles(filesToAdd, function (err, objHashes) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.addObjectHashes(objHashes, function (err/*, hashes*/) {
                    if (err) {
                        done(err);
                        return;
                    }
                    artifact.save(function (err, artHash) {
                        if (err) {
                            done(err);
                            return;
                        }
                        var url = bc.getViewURL(artHash, 'a.txt');
                        agent.get(url).end(function (err, res) {
                            if (err) {
                                done(err);
                                return;
                            }
                            should.equal(res.status, 200);
                            should.equal(res.text, 'tttt');
                            done();
                        });
                    });

                });
            });
        });
    });
});<commit_msg>#205 add more Blob artifact tests.<commit_after>/*globals WebGMEGlobal*/
/*jshint node:true, mocha:true*/
/**
 * @author pmeijer / https://github.com/pmeijer
 */

var testFixture = require('../../_globals.js');

describe('Artifact', function () {
    'use strict';
    var Artifact = testFixture.requirejs('blob/Artifact'),
        rimraf = testFixture.rimraf,
        should = testFixture.should,
        expect = testFixture.expect,
        superagent = testFixture.superagent,
        agent = superagent.agent(),
        BlobClient = testFixture.BlobClient,
        server,
        serverBaseUrl,

        bcParam = {};

    describe('[http]', function () {
        before(function (done) {
            // we have to set the config here
            var gmeConfig = testFixture.getGmeConfig();
            gmeConfig.server.port = 9006;
            gmeConfig.server.https.enable = false;
            serverBaseUrl = 'http://127.0.0.1:' + gmeConfig.server.port;
            bcParam.serverPort = gmeConfig.server.port;
            bcParam.server = '127.0.0.1';
            bcParam.httpsecure = gmeConfig.server.https.enable;
            server = testFixture.WebGME.standaloneServer(gmeConfig);
            server.start(function () {
                done();
            });
        });

        beforeEach(function (done) {
            rimraf('./test-tmp/blob-storage', function (err) {
                if (err) {
                    done(err);
                    return;
                }
                done();
            });
        });

        after(function (done) {
            server.stop(done);
        });

        it('should addFile', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            artifact.addFile('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(err);
                    return;
                }
                var url = bc.getViewURL(hash);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should addFiles', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {
                    'a.txt': 'tttt'
                },
                artifact = new Artifact('testartifact', bc);
            artifact.addFiles(filesToAdd, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                should.equal(hashes.length, 1);
                var url = bc.getViewURL(hashes[0]);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should succeed with no files addFiles', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {},
                artifact = new Artifact('testartifact', bc);
            artifact.addFiles(filesToAdd, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                expect(hashes).deep.equal([]);
                done();
            });
        });

        it('should addFileAsSoftLink', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            artifact.addFileAsSoftLink('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(err);
                    return;
                }
                var url = bc.getViewURL(hash);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should addFilesAsSoftLinks', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {
                    'a.txt': 'tttt'
                },
                artifact = new Artifact('testartifact', bc);
            artifact.addFilesAsSoftLinks(filesToAdd, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                should.equal(hashes.length, 1);
                var url = bc.getViewURL(hashes[0]);
                agent.get(url).end(function (err, res) {
                    if (err) {
                        done(err);
                        return;
                    }
                    should.equal(res.status, 200);
                    should.equal(res.text, 'tttt');
                    done();
                });
            });
        });

        it('should succeed with no files addFilesAsSoftLinks', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {},
                artifact = new Artifact('testartifact', bc);
            artifact.addFilesAsSoftLinks(filesToAdd, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                expect(hashes).deep.equal([]);
                done();
            });
        });

        it('should addObjectHash', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            bc.putFile('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.addObjectHash('a.txt', hash, function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    var url = bc.getViewURL(hash);
                    agent.get(url).end(function (err, res) {
                        if (err) {
                            done(err);
                            return;
                        }
                        should.equal(res.status, 200);
                        should.equal(res.text, 'tttt');
                        done();
                    });
                });
            });
        });

        it('should fail to add invalid object hash addObjectHash', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            artifact.addObjectHash('a.txt', 'invalid hash', function (err, hash) {
                if (err.indexOf('hash is invalid') > -1) {
                    done();
                    return;
                }
                done(new Error('should have failed to add an invalid hash to artifact ' + err));
            });
        });

        it('should fail to add different content with the same name addObjectHash', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            bc.putFile('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(new Error(err));
                    return;
                }
                artifact.addObjectHash('a.txt', hash, function (err, hash) {
                    if (err) {
                        done(new Error(err));
                        return;
                    }
                    artifact.addObjectHash('a.txt', hash, function (err, hash) {
                        if (err.indexOf('same name was already added') > -1) {
                            done();
                            return;
                        }
                        done(new Error('should have failed to add objects with the same name ' + err));
                    });
                });
            });
        });

        it('should addObjectHashes', function (done) {
            var bc = new BlobClient(bcParam),
                filesToAdd = {
                    'a.txt': 'tttt'
                },
                artifact = new Artifact('testartifact', bc);
            bc.putFiles(filesToAdd, function (err, objHashes) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.addObjectHashes(objHashes, function (err/*, hashes*/) {
                    if (err) {
                        done(err);
                        return;
                    }
                    artifact.save(function (err, artHash) {
                        if (err) {
                            done(err);
                            return;
                        }
                        var url = bc.getViewURL(artHash, 'a.txt');
                        agent.get(url).end(function (err, res) {
                            if (err) {
                                done(err);
                                return;
                            }
                            should.equal(res.status, 200);
                            should.equal(res.text, 'tttt');
                            done();
                        });
                    });

                });
            });
        });

        it('should succeed with no hashes addObjectHashes', function (done) {
            var bc = new BlobClient(bcParam),
                objHashes = {},
                artifact = new Artifact('testartifact', bc);

            artifact.addObjectHashes(objHashes, function (err, hashes) {
                if (err) {
                    done(err);
                    return;
                }
                expect(hashes).deep.equal([]);
                done();
            });
        });

        it('should fail to add invalid object hash addMetadataHash', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            artifact.addMetadataHash('a.txt', 'invalid hash', function (err, hash) {
                if (err.indexOf('hash is invalid') > -1) {
                    done();
                    return;
                }
                done(new Error('should have failed to add an invalid hash to artifact ' + err));
            });
        });

        it('should fail to add different content with the same name addMetadataHash', function (done) {
            var bc = new BlobClient(bcParam),
                artifact = new Artifact('testartifact', bc);
            bc.putFile('a.txt', 'tttt', function (err, hash) {
                if (err) {
                    done(new Error(err));
                    return;
                }
                artifact.addMetadataHash('a.txt', hash, function (err, hash) {
                    if (err) {
                        done(new Error(err));
                        return;
                    }
                    artifact.addMetadataHash('a.txt', hash, function (err, hash) {
                        if (err.indexOf('same name was already added') > -1) {
                            done();
                            return;
                        }
                        done(new Error('should have failed to add objects with the same name ' + err));
                    });
                });
            });
        });

        it('should fail with wrong hash addObjectHashes', function (done) {
            var bc = new BlobClient(bcParam),
                objHashes = {
                    'a.txt': '0123456789abcdef0123456789abcdef01234567'
                },
                artifact = new Artifact('testartifact', bc);

            artifact.addObjectHashes(objHashes, function (err, hashes) {
                if (err.indexOf('Failed adding objectHashes:') > -1) {
                    done();
                    return;
                }
                done(new Error('should have failed with bad hashes.'));
            });
        });

        it('should fail with wrong hashes addMetadataHashes', function (done) {
            var bc = new BlobClient(bcParam),
                objHashes = {
                    'a.txt': '0123456789abcdef0123456789abcdef01234567'
                },
                artifact = new Artifact('testartifact', bc);

            artifact.addMetadataHashes(objHashes, function (err, hashes) {
                if (err.indexOf('Failed adding objectHashes:') > -1) {
                    done();
                    return;
                }
                done(new Error('should have failed with bad hashes.'));
            });
        });

        it('should succeed with no hashes addMetadataHashes', function (done) {
            var bc = new BlobClient(bcParam),
                objHashes = {},
                artifact = new Artifact('testartifact', bc);

            artifact.addMetadataHashes(objHashes, function (err, hashes) {
                if (err) {
                    done(new Error(err));
                    return;
                }
                expect(hashes).deep.equal([]);
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>var _ = require('underscore'),
    async = require('async'),
    childProcess = require('child_process'),
    path = require('path');

var cpuCount = require('os').cpus().length;

module.exports = function(dir, callback) {
  childProcess.exec('find ' + dir + ' -name ".git"', function(err, stdout) {
    if (err) {
      return callback(err);
    }

    var files = stdout.trim().split(/\n/g).map(path.dirname),
        repos = {};

    async.eachLimit(files, cpuCount*5, function(file, callback) {
        childProcess.exec('git fetch origin', {cwd: file, timeout: 5000}, function(err) {
          // Ignoring error for cases where there is no upstream.

          branchInfo(file, function(err, info) {
            if (err) {
              return callback(err);
            }

            if (/github\.com.*[:\/](.+)\/(.*)\.git$/.test(info.remote)) {
              info.name = RegExp.$1 + '/' + RegExp.$2;
            } else {
              info.name = file;
            }

            aheadBehind(info.remote, info.branch, file, function(err, aheadBehind) {
              if (err) {
                return callback(err);
              }

              _.extend(info, aheadBehind);

              localStatus(file, function(err, status) {
                if (err) {
                  return callback(err);
                }

                info.path = file;
                info.status = status;
                repos[info.name] = info;

                callback();
              });
            });
          });
        });
      },
      function(err) {
        callback(err, repos);
      });
  });
};

function branchInfo(path, callback) {
  childProcess.exec('git remote -v', {cwd: path}, function(err, remote) {
    if (err) {
      return callback(new Error('git.remote: ' + path + ' ' + err.message));
    }

    remote = (/origin\s+(.*) \(fetch\)/.exec(remote) || [])[1];

    childProcess.exec('git branch', {cwd: path}, function(err, branch) {
      if (err) {
        return callback(new Error('git.branch: ' + path + ' ' + err.message));
      }

      branch = (/\* (.*)/.exec(branch) || [])[1];
      if (/^\((?:detached|no branch)/.test(branch)) {
        branch = undefined;
      }

      callback(undefined, {remote: remote, branch: branch});
    });
  });
}
function aheadBehind(remote, branch, path, callback) {
  if (!branch || !remote) {
    return callback(undefined, {});
  }

  childProcess.exec('git rev-list HEAD..origin/' + branch + ' --', {cwd: path}, function(err, behind) {
    if (err) {
      if (/bad revision/.test(err.message)) {
        return callback(undefined, {localBranch: true});
      } else {
        return callback(new Error('git.behind: ' + path + ' ' + err.message));
      }
    }

    behind = behind.split('\n').length - 1;

    childProcess.exec('git rev-list origin/' + branch + '..HEAD --', {cwd: path}, function(err, ahead) {
      if (err) {
        return callback(new Error('git.ahead: ' + path + ' ' + err.message));
      }

      ahead = ahead.split('\n').length - 1;
      callback(undefined, {ahead: ahead, behind: behind});
    });
  });
}

var STATUS_MAP = {
  'A': 'added',
  'M': 'modified',
  'D': 'deleted',
  'R': 'modified',
  'C': 'modified',
  '?': 'untracked',
  'U': 'modified'
};

function localStatus(path, callback) {
  childProcess.exec('git status --porcelain', {cwd: path}, function(err, stdout) {
    if (err) {
      return callback(new Error('git.status ' + path + ': ' + err.message));
    }

    var lines = stdout.trim().split('\n'),
        counter = {added: 0, modified: 0, deleted: 0, untracked: 0};

    lines = _.filter(lines, function(line) { return line; });
    _.each(lines, function(line) {
      var index = STATUS_MAP[line[0]],
          workDir = STATUS_MAP[line[1]],
          status = [index, workDir].sort();

      if (status[0]) {
        counter[status[0]]++;
      }
    });

    callback(undefined, counter);
  });
}
<commit_msg>Log timeouts from fetch<commit_after>var _ = require('underscore'),
    async = require('async'),
    childProcess = require('child_process'),
    path = require('path');

var cpuCount = require('os').cpus().length;

module.exports = function(dir, callback) {
  childProcess.exec('find ' + dir + ' -name ".git"', function(err, stdout) {
    if (err) {
      return callback(err);
    }

    var files = stdout.trim().split(/\n/g).map(path.dirname),
        repos = {};

    async.eachLimit(files, cpuCount*5, function(file, callback) {
        var fetch = childProcess.exec('git fetch origin', {cwd: file, stdio: 'ignore', timeout: 30000}, function(err) {
          // Ignoring error for cases where there is no upstream.

          if (err && fetch.killed) {
            console.error('timeout: ' + file);
          }

          branchInfo(file, function(err, info) {
            if (err) {
              return callback(err);
            }

            if (/github\.com.*[:\/](.+)\/(.*)\.git$/.test(info.remote)) {
              info.name = RegExp.$1 + '/' + RegExp.$2;
            } else {
              info.name = file;
            }

            aheadBehind(info.remote, info.branch, file, function(err, aheadBehind) {
              if (err) {
                return callback(err);
              }

              _.extend(info, aheadBehind);

              localStatus(file, function(err, status) {
                if (err) {
                  return callback(err);
                }

                info.path = file;
                info.status = status;
                repos[info.name] = info;

                callback();
              });
            });
          });
        });
      },
      function(err) {
        callback(err, repos);
      });
  });
};

function branchInfo(path, callback) {
  childProcess.exec('git remote -v', {cwd: path}, function(err, remote) {
    if (err) {
      return callback(new Error('git.remote: ' + path + ' ' + err.message));
    }

    remote = (/origin\s+(.*) \(fetch\)/.exec(remote) || [])[1];

    childProcess.exec('git branch', {cwd: path}, function(err, branch) {
      if (err) {
        return callback(new Error('git.branch: ' + path + ' ' + err.message));
      }

      branch = (/\* (.*)/.exec(branch) || [])[1];
      if (/^\((?:detached|no branch)/.test(branch)) {
        branch = undefined;
      }

      callback(undefined, {remote: remote, branch: branch});
    });
  });
}
function aheadBehind(remote, branch, path, callback) {
  if (!branch || !remote) {
    return callback(undefined, {});
  }

  childProcess.exec('git rev-list HEAD..origin/' + branch + ' --', {cwd: path}, function(err, behind) {
    if (err) {
      if (/bad revision/.test(err.message)) {
        return callback(undefined, {localBranch: true});
      } else {
        return callback(new Error('git.behind: ' + path + ' ' + err.message));
      }
    }

    behind = behind.split('\n').length - 1;

    childProcess.exec('git rev-list origin/' + branch + '..HEAD --', {cwd: path}, function(err, ahead) {
      if (err) {
        return callback(new Error('git.ahead: ' + path + ' ' + err.message));
      }

      ahead = ahead.split('\n').length - 1;
      callback(undefined, {ahead: ahead, behind: behind});
    });
  });
}

var STATUS_MAP = {
  'A': 'added',
  'M': 'modified',
  'D': 'deleted',
  'R': 'modified',
  'C': 'modified',
  '?': 'untracked',
  'U': 'modified'
};

function localStatus(path, callback) {
  childProcess.exec('git status --porcelain', {cwd: path}, function(err, stdout) {
    if (err) {
      return callback(new Error('git.status ' + path + ': ' + err.message));
    }

    var lines = stdout.trim().split('\n'),
        counter = {added: 0, modified: 0, deleted: 0, untracked: 0};

    lines = _.filter(lines, function(line) { return line; });
    _.each(lines, function(line) {
      var index = STATUS_MAP[line[0]],
          workDir = STATUS_MAP[line[1]],
          status = [index, workDir].sort();

      if (status[0]) {
        counter[status[0]]++;
      }
    });

    callback(undefined, counter);
  });
}
<|endoftext|>


<commit_before>
import React, { Component } from 'react'

class Info extends Component {
  render () {
    return (

        The info page

    )
  }
}

const styles = {
  container: {
    flex: 1,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 84
  }
}

export default Info
<commit_msg>Useful links page<commit_after>
import React, { Component } from 'react'

class Info extends Component {
  render () {
    return (

Useful Links

Social Security

            Serviços de Atendimento da Segurança Social

              http://www.seg-social.pt/servicos-de-atendimento

Police

            PSP Serviço de queixa electrónica

              https://queixaselectronicas.mai.gov.pt/SQE2013/default.aspx#tag=MAIN_CONTENT

Telephone Translation

            Tradução telefónica ACM

              http://www.acm.gov.pt/-/servico-de-traducao-telefonica

Portuguese for All

            Português para Todos

              http://www.acm.gov.pt/-/oferta-formativa-do-programa-ppt-portugues-para-todos

Online Platform for Portuguese

            Plataforma de Português Online

              https://pptonline.acm.gov.pt/

General Directorate for Education

            D. G. Educação (Reconhecimento de Qualificações)

              equivalencias.dsdc@dge.mec.pt/

    )
  }
}

const styles = {
  container: {
    flex: 1,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 84
  },
  header: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    display: 'flex',
    marginBottom: 50
  },
  row: {
    marginBottom: 40
  }
}

export default Info
<|endoftext|>


<commit_before>/**
 * fullPage 1.0
 * https://github.com/alvarotrigo/fullPage.js
 * MIT licensed
 *
 * Copyright (C) 2013 alvarotrigo.com - A project by Alvaro Trigo
 */
(function(a){a.fn.fullpage=function(c){function r(){return function(b){if(c.autoScrolling){b=window.event||b;b=Math.max(-1,Math.min(1,b.wheelDelta||-b.detail));if(!k){var e=a(".section.active").find(".scrollable");if(0>b)if(0<e.length)if(m("bottom",e))a.fn.fullpage.moveSlideDown();else return!0;else a.fn.fullpage.moveSlideDown();else if(0<e.length)if(m("top",e))a.fn.fullpage.moveSlideUp();else return!0;else a.fn.fullpage.moveSlideUp()}return!1}}}function g(b,e){var d={},f;f=b.position();var s=null!==
f?f.top:null,v=u(b),g=b.data("anchor"),h=b.index(".section");b.addClass("active").siblings().removeClass("active");k=!0;a.isFunction(e)||(location.hash="undefined"!==typeof g?g:"");c.autoScrolling?(d.top=-s,f="#superContainer"):(d.scrollTop=s,f="html, body");c.css3&&c.autoScrolling?(a.isFunction(c.onLeave)&&c.onLeave.call(this,h,v),d="translate3d(0px, -"+s+"px, 0px)",a("#superContainer").addClass("easing").css({"-webkit-transform":d,"-moz-transform":d,"-ms-transform":d,transform:d}),a.isFunction(c.afterLoad)&&
c.afterLoad.call(this,g,h+1),setTimeout(function(){k=!1;a.isFunction(e)&&e.call(this)},700)):(a.isFunction(c.onLeave)&&c.onLeave.call(this,h,v),a(f).animate(d,c.scrollingSpeed,c.easing,function(){a.isFunction(c.afterLoad)&&c.afterLoad.call(this,g,h+1);setTimeout(function(){k=!1;a.isFunction(e)&&e.call(this)},700)}));w=g;x(g);C(g,h)}function D(){var b=window.location.hash.replace("#","").split("/"),c=b[0],d=b[1];if(c){var f=a('[data-anchor="'+c+'"]');g(f,function(){if("undefined"!=typeof d){var a=
f.find(".slides"),b=a.find('[data-anchor="'+d+'"]');b.length||(b=a.find(".slide").eq(d));a.find(".slide").first().removeClass("active");n(a,b);b.addClass("active")}})}}function n(a,e){var d=e.position(),f=a.find(".slidesContainer").parent(),g=e.data("anchor");"undefined"===typeof g&&(g=e.index(".slide"));location.hash=location.hash.split("/")[0]+"/"+g;c.css3?(d="translate3d(-"+d.left+"px, 0px, 0px)",a.find(".slidesContainer").addClass("easing").css({"-webkit-transform":d,"-moz-transform":d,"-ms-transform":d,
transform:d}),setTimeout(function(){p=!0},c.scrollingSpeed)):f.animate({scrollLeft:d.left},c.scrollingSpeed,function(){p=!0})}function y(){var b=a(window).width(),e=a(window).height();c.resize&&E(e,b);a(".section").each(function(){c.scrollOverflow&&a(this).find(".scrollable").css("height",e+"px").parent().css("height",e+"px");c.verticalCentered&&a(this).find(".tableCell").css("height",e+"px");a(this).css("height",e+"px");var b=a(this).find(".slides");if(0b||900>c?(900>c&&(f=c,d=900),d=(100*f/d).toFixed(2),a("body").css("font-size",d+"%")):a("body").css("font-size","100%")}function C(b,e){c.navigation&&(a("#fullPage-nav").find(".active").removeClass("active"),b?a("#fullPage-nav").find('a[href="#'+b+'"]').addClass("active"):a("#fullPage-nav").find("li").eq(e).find("a").addClass("active"))}function x(b){c.menu&&(a(c.menu).find(".active").removeClass("active"),
a(c.menu).find('[data-menuanchor="'+b+'"]').addClass("active"))}function m(a,c){if("top"===a)return!c.scrollTop();if("bottom"===a)return c.scrollTop()+c.innerHeight()>=c[0].scrollHeight}function u(b){var c=a(".section.active").index(".section");b=b.index(".section");return c>b?"up":"down"}c=a.extend({verticalCentered:!0,resize:!0,slidesColor:[],anchors:[],scrollingSpeed:700,easing:"easeInQuart",menu:!1,navigation:!1,navigationPosition:"right",navigationColor:"#000",controlArrowColor:"#fff",loopBottom:!1,
loopTop:!1,autoScrolling:!0,scrollOverflow:!1,css3:!1,afterLoad:null,onLeave:null,afterRender:null},c);a.fn.fullpage.setAutoScrolling=function(b){c.autoScrolling=b;c.autoScrolling?a("html, body").css({overflow:"hidden",height:"100%"}):(a("html, body").css({overflow:"auto",height:"auto"}),a("#superContainer").css("top","0px"))};var p=!0,t=navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|Windows Phone)/),q=a(window).height(),k=!1,w;a.fn.fullpage.setAutoScrolling(c.autoScrolling);c.verticalCentered&&
a(".section").addClass("table").wrapInner('
');a("body").wrapInner('
');if(c.navigation){a("body").append('

');var h=a("#fullPage-nav");h.css("color",c.navigationColor);"right"===c.navigationPosition?h.css("right","17px"):h.css("left","17px")}a(".section").each(function(b){var e=a(this).find(".slide"),d=e.length;b||a(this).addClass("active");a(this).css("height",q+"px");"undefined"!==typeof c.slidesColor[b]&&
a(this).css("background-color",c.slidesColor[b]);"undefined"!==typeof c.anchors[b]&&a(this).data("anchor",c.anchors[b]);if(c.navigation){var f="";c.anchors.length&&(f=c.anchors[b]);h.find("ul").append('

')}if(0<d){b=100*d;var g=100/d;e.wrapAll('
');e.parent().wrap('
');a(this).find(".slidesContainer").css("width",b+"%");a(this).find(".slides").after('

');
a(".controlArrow.next").css("border-color","transparent transparent transparent "+c.controlArrowColor);a(".controlArrow.prev").css("border-color","transparent "+c.controlArrowColor+" transparent transparent");e.each(function(b){b||a(this).addClass("active");a(this).css("width",g+"%")})}}).promise().done(function(){a.isFunction(c.afterRender)&&c.afterRender.call(this);c.navigation&&(h.css("margin-top","-"+h.height()/2+"px"),h.find("li").first().find("a").addClass("active"));c.menu&&a(c.menu).appendTo("body");
if(c.scrollOverflow)a(window).on("load",function(){a(".section").each(function(){a(this).height()>q&&(c.verticalCentered?a(this).find(".tableCell").wrapInner('
'):a(this).wrapInner('
'),a(this).find(".scrollable").slimScroll({height:q+"px",size:"10px",alwaysVisible:!0}))})});a(window).on("load",function(){D()})});a(window).scroll(function(b){if(!c.autoScrolling){var e=a(window).scrollTop();b=a(".section").map(function(){if(a(this).offset().top<e+100)return a(this)});
b=b[b.length-1];if(!b.hasClass("active")){var d=u(b);a(".section.active").removeClass("active");b.addClass("active");var f=b.data("anchor");a.isFunction(c.onLeave)&&c.onLeave.call(this,b.index(".section"),d);a.isFunction(c.afterLoad)&&c.afterLoad.call(this,f,b.index(".section")+1);x(f)}}});var z=0,A=0;a(document).on("touchmove",function(b){if(c.autoScrolling&&t&&(b.preventDefault(),b=b.originalEvent,!k)){var e=a(".section.active").find(".scrollable");A=b.touches[0].pageY;if(z>A)if(0<e.length)if(m("bottom",
e))a.fn.fullpage.moveSlideDown();else return!0;else a.fn.fullpage.moveSlideDown();else if(0<e.length)if(m("top",e))a.fn.fullpage.moveSlideUp();else return!0;else a.fn.fullpage.moveSlideUp()}});a(document).on("touchstart",function(a){c.autoScrolling&&t&&(z=a.originalEvent.touches[0].pageY)});var l={},l=document;l.addEventListener?(l.addEventListener("mousewheel",r(),!1),l.addEventListener("DOMMouseScroll",r(),!1)):l.attachEvent("onmousewheel",r());a.fn.fullpage.moveSlideUp=function(){var b=a(".section.active").prev(".section");
c.loopTop&&!b.length&&(b=a(".section").last());(0<b.length||!b.length&&c.loopTop)&&g(b)};a.fn.fullpage.moveSlideDown=function(){var b=a(".section.active").next(".section");c.loopBottom&&!b.length&&(b=a(".section").first());(0<b.length||!b.length&&c.loopBottom)&&g(b)};a.fn.fullpage.moveToSlide=function(b){var c="",c=isNaN(b)?a('[data-anchor="'+b+'"]'):a(".section").eq(b-1);0<c.length&&g(c)};a(window).on("hashchange",function(){var b=window.location.hash.replace("#","").split("/")[0];b!==w&&(b=a('[data-anchor="'+
b+'"]'),g(b))});a(document).keydown(function(b){if(!k)switch(b.which){case 38:case 33:a.fn.fullpage.moveSlideUp();break;case 40:case 34:a.fn.fullpage.moveSlideDown();break;case 37:a(".section.active").find(".controlArrow.prev").trigger("click");break;case 39:a(".section.active").find(".controlArrow.next").trigger("click")}});a(document).on("click","#fullPage-nav a",function(b){b.preventDefault();b=a(this).parent().index("li");g(a(".section").eq(b))});a(".section").on("click",".controlArrow",function(){if(p){p=
!1;var b=a(this).closest(".section").find(".slides"),c=b.find(".slide.active"),d=null;c.removeClass("active");d=a(this).hasClass("prev")?c.prev(".slide"):c.next(".slide");d.length||(d=a(this).hasClass("prev")?c.siblings(":last"):c.siblings(":first"));n(b,d);d.addClass("active")}});a(".section").on("click",".toSlide",function(b){b.preventDefault();b=a(this).closest(".section").find(".slides");var c=b.find(".slide.active"),d=null,d=b.find(".slide").eq(a(this).data("index")-1);0<d.length&&(c.removeClass("active"),
n(b,d),d.addClass("active"))});if(!t){var B;a(window).resize(function(){clearTimeout(B);B=setTimeout(y,500)})}a(window).bind("orientationchange",function(){y()})}})(jQuery);<commit_msg>- Solved bug with anchor links.<commit_after>/**
 * fullPage 1.0
 * https://github.com/alvarotrigo/fullPage.js
 * MIT licensed
 *
 * Copyright (C) 2013 alvarotrigo.com - A project by Alvaro Trigo
 */
(function(a){a.fn.fullpage=function(c){function r(){return function(b){if(c.autoScrolling){b=window.event||b;b=Math.max(-1,Math.min(1,b.wheelDelta||-b.detail));if(!k){var e=a(".section.active").find(".scrollable");if(0>b)if(0<e.length)if(m("bottom",e))a.fn.fullpage.moveSlideDown();else return!0;else a.fn.fullpage.moveSlideDown();else if(0<e.length)if(m("top",e))a.fn.fullpage.moveSlideUp();else return!0;else a.fn.fullpage.moveSlideUp()}return!1}}}function g(b,e){var d={},f;f=b.position();var s=null!==
f?f.top:null,v=u(b),g=b.data("anchor"),h=b.index(".section");b.addClass("active").siblings().removeClass("active");k=!0;a.isFunction(e)||(location.hash="undefined"!==typeof g?g:"");c.autoScrolling?(d.top=-s,f="#superContainer"):(d.scrollTop=s,f="html, body");c.css3&&c.autoScrolling?(a.isFunction(c.onLeave)&&c.onLeave.call(this,h,v),d="translate3d(0px, -"+s+"px, 0px)",a("#superContainer").addClass("easing").css({"-webkit-transform":d,"-moz-transform":d,"-ms-transform":d,transform:d}),a.isFunction(c.afterLoad)&&
c.afterLoad.call(this,g,h+1),setTimeout(function(){k=!1;a.isFunction(e)&&e.call(this)},700)):(a.isFunction(c.onLeave)&&c.onLeave.call(this,h,v),a(f).animate(d,c.scrollingSpeed,c.easing,function(){a.isFunction(c.afterLoad)&&c.afterLoad.call(this,g,h+1);setTimeout(function(){k=!1;a.isFunction(e)&&e.call(this)},700)}));w=g;x(g);C(g,h)}function D(){var b=window.location.hash.replace("#","").split("/"),c=b[0],d=b[1];if(c){var f=a('[data-anchor="'+c+'"]');g(f,function(){if("undefined"!=typeof d){var a=
f.find(".slides"),b=a.find('[data-anchor="'+d+'"]');b.length||(b=a.find(".slide").eq(d));a.find(".slide").first().removeClass("active");n(a,b);b.addClass("active")}})}}function n(a,e){var d=e.position(),f=a.find(".slidesContainer").parent(),g=e.data("anchor");"undefined"===typeof g&&(g=e.index(".slide"));location.hash=location.hash.split("/")[0]+"/"+g;c.css3?(d="translate3d(-"+d.left+"px, 0px, 0px)",a.find(".slidesContainer").addClass("easing").css({"-webkit-transform":d,"-moz-transform":d,"-ms-transform":d,
transform:d}),setTimeout(function(){p=!0},c.scrollingSpeed)):f.animate({scrollLeft:d.left},c.scrollingSpeed,function(){p=!0})}function y(){var b=a(window).width(),e=a(window).height();c.resize&&E(e,b);a(".section").each(function(){c.scrollOverflow&&a(this).find(".scrollable").css("height",e+"px").parent().css("height",e+"px");c.verticalCentered&&a(this).find(".tableCell").css("height",e+"px");a(this).css("height",e+"px");var b=a(this).find(".slides");if(0b||900>c?(900>c&&(f=c,d=900),d=(100*f/d).toFixed(2),a("body").css("font-size",d+"%")):a("body").css("font-size","100%")}function C(b,e){c.navigation&&(a("#fullPage-nav").find(".active").removeClass("active"),b?a("#fullPage-nav").find('a[href="#'+b+'"]').addClass("active"):a("#fullPage-nav").find("li").eq(e).find("a").addClass("active"))}function x(b){c.menu&&(a(c.menu).find(".active").removeClass("active"),
a(c.menu).find('[data-menuanchor="'+b+'"]').addClass("active"))}function m(a,c){if("top"===a)return!c.scrollTop();if("bottom"===a)return c.scrollTop()+c.innerHeight()>=c[0].scrollHeight}function u(b){var c=a(".section.active").index(".section");b=b.index(".section");return c>b?"up":"down"}c=a.extend({verticalCentered:!0,slidesColor:[],anchors:[],scrollingSpeed:700,easing:"easeInQuart",menu:!1,navigation:!1,navigationPosition:"right",navigationColor:"#000",controlArrowColor:"#fff",loopBottom:!1,loopTop:!1,
autoScrolling:!0,scrollOverflow:!1,css3:!1,afterLoad:null,onLeave:null,afterRender:null},c);a.fn.fullpage.setAutoScrolling=function(b){c.autoScrolling=b;c.autoScrolling?a("html, body").css({overflow:"hidden",height:"100%"}):(a("html, body").css({overflow:"auto",height:"auto"}),a("#superContainer").css("top","0px"))};var p=!0,t=navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|Windows Phone)/),q=a(window).height(),k=!1,w;a.fn.fullpage.setAutoScrolling(c.autoScrolling);c.verticalCentered&&
a(".section").addClass("table").wrapInner('
');a("body").wrapInner('
');if(c.navigation){a("body").append('

');var h=a("#fullPage-nav");h.css("color",c.navigationColor);"right"===c.navigationPosition?h.css("right","17px"):h.css("left","17px")}a(".section").each(function(b){var e=a(this).find(".slide"),d=e.length;b||a(this).addClass("active");a(this).css("height",q+"px");"undefined"!==typeof c.slidesColor[b]&&
a(this).css("background-color",c.slidesColor[b]);"undefined"!==typeof c.anchors[b]&&a(this).attr("data-anchor",c.anchors[b]);if(c.navigation){var f="";c.anchors.length&&(f=c.anchors[b]);h.find("ul").append('

')}if(0<d){b=100*d;var g=100/d;e.wrapAll('
');e.parent().wrap('
');a(this).find(".slidesContainer").css("width",b+"%");a(this).find(".slides").after('

');
a(".controlArrow.next").css("border-color","transparent transparent transparent "+c.controlArrowColor);a(".controlArrow.prev").css("border-color","transparent "+c.controlArrowColor+" transparent transparent");e.each(function(b){b||a(this).addClass("active");a(this).css("width",g+"%")})}}).promise().done(function(){a.isFunction(c.afterRender)&&c.afterRender.call(this);c.navigation&&(h.css("margin-top","-"+h.height()/2+"px"),h.find("li").first().find("a").addClass("active"));c.menu&&a(c.menu).appendTo("body");
if(c.scrollOverflow)a(window).on("load",function(){a(".section").each(function(){a(this).height()>q&&(c.verticalCentered?a(this).find(".tableCell").wrapInner('
'):a(this).wrapInner('
'),a(this).find(".scrollable").slimScroll({height:q+"px",size:"10px",alwaysVisible:!0}))})});a(window).on("load",function(){D()})});a(window).scroll(function(b){if(!c.autoScrolling){var e=a(window).scrollTop();b=a(".section").map(function(){if(a(this).offset().top<e+100)return a(this)});
b=b[b.length-1];if(!b.hasClass("active")){var d=u(b);a(".section.active").removeClass("active");b.addClass("active");var f=b.data("anchor");a.isFunction(c.onLeave)&&c.onLeave.call(this,b.index(".section"),d);a.isFunction(c.afterLoad)&&c.afterLoad.call(this,f,b.index(".section")+1);x(f)}}});var z=0,A=0;a(document).on("touchmove",function(b){if(c.autoScrolling&&t&&(b.preventDefault(),b=b.originalEvent,!k)){var e=a(".section.active").find(".scrollable");A=b.touches[0].pageY;if(z>A)if(0<e.length)if(m("bottom",
e))a.fn.fullpage.moveSlideDown();else return!0;else a.fn.fullpage.moveSlideDown();else if(0<e.length)if(m("top",e))a.fn.fullpage.moveSlideUp();else return!0;else a.fn.fullpage.moveSlideUp()}});a(document).on("touchstart",function(a){c.autoScrolling&&t&&(z=a.originalEvent.touches[0].pageY)});var l={},l=document;l.addEventListener?(l.addEventListener("mousewheel",r(),!1),l.addEventListener("DOMMouseScroll",r(),!1)):l.attachEvent("onmousewheel",r());a.fn.fullpage.moveSlideUp=function(){var b=a(".section.active").prev(".section");
c.loopTop&&!b.length&&(b=a(".section").last());(0<b.length||!b.length&&c.loopTop)&&g(b)};a.fn.fullpage.moveSlideDown=function(){var b=a(".section.active").next(".section");c.loopBottom&&!b.length&&(b=a(".section").first());(0<b.length||!b.length&&c.loopBottom)&&g(b)};a.fn.fullpage.moveToSlide=function(b){var c="",c=isNaN(b)?a('[data-anchor="'+b+'"]'):a(".section").eq(b-1);0<c.length&&g(c)};a(window).on("hashchange",function(){var b=window.location.hash.replace("#","").split("/")[0];b!==w&&(b=a('[data-anchor="'+
b+'"]'),g(b))});a(document).keydown(function(b){if(!k)switch(b.which){case 38:case 33:a.fn.fullpage.moveSlideUp();break;case 40:case 34:a.fn.fullpage.moveSlideDown();break;case 37:a(".section.active").find(".controlArrow.prev").trigger("click");break;case 39:a(".section.active").find(".controlArrow.next").trigger("click")}});a(document).on("click","#fullPage-nav a",function(b){b.preventDefault();b=a(this).parent().index("li");g(a(".section").eq(b))});a(".section").on("click",".controlArrow",function(){if(p){p=
!1;var b=a(this).closest(".section").find(".slides"),c=b.find(".slide.active"),d=null;c.removeClass("active");d=a(this).hasClass("prev")?c.prev(".slide"):c.next(".slide");d.length||(d=a(this).hasClass("prev")?c.siblings(":last"):c.siblings(":first"));n(b,d);d.addClass("active")}});a(".section").on("click",".toSlide",function(b){b.preventDefault();b=a(this).closest(".section").find(".slides");var c=b.find(".slide.active"),d=null,d=b.find(".slide").eq(a(this).data("index")-1);0<d.length&&(c.removeClass("active"),
n(b,d),d.addClass("active"))});if(!t){var B;a(window).resize(function(){clearTimeout(B);B=setTimeout(y,500)})}a(window).bind("orientationchange",function(){y()})}})(jQuery);<|endoftext|>


<commit_before>console.log("ljswitchboard-kipling_tester index.js");

var gui = require('nw.gui');
var path = require('path');
var q = require('q');
var win = gui.Window.get();

var cwd = path.dirname(document.URL.split('file:///').join(''));
if(!path.isAbsolute(cwd)) {
	cwd = path.resolve(path.sep, cwd);
}

var nodeunit = require(path.normalize(path.join(cwd, '../node_modules/nodeunit')));
var nodeunit_recorder = require(path.normalize(path.join(cwd, 'nodeunit_recorder')));

var testFiles = [
	'test_kipling.js',
	// Execute Mock-Device compatable Tests
	'mock_module_tests/mock_device_selector.js',
	'mock_module_tests/mock_device_info.js',
	// 'mock_module_tests/mock_dashboard.js',

	// Execute Live-Device tests
	'module_tests/test_device_info.js',

	'finish_testing.js',
];
var test_dir = '../test';
for(var i = 0; i < testFiles.length; i++) {
	testFiles[i] = path.normalize(path.join(cwd, test_dir, testFiles[i]));
}

var package_loader = require('ljswitchboard-package_loader');
var gns = package_loader.getNameSpace();
var window_manager = require('ljswitchboard-window_manager');
var startDir = global[gns].info.startDir;
var handlebars = require('handlebars');
/*
	Function called to load the application's core resources.
	The resources are loaded from the ljswitchboard-static_files/static
	directory.
*/
var coreResourcesLoaded = false;
var loadCoreResources = function(resources) {
	global[gns].static_files.loadResources(document, resources)
	.then(function(res) {
		coreResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

/*
	Function called to load the application's local resources.
	The resources are loaded starting from the directory of the
	index.html/index.js file aka the cwd of the window.
*/
var localResourcesLoaded = false;
var loadLocalResources = function(resources) {
	global[gns].static_files.loadResources(document, resources, true)
	.then(function(res) {
		localResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

var loadResources = function(resources, isLocal) {
	var defered = q.defer();
	global[gns].static_files.loadResources(document, resources, isLocal)
	.then(function(res) {
		defered.resolve();
	}, function(err) {
		console.error('Error Loading resources', err);
		defered.reject(err);
	});
	return defered.promise;
};

var getUpdateTestResults = function(divID) {
	var cachedTestDiv;
	cachedTestDiv = undefined;
	var updateTestResults = function() {

		var savedText = nodeunit_recorder.getSavedText();
		if(cachedTestDiv) {
			cachedTestDiv.html(savedText);
		} else {
			cachedTestDiv = $(divID);
			cachedTestDiv.html(savedText);
		}
	};
	return updateTestResults;
};
var getRunTest = function(testFile, testDiv) {
	var testName = path.basename(testFile);
	var fileName = path.basename(testFile);
	var fileEnding = path.extname(testName);
	fileName = fileName.split(fileEnding).join('');

	var divID = fileName + '-test';
	var runTest = function() {
		var defered = q.defer();
		var str = [
			'
',
			'
',
				'Test: {{testName}}',
				'
',
					'Status: In Progress',
					'',
				'
',
			'
',
			'

Test!

',
			'
'
		].join('');
		var template = handlebars.compile(str);
		var newTxt = template({
			'id': divID,
			'testName':testName,
			'fileName': fileName
		});
		testDiv.append($(newTxt));
		try {
			var outputHTML = nodeunit_recorder.run(
				[testFile],
				{},
				getUpdateTestResults('#' + divID),
				function(err) {
					var testResults = $('#' + divID);
					if(err) {
						console.log('Error running test', err, testFile);
						var status = $('#' + divID + '_status');
						status.text('Error');
						status.css('color', 'red');
					} else {
						var status = $('#' + divID + '_status');
						status.text('Success');
						status.css('color', 'green');
						testResults.slideUp();
						// console.log('Finished running test', testFile);
					}

					var btn = $('#' + divID + '_button');
					btn.on('click', function() {
						testResults.slideToggle();
					})
					defered.resolve();
				});
		} catch(err) {
			console.error('Error Running nodeunit tester', err, testFile);
			defered.resolve();
		}
		return defered.promise;
	};
	return runTest;
};

var runTests = function() {
	var testDiv = $('#nodeunit_test_results');
	// testDiv.empty();
	var testFuncs = [];
	testFiles.forEach(function(testFile) {
		testFuncs.push(getRunTest(testFile, testDiv));
	});
	return testFuncs.reduce(q.when, q({}));
};

var numLoadDelay = 0;
var startCoreApp = function() {
	if(coreResourcesLoaded && localResourcesLoaded) {
		// win.showDevTools();
	} else {
		numLoadDelay += 1;
		if(numLoadDelay > 5) {
			win.showDevTools();
			console.log('numLoadDelay', numLoadDelay);
			setTimeout(startCoreApp, 100);
		} else {
			setTimeout(startCoreApp, 10);
		}
	}
};

/*
	When the window finishes loading start the core application.

	The application is started in a timeout-loop because some of the resources
	are asynchronously loaded upon start.  The application attempts to start
	every 10ms until those resources are loaded.
*/
window.onload = function(e) {
	setTimeout(startCoreApp, 10);
};

// gui.App.sharedData.appWindows.core.show();
// gui.App.sharedData.appWindows.core.showDevTools();<commit_msg>Commented out bad tests.<commit_after>console.log("ljswitchboard-kipling_tester index.js");

var gui = require('nw.gui');
var path = require('path');
var q = require('q');
var win = gui.Window.get();

var cwd = path.dirname(document.URL.split('file:///').join(''));
if(!path.isAbsolute(cwd)) {
	cwd = path.resolve(path.sep, cwd);
}

var nodeunit = require(path.normalize(path.join(cwd, '../node_modules/nodeunit')));
var nodeunit_recorder = require(path.normalize(path.join(cwd, 'nodeunit_recorder')));

var testFiles = [
	'test_kipling.js',
	// Execute Mock-Device compatable Tests
	'mock_module_tests/mock_device_selector.js',
	'mock_module_tests/mock_device_info.js',
	// 'mock_module_tests/mock_dashboard.js',

	// Execute Live-Device tests
	// 'module_tests/test_device_info.js',

	'finish_testing.js',
];
var test_dir = '../test';
for(var i = 0; i < testFiles.length; i++) {
	testFiles[i] = path.normalize(path.join(cwd, test_dir, testFiles[i]));
}

var package_loader = require('ljswitchboard-package_loader');
var gns = package_loader.getNameSpace();
var window_manager = require('ljswitchboard-window_manager');
var startDir = global[gns].info.startDir;
var handlebars = require('handlebars');
/*
	Function called to load the application's core resources.
	The resources are loaded from the ljswitchboard-static_files/static
	directory.
*/
var coreResourcesLoaded = false;
var loadCoreResources = function(resources) {
	global[gns].static_files.loadResources(document, resources)
	.then(function(res) {
		coreResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

/*
	Function called to load the application's local resources.
	The resources are loaded starting from the directory of the
	index.html/index.js file aka the cwd of the window.
*/
var localResourcesLoaded = false;
var loadLocalResources = function(resources) {
	global[gns].static_files.loadResources(document, resources, true)
	.then(function(res) {
		localResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

var loadResources = function(resources, isLocal) {
	var defered = q.defer();
	global[gns].static_files.loadResources(document, resources, isLocal)
	.then(function(res) {
		defered.resolve();
	}, function(err) {
		console.error('Error Loading resources', err);
		defered.reject(err);
	});
	return defered.promise;
};

var getUpdateTestResults = function(divID) {
	var cachedTestDiv;
	cachedTestDiv = undefined;
	var updateTestResults = function() {

		var savedText = nodeunit_recorder.getSavedText();
		if(cachedTestDiv) {
			cachedTestDiv.html(savedText);
		} else {
			cachedTestDiv = $(divID);
			cachedTestDiv.html(savedText);
		}
	};
	return updateTestResults;
};
var getRunTest = function(testFile, testDiv) {
	var testName = path.basename(testFile);
	var fileName = path.basename(testFile);
	var fileEnding = path.extname(testName);
	fileName = fileName.split(fileEnding).join('');

	var divID = fileName + '-test';
	var runTest = function() {
		var defered = q.defer();
		var str = [
			'
',
			'
',
				'Test: {{testName}}',
				'
',
					'Status: In Progress',
					'',
				'
',
			'
',
			'

Test!

',
			'
'
		].join('');
		var template = handlebars.compile(str);
		var newTxt = template({
			'id': divID,
			'testName':testName,
			'fileName': fileName
		});
		testDiv.append($(newTxt));
		try {
			var outputHTML = nodeunit_recorder.run(
				[testFile],
				{},
				getUpdateTestResults('#' + divID),
				function(err) {
					var testResults = $('#' + divID);
					if(err) {
						console.log('Error running test', err, testFile);
						var status = $('#' + divID + '_status');
						status.text('Error');
						status.css('color', 'red');
					} else {
						var status = $('#' + divID + '_status');
						status.text('Success');
						status.css('color', 'green');
						testResults.slideUp();
						// console.log('Finished running test', testFile);
					}

					var btn = $('#' + divID + '_button');
					btn.on('click', function() {
						testResults.slideToggle();
					})
					defered.resolve();
				});
		} catch(err) {
			console.error('Error Running nodeunit tester', err, testFile);
			defered.resolve();
		}
		return defered.promise;
	};
	return runTest;
};

var runTests = function() {
	var testDiv = $('#nodeunit_test_results');
	// testDiv.empty();
	var testFuncs = [];
	testFiles.forEach(function(testFile) {
		testFuncs.push(getRunTest(testFile, testDiv));
	});
	return testFuncs.reduce(q.when, q({}));
};

var numLoadDelay = 0;
var startCoreApp = function() {
	if(coreResourcesLoaded && localResourcesLoaded) {
		// win.showDevTools();
	} else {
		numLoadDelay += 1;
		if(numLoadDelay > 5) {
			win.showDevTools();
			console.log('numLoadDelay', numLoadDelay);
			setTimeout(startCoreApp, 100);
		} else {
			setTimeout(startCoreApp, 10);
		}
	}
};

/*
	When the window finishes loading start the core application.

	The application is started in a timeout-loop because some of the resources
	are asynchronously loaded upon start.  The application attempts to start
	every 10ms until those resources are loaded.
*/
window.onload = function(e) {
	setTimeout(startCoreApp, 10);
};

// gui.App.sharedData.appWindows.core.show();
// gui.App.sharedData.appWindows.core.showDevTools();<|endoftext|>