<commit_before>/**
 * @ngdoc directive
 * @name refigureApp.directive:pager
 * @restrict E
 * @description
 * Search Results
 * @example
 * <pager total="20" search-params="stateParams" default-sort="relevance" sort="vm.showSortDropdown"></pager>
 */
(function (angular) {
    'use strict';

    angular
        .module('refigureShared')
        .component('pager', {
            templateUrl: 'view/pager.component.html',
            controller: PagerCtrl,
            controllerAs: 'vm',
            bindings: {
                total: '<',
                searchParams: '=',
                defaultSort: '@',
                sort: '@',
                totalLabel: '@'
            }
        });

    PagerCtrl.$inject = ['$scope', '$state'];

    function PagerCtrl($scope, $state) {
        var vm = this;
        var defaults = {
            query: '',
            from: 0,
            size: 5,
            sortDirection: 'ASC',
            sortField: 'Metapublication.Title',
            Flagged: 0
        };

        vm.isMenuOpened = false;
        vm.sortBy = {
            relevance: {
                stateParams: {
                    from: 0,
                    sortDirection: '',
                    sortField: ''
                },
                name: 'relevance'
            },
            figCountDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'FiguresCount'
                },
                name: 'number of images - largest at top'
            },
            figCountAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'FiguresCount'
                },
                name: 'number of images - smallest at top'
            },
            nameAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'Metapublication.Title'
                },
                name: 'name - A..Z'
            },
            nameDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'Metapublication.Title'
                },
                name: 'name - Z..A'
            },
            visitsDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'Visit.Count'
                },
                name: 'popularity - most at top'
            },
            visitsAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'Visit.Count'
                },
                name: 'popularity - less at top'
            }
        };

        vm.queryFieldLabels = {
            'Metapublication.Keywords': 'Keywords'
        };

        vm.updateState = updateState;
        vm.resetQueryField = resetQueryField;
        vm.changeSort = changeSort;
        vm.$onInit = activate;

        //////////////////////////////////////////

        function activate() {
            vm.totalLabel = vm.totalLabel || 'Refigures';
            vm.sortKey = vm.defaultSort || 'relevance';
            angular.extend(defaults, vm.sortBy[vm.sortKey].stateParams);
            vm.searchParams = $state.params;
            angular.forEach(vm.searchParams, function (val, key) {
                if (val === undefined && angular.isDefined(defaults[key])) {
                    vm.searchParams[key] = defaults[key];
                }
            });
            updateState(vm.searchParams);

            $scope.$watch('vm.total', function () {
                if (vm.total) {
                    vm.paging = {
                        pages: Math.ceil(vm.total / vm.searchParams.size)
                    };
                    vm.paging.pageArr = new Array(vm.paging.pages);
                }
            });
            $scope.$on('$mdMenuOpen', toggleMenu);
            $scope.$on('$mdMenuClose', toggleMenu);

            if (vm.sort && vm.sort === 'false') {
                vm.sortBy = null;
            }
        }

        function toggleMenu() {
            vm.isMenuOpened = !vm.isMenuOpened;
        }

        function updateState(searchParams) {
            $state.go($state.current.name, searchParams);
        }

        function changeSort(key) {
            vm.sortKey = key;
            updateState(vm.sortBy[vm.sortKey].stateParams);
        }

        function resetQueryField() {
            $state.go($state.current.name, {queryField: null});
        }
    }

})(window.angular);
<commit_msg>+ date creation sort for metapublications<commit_after>/**
 * @ngdoc directive
 * @name refigureApp.directive:pager
 * @restrict E
 * @description
 * Search Results
 * @example
 * <pager total="20" search-params="stateParams" default-sort="relevance" sort="vm.showSortDropdown"></pager>
 */
(function (angular) {
    'use strict';

    angular
        .module('refigureShared')
        .component('pager', {
            templateUrl: 'view/pager.component.html',
            controller: PagerCtrl,
            controllerAs: 'vm',
            bindings: {
                total: '<',
                searchParams: '=',
                defaultSort: '@',
                sort: '@',
                totalLabel: '@'
            }
        });

    PagerCtrl.$inject = ['$scope', '$state'];

    function PagerCtrl($scope, $state) {
        var vm = this;
        var defaults = {
            query: '',
            from: 0,
            size: 5,
            sortDirection: 'ASC',
            sortField: 'Metapublication.Title',
            Flagged: 0
        };

        vm.isMenuOpened = false;
        vm.sortBy = {
            relevance: {
                stateParams: {
                    from: 0,
                    sortDirection: '',
                    sortField: ''
                },
                name: 'relevance'
            },
            figCountDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'FiguresCount'
                },
                name: 'number of images - largest at top'
            },
            figCountAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'FiguresCount'
                },
                name: 'number of images - smallest at top'
            },
            nameAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'Metapublication.Title'
                },
                name: 'name - A..Z'
            },
            nameDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'Metapublication.Title'
                },
                name: 'name - Z..A'
            },
            visitsDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'Visit.Count'
                },
                name: 'popularity - most at top'
            },
            visitsAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'Visit.Count'
                },
                name: 'popularity - less at top'
            },
            createdAsc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'ASC',
                    sortField: 'Metapublication.DateCreated'
                },
                name: 'creation date - older at top'
            },
            createdDesc: {
                stateParams: {
                    from: 0,
                    sortDirection: 'DESC',
                    sortField: 'Metapublication.DateCreated'
                },
                name: 'creation date - newer at top'
            }
        };

        vm.queryFieldLabels = {
            'Metapublication.Keywords': 'Keywords'
        };

        vm.updateState = updateState;
        vm.resetQueryField = resetQueryField;
        vm.changeSort = changeSort;
        vm.$onInit = activate;

        //////////////////////////////////////////

        function activate() {
            vm.totalLabel = vm.totalLabel || 'Refigures';
            vm.sortKey = vm.defaultSort || 'relevance';
            angular.extend(defaults, vm.sortBy[vm.sortKey].stateParams);
            vm.searchParams = $state.params;
            angular.forEach(vm.searchParams, function (val, key) {
                if (val === undefined && angular.isDefined(defaults[key])) {
                    vm.searchParams[key] = defaults[key];
                }
            });
            updateState(vm.searchParams);

            $scope.$watch('vm.total', function () {
                if (vm.total) {
                    vm.paging = {
                        pages: Math.ceil(vm.total / vm.searchParams.size)
                    };
                    vm.paging.pageArr = new Array(vm.paging.pages);
                }
            });
            $scope.$on('$mdMenuOpen', toggleMenu);
            $scope.$on('$mdMenuClose', toggleMenu);

            if (vm.sort && vm.sort === 'false') {
                vm.sortBy = null;
            }
        }

        function toggleMenu() {
            vm.isMenuOpened = !vm.isMenuOpened;
        }

        function updateState(searchParams) {
            $state.go($state.current.name, searchParams);
        }

        function changeSort(key) {
            vm.sortKey = key;
            updateState(vm.sortBy[vm.sortKey].stateParams);
        }

        function resetQueryField() {
            $state.go($state.current.name, {queryField: null});
        }
    }

})(window.angular);
<|endoftext|>


<commit_before>import Morph from './Morph.js';

import { Graph } from 'src/client/triples/triples.js';

export default class KnotInput extends Morph {
  get listSelector() { return '#list'}
  get input() { return this.get('#input'); }
  get list() { return this.get(this.listSelector); }
  get label() { return this.get('#label'); }

  async initialize() {
    this.windowTitle = "Knot Input";

    this.input.addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.onEnter();
      }
    });

    await this.prepareDatalist();
  }

  async prepareDatalist() {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    graph.getKnots().forEach(knot => {
      let option = document.createElement('option');

      option.innerHTML = knot.label();
      option.value = knot.url;
      option.dataset.url = knot.url;

      this.list.appendChild(option);
    });
  }

  // https://derickbailey.com/2016/03/23/get-a-data-attribute-value-from-the-selected-datalist-option/
  getURLStringFor() {
    var value = this.input.value;
    lively.notify('input value: ' + value);
    // TODO: check for empty value ('')
    // TODO: value could be a literal or a url
    var option = this.get(`${this.listSelector} [value='${value}']`);
    // value could also be an external url
    if(!option) return;
    lively.notify(option.innerHTML)
    let url = option.dataset.url;
    lively.notify('url: ' + url);
    return url;
  }
  getValue() { return this.input.value; }

  setLabel(text) { this.label.innerHTML = text; }
  setPlaceholder(text) { this.input.setAttribute('placeholder', text); }
  onEnter() {
    lively.notify(123 + this.getURLString());
  }
}<commit_msg>AUTO-COMMIT templates/knot-input.js<commit_after>import Morph from './Morph.js';

import { Graph } from 'src/client/triples/triples.js';

export default class KnotInput extends Morph {
  get listSelector() { return '#list'}
  get input() { return this.get('#input'); }
  get list() { return this.get(this.listSelector); }
  get label() { return this.get('#label'); }

  async initialize() {
    this.windowTitle = "Knot Input";

    this.input.addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.onEnter();
      }
    });

    await this.prepareDatalist();
  }

  async prepareDatalist() {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    graph.getKnots().forEach(knot => {
      let option = document.createElement('option');

      option.innerHTML = knot.label();
      option.value = knot.url;
      option.dataset.url = knot.url;

      this.list.appendChild(option);
    });
  }

  // https://derickbailey.com/2016/03/23/get-a-data-attribute-value-from-the-selected-datalist-option/
  getURLString() {
    var value = this.input.value;
    lively.notify('input value: ' + value);
    // TODO: check for empty value ('')
    // TODO: value could be a literal or a url
    var option = this.get(`${this.listSelector} [value='${value}']`);
    // value could also be an external url
    if(!option) return;
    lively.notify(option.innerHTML)
    let url = option.dataset.url;
    lively.notify('url: ' + url);
    return url;
  }
  getValue() { return this.input.value; }

  setLabel(text) { this.label.innerHTML = text; }
  setPlaceholder(text) { this.input.setAttribute('placeholder', text); }
  onEnter() {
    lively.notify(123 + this.getURLString());
  }
}<|endoftext|>


<commit_before>var Socket = function (url) {
    this.url = url;

    this.events = [];

    this.connected = false;

    this.triggerEvent = function (name, data, event) {
        var i = 0, len = this.events.length;
        for (; i < len; i++) {
            if (this.events[i].name === name) {
                this.events[i].callback(data, event);
            }
        }
    };

    this.addEvent = function (name, callback) {
        this.events.push({
            name: name,
            callback: callback
        });
    };

    this.removeEvent = function (callback) {
        var i = 0, len = this.events.length;
        for (; i < len; i++) {
            if (!this.events[i])
                continue;
            if (this.events[i].callback === callback) {
                this.events.splice(i, 1);
            }
        }
    };

    this.bindConnection = function () {
        var _this = this;

        this.connection.onopen = function (event) {
            _this.connected = true;

            _this.triggerEvent('connected', null, event);
        };

        this.connection.onmessage = function (event) {
            _this.triggerEvent('message', null, event);

            var incoming = JSON.parse(event.data);
            _this.triggerEvent(incoming.command, incoming.data, event);
        };

        this.connection.onclose = function (event) {
            _this.triggerEvent('disconnected', null, event);
        };
    };
};

Socket.prototype.connect = function (callback) {
    if (callback) {
        this.bind('connected', callback);
    }

    this.connection = new WebSocket(this.url);
    this.bindConnection();
};

Socket.prototype.isConnected = function () {
    return this.connected;
};

Socket.prototype.disconnect = function () {
    this.connection.close();
};

Socket.prototype.bind = function (name, callback) {
    this.addEvent(name, callback);
    return callback;
};

Socket.prototype.on = Socket.prototype.bind;

Socket.prototype.unbind = function (callback) {
    this.removeEvent(callback);
};

Socket.prototype.send = function (command, data) {
    var json = JSON.stringify({
        command: command,
        data: data
    });
    this.connection.send(json);
};
<commit_msg>Closes #1<commit_after>var Socket = function (url) {
    this.url = url;

    this.events = [];

    this.connected = false;

    this.triggerEvent = function (name, data, event) {
        var i = 0, len = this.events.length;
        for (; i < len; i++) {
            if (this.events[i].name === name) {
                this.events[i].callback(data, event);
            }
        }
    };

    this.addEvent = function (name, callback) {
        this.events.push({
            name: name,
            callback: callback
        });
    };

    this.removeEvent = function (callback) {
        var i = 0, len = this.events.length;
        for (; i < len; i++) {
            if (!this.events[i])
                continue;
            if (this.events[i].callback === callback) {
                this.events.splice(i, 1);
            }
        }
    };

    this.bindConnection = function () {
        var _this = this;

        this.connection.onopen = function (event) {
            _this.connected = true;

            _this.triggerEvent('connected', null, event);
        };

        this.connection.onmessage = function (event) {
            _this.triggerEvent('message', null, event);

            var incoming = JSON.parse(event.data);
            _this.triggerEvent(incoming.command, incoming.data, event);
        };

        this.connection.onclose = function (event) {
            _this.connected = false;

            _this.triggerEvent('disconnected', null, event);
        };
    };
};

Socket.prototype.connect = function (callback) {
    if (callback) {
        this.bind('connected', callback);
    }

    this.connection = new WebSocket(this.url);
    this.bindConnection();
};

Socket.prototype.isConnected = function () {
    return this.connected;
};

Socket.prototype.disconnect = function () {
    this.connection.close();
};

Socket.prototype.bind = function (name, callback) {
    this.addEvent(name, callback);
    return callback;
};

Socket.prototype.on = Socket.prototype.bind;

Socket.prototype.unbind = function (callback) {
    this.removeEvent(callback);
};

Socket.prototype.send = function (command, data) {
    var json = JSON.stringify({
        command: command,
        data: data
    });
    this.connection.send(json);
};
<|endoftext|>


<commit_before>module.exports = function checkAndSetPost (req, res, next) {
  var postId = req.param('postId')

  var fail = function (log, responseType) {
    sails.log.debug(`policy: checkAndSetPost: ${log}`)
    res[responseType || 'forbidden']()
  }

  return Post.find(postId, {withRelated: 'communities'})
  .then(post => {
    if (!post) return fail(`post ${postId} not found`, 'notFound')

    res.locals.post = post

    var ok = Admin.isSignedIn(req) ||
      (res.locals.publicAccessAllowed && post.isPublic())

    return (ok ? Promise.resolve(true)
      : Post.isVisibleToUser(post.id, req.session.userId))
    .then(allowed => {
      if (allowed) {
        next()
      } else {
        fail('not allowed')
      }
      return null
    })
  })
  .catch(err => fail(err.message, 'serverError'))
}
<commit_msg>fix bad error handling in dev<commit_after>module.exports = function checkAndSetPost (req, res, next) {
  var postId = req.param('postId')

  var fail = function (log, responseType, err) {
    sails.log.debug(`policy: checkAndSetPost: ${log}`)
    res[responseType || 'forbidden'](err)
  }

  return Post.find(postId, {withRelated: 'communities'})
  .then(post => {
    if (!post) return fail(`post ${postId} not found`, 'notFound')

    res.locals.post = post

    var ok = Admin.isSignedIn(req) ||
      (res.locals.publicAccessAllowed && post.isPublic())

    return (ok ? Promise.resolve(true)
      : Post.isVisibleToUser(post.id, req.session.userId))
    .then(allowed => {
      if (allowed) {
        next()
      } else {
        fail('not allowed')
      }
      return null
    })
  })
  .catch(err => fail(err.message, 'serverError', err))
}
<|endoftext|>


<commit_before>var sqlite3 = require('sqlite3');
var _ = require('underscore');

module.exports = function(callback) {

    var db = new sqlite3.Database('db/storage/main.sqlite', setupDb);

    function setupDb(err) {
        if (err) throw err;
        db.serialize(function(){

            db.run('CREATE TABLE Client ("id" INTEGER PRIMARY KEY ASC, "client_code" TEXT, "client_name" TEXT);', handleCallback);

            db.run('CREATE TABLE Server ('+
            'id INTEGER PRIMARY KEY ASC,'+
            'client_id INTEGER,'+
            'server_name TEXT,'+
            'ssh_host TEXT,'+
            'ssh_username TEXT'+
            ');', handleCallback);

            db.run('CREATE TABLE Profile ('+
            'id INTEGER PRIMARY KEY ASC,'+
            'server_id INTEGER,'+
            'profile_name TEXT,'+
            'magento_path TEXT,'+
            'tables TEXT,'+
            'excluded_tables TEXT'+
            ');', function(err){
                handleCallback.call(this, err);
                callback();
            });
        });
    }
    function handleCallback(err) {
        if (err) throw err;
    }
};<commit_msg>--setup-db now creates storage directory if not exists<commit_after>var fs = require('fs');
var sqlite3 = require('sqlite3');
var _ = require('underscore');

module.exports = function(callback) {
    var db;

    fs.mkdir('db/storage', function(err){
        db = new sqlite3.Database('db/storage/main.sqlite', setupDb);
    });

    function setupDb(err) {
        if (err) throw err;
        db.serialize(function(){

            db.run('CREATE TABLE Client ("id" INTEGER PRIMARY KEY ASC, "client_code" TEXT, "client_name" TEXT);', handleCallback);

            db.run('CREATE TABLE Server ('+
            'id INTEGER PRIMARY KEY ASC,'+
            'client_id INTEGER,'+
            'server_name TEXT,'+
            'ssh_host TEXT,'+
            'ssh_username TEXT'+
            ');', handleCallback);

            db.run('CREATE TABLE Profile ('+
            'id INTEGER PRIMARY KEY ASC,'+
            'server_id INTEGER,'+
            'profile_name TEXT,'+
            'magento_path TEXT,'+
            'tables TEXT,'+
            'excluded_tables TEXT'+
            ');', function(err){
                handleCallback.call(this, err);
                callback();
            });
        });
    }
    function handleCallback(err) {
        if (err) throw err;
    }
};<|endoftext|>


<commit_before>/*
 *
 * Assignment 1 web app
 *
 * Copyright (c) 2016  Monash University
 *
 * Written by Michael Wybrow
 *
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
*/

function CameraVideoPageController(callback)
{
    var self = this;

    this.initialisationCallback = callback;

    // Workaround a bug where the map canvas sometimes doesn't get
    // the correct height: Delay setup of video for a tenth of a second.
    setTimeout(initialiseCamera, 100);

    self.setHeadsUpDisplayHTML = function(htmlString)
    {
        if (typeof(htmlString) == 'number')
        {
            // If argument is a number, convert to a string.
            htmlString = htmlString.toString();
        }

        if (typeof(htmlString) != 'string')
        {
            console.log("setHeadsUpDisplayHTML: Argument is not a string.");
            return;
        }

        if (htmlString.length == 0)
        {
            console.log("setHeadsUpDisplayHTML: Given an empty string.");
            return;
        }

        document.getElementById("hud").innerHTML = htmlString;
    }

    self.displayMessage = function(message, timeout)
    {
        if (timeout === undefined)
        {
            // Timeout argument not specifed, use default.
            timeout = 1000;
        }

        if (typeof(message) == 'number')
        {
            // If argument is a number, convert to a string.
            message = message.toString();
        }

        if (typeof(message) != 'string')
        {
            console.log("displayMessage: Argument is not a string.");
            return;
        }

        if (message.length == 0)
        {
            console.log("displayMessage: Given an empty string.");
            return;
        }

        var snackbarContainer = document.getElementById('toast');
        var data = {
            message: message,
            timeout: timeout
        };
        if (snackbarContainer && snackbarContainer.hasOwnProperty("MaterialSnackbar"))
        {
            snackbarContainer.MaterialSnackbar.showSnackbar(data);
        }
    };

    function initialiseCamera()
    {
        var videoContainer = document.getElementById("video-container");
        videoContainer.innerHTML = '<video autoplay class="bg-video"></video>' +
            '<object class="crosshairs" type="image/svg+xml" data="crosshairs.svg"></object>';

        // Support different browsers
        navigator.getUserMedia = navigator.getUserMedia ||
                                 navigator.webkitGetUserMedia ||
                                 navigator.mozGetUserMedia ||
                                 navigator.msGetUserMedia;

        if (typeof MediaStreamTrack !== 'undefined')
        {
            MediaStreamTrack.getSources(gotSources);
        }
        else
        {
            self.displayMessage("Camera not supported");
        }

        if (self.initialisationCallback)
        {
            self.initialisationCallback();
        }
    }

    function successCallback(stream)
    {
        window.stream = stream; // make stream available to console
        var videoElement = document.querySelector("video");
        videoElement.src = window.URL.createObjectURL(stream);
        videoElement.play();
    }

    function errorCallback(error)
    {
        self.displayMessage("Camera permission error");
        console.log("navigator.getUserMedia error: ", error);
    }

    function sourceSelected(videoSource)
    {
        if (!!window.stream)
        {
            videoElement.src = null;
            window.stream.stop();
        }

        var constraints = {
            video: {
                optional: [{sourceId: videoSource}]
            },
            audio: false
        };

        navigator.getUserMedia(constraints, successCallback, errorCallback);
    }

    function gotSources(sourceInfos)
    {
        var videoSource = null;

        for (var i = 0; i != sourceInfos.length; ++i)
        {
            var sourceInfo = sourceInfos[i];
            if (sourceInfo.kind === 'video')
            {
                videoSource = sourceInfo.id;
            }
            else
            {
                console.log('Some other kind of source: ', sourceInfo);
            }
        }

        sourceSelected(videoSource);
    }
}
<commit_msg>Update CameraVideoPageController.js<commit_after>/*
 *
 * Assignment 1 web app
 *
 * Copyright (c) 2016  Monash University
 *
 * Written by Michael Wybrow
 *
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
*/

function CameraVideoPageController(callback)
{
    var self = this;

    this.initialisationCallback = callback;

    // Workaround a bug where the map canvas sometimes doesn't get
    // the correct height: Delay setup of video for a tenth of a second.
    setTimeout(initialiseCamera, 100);

    self.setHeadsUpDisplayHTML = function(htmlString)
    {
        if (typeof(htmlString) == 'number')
        {
            // If argument is a number, convert to a string.
            htmlString = htmlString.toString();
        }

        if (typeof(htmlString) != 'string')
        {
            console.log("setHeadsUpDisplayHTML: Argument is not a string.");
            return;
        }

        if (htmlString.length == 0)
        {
            console.log("setHeadsUpDisplayHTML: Given an empty string.");
            return;
        }

        document.getElementById("hud").innerHTML = htmlString;
    }

    self.displayMessage = function(message, timeout)
    {
        if (timeout === undefined)
        {
            // Timeout argument not specifed, use default.
            timeout = 1000;
        }

        if (typeof(message) == 'number')
        {
            // If argument is a number, convert to a string.
            message = message.toString();
        }

        if (typeof(message) != 'string')
        {
            console.log("displayMessage: Argument is not a string.");
            return;
        }

        if (message.length == 0)
        {
            console.log("displayMessage: Given an empty string.");
            return;
        }

        var snackbarContainer = document.getElementById('toast');
        var data = {
            message: message,
            timeout: timeout
        };
        if (snackbarContainer && snackbarContainer.hasOwnProperty("MaterialSnackbar"))
        {
            snackbarContainer.MaterialSnackbar.showSnackbar(data);
        }
    };

    function initialiseCamera()
    {
        var videoContainer = document.getElementById("video-container");
        videoContainer.innerHTML = '<video autoplay class="bg-video"></video>' +
            '<object class="crosshairs" type="image/svg+xml" data="images/crosshairs.svg"></object>';

        // Support different browsers
        navigator.getUserMedia = navigator.getUserMedia ||
                                 navigator.webkitGetUserMedia ||
                                 navigator.mozGetUserMedia ||
                                 navigator.msGetUserMedia;

        if (typeof MediaStreamTrack !== 'undefined')
        {
            MediaStreamTrack.getSources(gotSources);
        }
        else
        {
            self.displayMessage("Camera not supported");
        }

        if (self.initialisationCallback)
        {
            self.initialisationCallback();
        }
    }

    function successCallback(stream)
    {
        window.stream = stream; // make stream available to console
        var videoElement = document.querySelector("video");
        videoElement.src = window.URL.createObjectURL(stream);
        videoElement.play();
    }

    function errorCallback(error)
    {
        self.displayMessage("Camera permission error");
        console.log("navigator.getUserMedia error: ", error);
    }

    function sourceSelected(videoSource)
    {
        if (!!window.stream)
        {
            videoElement.src = null;
            window.stream.stop();
        }

        var constraints = {
            video: {
                optional: [{sourceId: videoSource}]
            },
            audio: false
        };

        navigator.getUserMedia(constraints, successCallback, errorCallback);
    }

    function gotSources(sourceInfos)
    {
        var videoSource = null;

        for (var i = 0; i != sourceInfos.length; ++i)
        {
            var sourceInfo = sourceInfos[i];
            if (sourceInfo.kind === 'video')
            {
                videoSource = sourceInfo.id;
            }
            else
            {
                console.log('Some other kind of source: ', sourceInfo);
            }
        }

        sourceSelected(videoSource);
    }
}
<|endoftext|>


<commit_before>'use strict';

// Forked from https://github.com/floatdrop/timed-out

module.exports = function (req, delays) {
	if (req.timeoutTimer) {
		return req;
	}

	const host = req._headers ? (' to ' + req._headers.host) : '';

	function throwESOCKETTIMEDOUT() {
		req.abort();
		const e = new Error('Socket timed out on request' + host);
		e.code = 'ESOCKETTIMEDOUT';
		req.emit('error', e);
	}

	function throwETIMEDOUT() {
		req.abort();
		const e = new Error('Connection timed out on request' + host);
		e.code = 'ETIMEDOUT';
		req.emit('error', e);
	}

	if (delays.connect !== undefined) {
		req.timeoutTimer = setTimeout(throwETIMEDOUT, delays.connect);
	}

	if (delays.request !== undefined) {
		req.requestTimeoutTimer = setTimeout(() => {
			clear();

			if (req.connection.connecting) {
				throwETIMEDOUT();
			} else {
				throwESOCKETTIMEDOUT();
			}
		}, delays.request);
	}

	// Clear the connection timeout timer once a socket is assigned to the
	// request and is connected.
	req.on('socket', socket => {
		// Socket may come from Agent pool and may be already connected.
		if (!socket.connecting) {
			connect();
			return;
		}

		socket.once('connect', connect);
	});

	function clear() {
		if (req.timeoutTimer) {
			clearTimeout(req.timeoutTimer);
			req.timeoutTimer = null;
		}
	}

	function connect() {
		clear();

		if (delays.socket !== undefined) {
			// Abort the request if there is no activity on the socket for more
			// than `delays.socket` milliseconds.
			req.setTimeout(delays.socket, throwESOCKETTIMEDOUT);
		}

		req.on('end', () => {
			// The request is finished, cancel request timeout.
			clearTimeout(req.requestTimeoutTimer);
		});
	}

	return req.on('error', clear);
};
<commit_msg>Properly clear `requestTimeoutTimer` timeout<commit_after>'use strict';

// Forked from https://github.com/floatdrop/timed-out

module.exports = function (req, delays) {
	if (req.timeoutTimer) {
		return req;
	}

	const host = req._headers ? (' to ' + req._headers.host) : '';

	function throwESOCKETTIMEDOUT() {
		req.abort();
		const e = new Error('Socket timed out on request' + host);
		e.code = 'ESOCKETTIMEDOUT';
		req.emit('error', e);
	}

	function throwETIMEDOUT() {
		req.abort();
		const e = new Error('Connection timed out on request' + host);
		e.code = 'ETIMEDOUT';
		req.emit('error', e);
	}

	if (delays.connect !== undefined) {
		req.timeoutTimer = setTimeout(throwETIMEDOUT, delays.connect);
	}

	if (delays.request !== undefined) {
		req.requestTimeoutTimer = setTimeout(() => {
			clear();

			if (req.connection.connecting) {
				throwETIMEDOUT();
			} else {
				throwESOCKETTIMEDOUT();
			}
		}, delays.request);
	}

	// Clear the connection timeout timer once a socket is assigned to the
	// request and is connected.
	req.on('socket', socket => {
		// Socket may come from Agent pool and may be already connected.
		if (!socket.connecting) {
			connect();
			return;
		}

		socket.once('connect', connect);
	});

	function clear() {
		if (req.timeoutTimer) {
			clearTimeout(req.timeoutTimer);
			req.timeoutTimer = null;
		}
	}

	function connect() {
		clear();

		if (delays.socket !== undefined) {
			// Abort the request if there is no activity on the socket for more
			// than `delays.socket` milliseconds.
			req.setTimeout(delays.socket, throwESOCKETTIMEDOUT);
		}

		req.on('response', res => {
			res.on('end', () => {
				// The request is finished, cancel request timeout.
				clearTimeout(req.requestTimeoutTimer);
			});
		});
	}

	return req.on('error', clear);
};
<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename);

const Intel = require('./Intel.js');
const rp = require('request-promise');

const iptool = require('ip');

class Cymon2Intel extends Intel {

  async enrichAlarm(alarm) {
    const ip = alarm["p.dest.ip"];

    if(ip) {
      const result = await this.loadFromCymon(ip);
      if(result["total"]) {
        alarm["p.security.numOfReportSources2"] = result["total"];
      }
    }

    return alarm;
  }

  async loadFromCymon(ip) {

    if(!ip) {
      return;
    }

    if(!iptool.isV4Format(ip)) { // only support v4 yet..
      return;
    }

    const uri = `https://api.cymon.io/v2/ioc/search/ip/${ip}`

    const body = await rp({
      uri: uri,
      method: 'GET',
      family: 4,
      json: true,
      timeout: 10000 //ms
    }).catch((err) => {
      log.error("Failed to request info from cymon, err:", err);
      return null;
    });

    if(body) {
      try {
        const json = JSON.parse(body);

        return json;

      } catch(err) {
        log.error("Failed to parse json output:", body, "err:", err);
      }

    }

    return null;
  }

}

module.exports = Cymon2Intel;
<commit_msg>bug fix<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename);

const Intel = require('./Intel.js');
const rp = require('request-promise');

const iptool = require('ip');

class Cymon2Intel extends Intel {

  async enrichAlarm(alarm) {
    const ip = alarm["p.dest.ip"];

    if(ip) {
      const result = await this.loadFromCymon(ip);
      if(result["total"] !== undefined) {
        alarm["p.security.numOfReportSources2"] = result["total"];
      }
    }

    return alarm;
  }

  async loadFromCymon(ip) {

    if(!ip) {
      return;
    }

    if(!iptool.isV4Format(ip)) { // only support v4 yet..
      return;
    }

    const uri = `https://api.cymon.io/v2/ioc/search/ip/${ip}`

    const body = await rp({
      uri: uri,
      method: 'GET',
      family: 4,
      json: true,
      timeout: 10000 //ms
    }).catch((err) => {
      log.error("Failed to request info from cymon, err:", err);
      return null;
    });

    if(body) {
      try {
        const json = JSON.parse(body);

        return json;

      } catch(err) {
        log.error("Failed to parse json output:", body, "err:", err);
      }

    }

    return null;
  }

}

module.exports = Cymon2Intel;
<|endoftext|>


<commit_before>import generateData from './data-generator.js';
import train from './train.js';

let eInTotal = 0;
let eOutTotal = 0;

for (let i = 0; i < 5000; i++) {
    let generatedData = generateData(20, true),
        { theta, s, eIn} = train(generatedData);
    eInTotal += eIn;
    eOutTotal += 0.5 + 0.3 * s * (Math.abs(theta) - 1);
}

console.log(`Ein: ${eInTotal / 5000}`);
console.log(`Eout: ${eOutTotal / 5000}`);
<commit_msg>Refactor hw2 Q16 & Q17 code<commit_after>import generateData from './data-generator.js';
import train from './train.js';

const CYCLE_COUNT = 5000;
const DATA_LENGTH = 20;
let eInTotal = 0,
    eOutTotal = 0,
    generatedData;

for (let i = 0; i < CYCLE_COUNT; i++) {
    generatedData = generateData(DATA_LENGTH);
    let { theta, s, eIn } = train(generatedData);
    eInTotal += eIn;
    eOutTotal += 0.5 + 0.3 * s * (Math.abs(theta) - 1);
}

console.log(`Ein: ${eInTotal / CYCLE_COUNT}`);
console.log(`Eout: ${eOutTotal / CYCLE_COUNT}`);
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
        bboxcache: {
            default: {
                files: {
                    'static/dist/bboxcache.json': ['static/map/*.svg'],
                },
            },
        },
        bower_concat: {
            all: {
                dest: 'static/dist/js/bower-libs.js',
                cssDest: 'static/dist/css/bower-libs.css',
                dependencies: {
                    'kartograph.js': ['jquery'],
                    'qtip2': ['jquery'],
                    'raphael-pan-zoom': ['raphael'],
                },
                mainFiles: {
                    'raphael-pan-zoom': 'src/raphael.pan-zoom.js',
                    'angular-i18n': 'angular-locale_cs-cz.js'
                },
                exclude: ['proso-apps-js']
            }
        },
        concat: {
            geography: {
                src: [
                  'static/dist/js/bbox.js',
                  'static/js/*.js',
                  'static/dist/js/translations.js'
                ],
                dest: 'static/dist/js/geography.js'
            }
        },
        copy: {
            'above-fold': {
                src: 'static/dist/css/above-fold.css',
                dest: 'templates/dist/above-fold.css'
            },
            'images': {
                expand: true,
                cwd: 'static/img',
                src: ['**'],
                dest: 'static/dist/img/'
            },
            'fonts': {
                expand: true,
                cwd: 'bower_components/bootstrap/fonts/',
                src: ['**'],
                dest: 'static/dist/fonts/'
            },
            'proso-apps-js': {
                src: 'bower_components/proso-apps-js/proso-apps-all.js',
                dest: 'static/dist/js/proso-apps-all.js'
            }
        },
        html2js: {
            options: {
                base: '.',
                module: 'proso.geography.templates',
                singleModule: true,
                useStric: true
            },
            geography: {
                src: ['static/tpl/*.html'],
                dest: 'static/dist/js/geography.html.js',
            }
        },
        jshint: {
            options: {
                "undef": true,
                "unused": true,
                "browser": true,
                "globals": {
                    "angular": false,
                    "bboxCache": false,
                    "chroma": false,
                    "console": false,
                    "gettext": false,
                    "jQuery": false,
                },
                "maxcomplexity": 6,
                "maxstatements": 20,
                "maxdepth" : 3,
                "maxparams": 12,
                "predef": ["Kartograph"],
            },
            dist: {
                src: 'static/js/',
            }
        },
        nggettext_compile: {
            all: {
                src: ['static/po/*.po'],
                dest:'static/dist/js/translations.js',
            },
        },
        nggettext_extract: {
            pot: {
                src: [
                    'static/js/*.js',
                    'static/tpl/*.html'
                ],
                dest: 'static/dist/client.pot',
            },
        },
        sass: {
            options: {
                style: "compressed"
            },
            geography: {
                files: [{
                    expand: true,
                    cwd: 'static/sass',
                    src: ['*.sass'],
                    dest: 'static/dist/css',
                    ext: '.css'
                }]
            }
        },
        shell: {
            bower_install: {
                command: 'node_modules/bower/bin/bower install -f'
            },
            makemessages: {
                command: '../manage.py makemessages --all --ignore=node_modules/*  && ../manage.py makemessages --all --domain djangojs --ignore=node_modules/* --ignore=bower_components/* --ignore=static/dist/*'
            }
        },
        'string-replace': {
            bboxcache: {
                options: {
                    replacements: [{
                        pattern: '{{bboxes}}',
                        replacement: "<%= grunt.file.read('static/dist/bboxcache.json') %>"
                    }]
                },
                src: ['static/jstpl/bbox.js'],
                dest: 'static/dist/js/bbox.js',
            }
        },
        uglify: {
            libs: {
                options: {
                    mangle: {
                        except: ['Kartograph', 'Raphael', 'gettextCatalog']
                    },
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    sourceMapName: 'static/dist/js/bower-libs.min.js.map'
                },
                src: 'static/dist/js/bower-libs.js',
                dest: 'static/dist/js/bower-libs.min.js'
            },
            geography: {
                options: {
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    sourceMapName: 'static/dist/geography.min.js.map'
                },
                src: 'static/dist/js/geography.js',
                dest: 'static/dist/js/geography.min.js'
            },
            'geography-tpls': {
                options: {
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    sourceMapName: 'static/dist/geography-tpls.min.js.map'
                },
                src: 'static/dist/js/geography-tpls.js',
                dest: 'static/dist/js/geography-tpls.min.js'
            },

        },
        watch: {
            'geography-js': {
                files: 'static/js/*.js',
                tasks: ['concat:geography', 'uglify:geography']
            },
            'geography-css': {
                files: 'static/sass/*.sass',
                tasks: ['sass:geography', 'copy:above-fold']
            },
            'geography-tpls': {
                files: 'static/tpl/*.html',
                tasks: ['html2js:geography', 'concat:geography', 'uglify:geography']
            },
            'geography-nggettext_compile': {
                files: '<%= nggettext_compile.all.src %>',
                tasks: ['nggettext_compile']
            },
            'geography-nggettext_extract': {
                files: '<%= nggettext_extract.pot.src %>',
                tasks: ['nggettext_extract']
            }
        }
    });

    grunt.loadNpmTasks('grunt-bower-concat');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-string-replace');
    grunt.loadNpmTasks('grunt-html2js');
    grunt.loadNpmTasks('grunt-angular-gettext');

    grunt.registerTask('bboxcache-all', ['bboxcache', 'string-replace:bboxcache']);
    grunt.registerTask('makemessages', ['shell:makemessages']);
    grunt.registerTask('collect-libs', ['bower_concat:all', 'uglify:libs', 'copy:fonts', 'copy:proso-apps-js']);
    grunt.registerTask('prepare-libs', ['shell:bower_install', 'collect-libs']);
    grunt.registerTask('prepare', ['jshint', 'html2js:geography', 'concat:geography', 'uglify:geography', 'sass:geography', 'copy:above-fold', 'copy:images']);
    grunt.registerTask('default', ['bboxcache-all', 'nggettext_compile', 'prepare-libs', 'prepare']);

    /* CUSTOM TASKS */

    grunt.registerMultiTask('bboxcache', 'Precompute bbox of svg paths.', function() {

        var raphael = require('node-raphael');
        var DomJS = require("dom-js").DomJS;
        var RANDOM_CONST = 42;

        function mapNameFromFilepath (filepath) {
            var splittedPath = filepath.split('/');
            var filename = splittedPath[splittedPath.length -1];
            return filename.split('.')[0];
        }

        // Iterate over all specified file groups.
        this.files.forEach(function(f) {
            var cache = {
                bboxes : {},
                maps : {},
            };

            f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).map(function(filepath) {

                var domjs = new DomJS();

                domjs.parse(grunt.file.read(filepath), function(err, dom) {
                    var mapName = mapNameFromFilepath(filepath);
                    var map = {
                        width :  parseInt(dom.attributes.width),
                        height :  parseInt(dom.attributes.height),
                    };
                    cache.maps[mapName] = map;

                    raphael.generate(RANDOM_CONST, RANDOM_CONST, function draw(paper) {
                        dom.children.filter(function(e) {
                            return e.name == 'g';
                        }).map(function (e) {
                            return e.children.filter(function(ch) {
                                return ch.name == 'path' && ch.attributes['data-code'];
                            }).map(function(ch) {
                                var d = ch.attributes.d;
                                var code = ch.attributes['data-code'];
                                if (code) {
                                    var path = paper.path(d);
                                    var bbox =  path.getBBox();
                                    var keys = ['x', 'y', 'cx', 'cy', 'x2', 'y2', 'width', 'height'];
                                    for (var j = 0; j < keys.length; j++) {
                                        bbox[keys[j]] = Math.round(bbox[keys[j]]);
                                    }
                                    bbox.map = mapName;
                                    if (!cache.bboxes[code]) {
                                        cache.bboxes[code] = bbox;
                                    }
                                }
                            });
                        });
                    });
                });
                return;
            });

            // Write the destination file.
            grunt.file.write(f.dest, JSON.stringify(cache));

            // Print a success message.
            grunt.log.writeln('File "' + f.dest + '" created.');
        });
    });
};
<commit_msg>Fix grunt watch:geography-js<commit_after>module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
        bboxcache: {
            default: {
                files: {
                    'static/dist/bboxcache.json': ['static/map/*.svg'],
                },
            },
        },
        bower_concat: {
            all: {
                dest: 'static/dist/js/bower-libs.js',
                cssDest: 'static/dist/css/bower-libs.css',
                dependencies: {
                    'kartograph.js': ['jquery'],
                    'qtip2': ['jquery'],
                    'raphael-pan-zoom': ['raphael'],
                },
                mainFiles: {
                    'raphael-pan-zoom': 'src/raphael.pan-zoom.js',
                    'angular-i18n': 'angular-locale_cs-cz.js'
                },
                exclude: ['proso-apps-js']
            }
        },
        concat: {
            geography: {
                src: [
                  'static/dist/js/bbox.js',
                  'static/js/*.js',
                  'static/dist/js/translations.js'
                ],
                dest: 'static/dist/js/geography.js'
            }
        },
        copy: {
            'above-fold': {
                src: 'static/dist/css/above-fold.css',
                dest: 'templates/dist/above-fold.css'
            },
            'images': {
                expand: true,
                cwd: 'static/img',
                src: ['**'],
                dest: 'static/dist/img/'
            },
            'fonts': {
                expand: true,
                cwd: 'bower_components/bootstrap/fonts/',
                src: ['**'],
                dest: 'static/dist/fonts/'
            },
            'proso-apps-js': {
                src: 'bower_components/proso-apps-js/proso-apps-all.js',
                dest: 'static/dist/js/proso-apps-all.js'
            }
        },
        html2js: {
            options: {
                base: '.',
                module: 'proso.geography.templates',
                singleModule: true,
                useStric: true
            },
            geography: {
                src: ['static/tpl/*.html'],
                dest: 'static/dist/js/geography.html.js',
            }
        },
        jshint: {
            options: {
                "undef": true,
                "unused": true,
                "browser": true,
                "globals": {
                    "angular": false,
                    "bboxCache": false,
                    "chroma": false,
                    "console": false,
                    "gettext": false,
                    "jQuery": false,
                },
                "maxcomplexity": 6,
                "maxstatements": 20,
                "maxdepth" : 3,
                "maxparams": 12,
                "predef": ["Kartograph"],
            },
            dist: {
                src: 'static/js/',
            }
        },
        nggettext_compile: {
            all: {
                src: ['static/po/*.po'],
                dest:'static/dist/js/translations.js',
            },
        },
        nggettext_extract: {
            pot: {
                src: [
                    'static/js/*.js',
                    'static/tpl/*.html'
                ],
                dest: 'static/dist/client.pot',
            },
        },
        sass: {
            options: {
                style: "compressed"
            },
            geography: {
                files: [{
                    expand: true,
                    cwd: 'static/sass',
                    src: ['*.sass'],
                    dest: 'static/dist/css',
                    ext: '.css'
                }]
            }
        },
        shell: {
            bower_install: {
                command: 'node_modules/bower/bin/bower install -f'
            },
            makemessages: {
                command: '../manage.py makemessages --all --ignore=node_modules/*  && ../manage.py makemessages --all --domain djangojs --ignore=node_modules/* --ignore=bower_components/* --ignore=static/dist/*'
            }
        },
        'string-replace': {
            bboxcache: {
                options: {
                    replacements: [{
                        pattern: '{{bboxes}}',
                        replacement: "<%= grunt.file.read('static/dist/bboxcache.json') %>"
                    }]
                },
                src: ['static/jstpl/bbox.js'],
                dest: 'static/dist/js/bbox.js',
            }
        },
        uglify: {
            libs: {
                options: {
                    mangle: {
                        except: ['Kartograph', 'Raphael', 'gettextCatalog']
                    },
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    sourceMapName: 'static/dist/js/bower-libs.min.js.map'
                },
                src: 'static/dist/js/bower-libs.js',
                dest: 'static/dist/js/bower-libs.min.js'
            },
            geography: {
                options: {
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    sourceMapName: 'static/dist/geography.min.js.map'
                },
                src: 'static/dist/js/geography.js',
                dest: 'static/dist/js/geography.min.js'
            },
            'geography-tpls': {
                options: {
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    sourceMapName: 'static/dist/geography-tpls.min.js.map'
                },
                src: 'static/dist/js/geography-tpls.js',
                dest: 'static/dist/js/geography-tpls.min.js'
            },

        },
        watch: {
            'geography-js': {
                files: '<%= concat.geography.src %>',
                tasks: ['concat:geography', 'uglify:geography']
            },
            'geography-css': {
                files: 'static/sass/*.sass',
                tasks: ['sass:geography', 'copy:above-fold']
            },
            'geography-tpls': {
                files: 'static/tpl/*.html',
                tasks: ['html2js:geography', 'concat:geography', 'uglify:geography']
            },
            'geography-nggettext_compile': {
                files: '<%= nggettext_compile.all.src %>',
                tasks: ['nggettext_compile']
            },
            'geography-nggettext_extract': {
                files: '<%= nggettext_extract.pot.src %>',
                tasks: ['nggettext_extract']
            }
        }
    });

    grunt.loadNpmTasks('grunt-bower-concat');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-string-replace');
    grunt.loadNpmTasks('grunt-html2js');
    grunt.loadNpmTasks('grunt-angular-gettext');

    grunt.registerTask('bboxcache-all', ['bboxcache', 'string-replace:bboxcache']);
    grunt.registerTask('makemessages', ['shell:makemessages']);
    grunt.registerTask('collect-libs', ['bower_concat:all', 'uglify:libs', 'copy:fonts', 'copy:proso-apps-js']);
    grunt.registerTask('prepare-libs', ['shell:bower_install', 'collect-libs']);
    grunt.registerTask('prepare', ['jshint', 'html2js:geography', 'concat:geography', 'uglify:geography', 'sass:geography', 'copy:above-fold', 'copy:images']);
    grunt.registerTask('default', ['bboxcache-all', 'nggettext_compile', 'prepare-libs', 'prepare']);

    /* CUSTOM TASKS */

    grunt.registerMultiTask('bboxcache', 'Precompute bbox of svg paths.', function() {

        var raphael = require('node-raphael');
        var DomJS = require("dom-js").DomJS;
        var RANDOM_CONST = 42;

        function mapNameFromFilepath (filepath) {
            var splittedPath = filepath.split('/');
            var filename = splittedPath[splittedPath.length -1];
            return filename.split('.')[0];
        }

        // Iterate over all specified file groups.
        this.files.forEach(function(f) {
            var cache = {
                bboxes : {},
                maps : {},
            };

            f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).map(function(filepath) {

                var domjs = new DomJS();

                domjs.parse(grunt.file.read(filepath), function(err, dom) {
                    var mapName = mapNameFromFilepath(filepath);
                    var map = {
                        width :  parseInt(dom.attributes.width),
                        height :  parseInt(dom.attributes.height),
                    };
                    cache.maps[mapName] = map;

                    raphael.generate(RANDOM_CONST, RANDOM_CONST, function draw(paper) {
                        dom.children.filter(function(e) {
                            return e.name == 'g';
                        }).map(function (e) {
                            return e.children.filter(function(ch) {
                                return ch.name == 'path' && ch.attributes['data-code'];
                            }).map(function(ch) {
                                var d = ch.attributes.d;
                                var code = ch.attributes['data-code'];
                                if (code) {
                                    var path = paper.path(d);
                                    var bbox =  path.getBBox();
                                    var keys = ['x', 'y', 'cx', 'cy', 'x2', 'y2', 'width', 'height'];
                                    for (var j = 0; j < keys.length; j++) {
                                        bbox[keys[j]] = Math.round(bbox[keys[j]]);
                                    }
                                    bbox.map = mapName;
                                    if (!cache.bboxes[code]) {
                                        cache.bboxes[code] = bbox;
                                    }
                                }
                            });
                        });
                    });
                });
                return;
            });

            // Write the destination file.
            grunt.file.write(f.dest, JSON.stringify(cache));

            // Print a success message.
            grunt.log.writeln('File "' + f.dest + '" created.');
        });
    });
};
<|endoftext|>


<commit_before>var Web3 = require( 'web3' ),
    express = require( 'express' ),
    bodyParser = require('body-parser')
    web3 = new Web3(),
    app = express()

web3.setProvider(new web3.providers.HttpProvider( 'http://localhost:8545' ));

var giveAwayContract = web3.eth.contract( [{"constant":false,"inputs":[],"name":"registerAddress","outputs":[{"name":"addressID","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"foreignAddress","type":"address"}],"name":"registerForeignAddress","outputs":[{"name":"addressID","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"addressCount","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"addresses","outputs":[{"name":"","type":"address"}],"type":"function"}] ).at('0x437cd5726c971c22860a8218b5fcd6ad0f7f40d8');

function sendEther( to, value, gasPrice, gas, callback ) {
  web3.eth.sendTransaction({
    from: web3.eth.coinbase,
    to: to,
    value: value,
    gasPrice: gasPrice,
    gas: gas
  }, callback );
};

function giveaway() {
  var count = giveAwayContract.addressCount().c[0]
  console.log( '-> Giveaway round!' );
  console.log( '-> Registered addresses', count );

  var n = 0;
  while( n < count ) {
    var destinationAddress = giveAwayContract.addresses(n),
        amount = parseFloat(Math.random()*10000000);
    console.log( '*> Send', amount, 'ether ->' , destinationAddress );
    sendEther( destinationAddress, amount, 50000000000, 50000, function( err, txhash ) {
      console.log( '>> Sent', amount, 'ether ->', txhash, '(tx)' );
      console.log('');
    });
    n++;
  };
};

app.use(bodyParser.urlencoded({ extended: false }))

app.post( '/appendAddress', function( req, res ) {
  var addr = req.body.address;
  console.log( '** Appending address', addr );
  giveAwayContract.registerForeignAddress( '0x0000000000000000000000000000000000000123', { from: web3.eth.coinbase } );
  res.write('');
  res.end();
});

giveaway();

setInterval( giveaway, 60000 );

app.listen( 8540 )
<commit_msg>CORS handling<commit_after>var Web3 = require( 'web3' ),
    express = require( 'express' ),
    bodyParser = require('body-parser')
    web3 = new Web3(),
    app = express()

web3.setProvider(new web3.providers.HttpProvider( 'http://localhost:8545' ));

var giveAwayContract = web3.eth.contract( [{"constant":false,"inputs":[],"name":"registerAddress","outputs":[{"name":"addressID","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"foreignAddress","type":"address"}],"name":"registerForeignAddress","outputs":[{"name":"addressID","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"addressCount","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"addresses","outputs":[{"name":"","type":"address"}],"type":"function"}] ).at('0x437cd5726c971c22860a8218b5fcd6ad0f7f40d8');

function sendEther( to, value, gasPrice, gas, callback ) {
  web3.eth.sendTransaction({
    from: web3.eth.coinbase,
    to: to,
    value: value,
    gasPrice: gasPrice,
    gas: gas
  }, callback );
};

function giveaway() {
  var count = giveAwayContract.addressCount().c[0]
  console.log( '-> Giveaway round!' );
  console.log( '-> Registered addresses', count );

  var n = 0;
  while( n < count ) {
    var destinationAddress = giveAwayContract.addresses(n),
        amount = parseFloat(Math.random()*10000000);
    console.log( '*> Send', amount, 'ether ->' , destinationAddress );
    sendEther( destinationAddress, amount, 50000000000, 50000, function( err, txhash ) {
      console.log( '>> Sent', amount, 'ether ->', txhash, '(tx)' );
      console.log('');
    });
    n++;
  };
};

app.use(bodyParser.urlencoded({ extended: false }))

app.use( function( req, res, next ) {
  res.header( 'Access-Control-Allow-Origin', '* ' );
  res.header( 'Access-Control-Allow-Headers', 'X-Requested-With' )
  next();
});

app.post( '/appendAddress', function( req, res ) {
  var addr = req.body.address;
  console.log( '** Appending address', addr );
  giveAwayContract.registerForeignAddress( '0x0000000000000000000000000000000000000123', { from: web3.eth.coinbase } );
  res.write('');
  res.end();
});

giveaway();

setInterval( giveaway, 60000 );

app.listen( 8540 )
<|endoftext|>


<commit_before>let Register = {

	/**
	 * Prefix of component if used
	 * e.g. com-foo
	 */
	prefix: 'com',

	/**
	 * customElement
	 * @param Class {function}
	 * @param config {{extends: string, name: string}}
	 */
	customElement(Class, config = {}){

		let name = config.name;
		if(!name){
			let className = this._getClassName(Class);
			name = this._createComponentName(className, this.prefix);
		} else {
			delete config.name;
		}

		this._addExtends(Class, config);
		this._registerElement(Class, name);
	},

	/**
	 * _classof
	 * @param value {*}
	 * @returns {string}
	 * @private
	 */
	_classof(value){
		return Object.prototype.toString.call(value).slice(8, -1);
	},

	/**
	 * _addExtends
	 * @param Class {function}
	 * @param config {{extends: string, name: string}}
	 * @returns Class {function}
	 */
	_addExtends(Class, config = {}){

		let inherit = config.extends;
		if(inherit && !Class.extends){
			Class.extends = inherit;
		}

		return Class;
	},

	/**
	 *
	 * @param Class {function}
	 * @returns className {string}
	 */
	_getClassName(Class){

		return Class.prototype.constructor.name;
	},

	/**
	 *
	 * @param className {string}
	 * @param prefix {string}
	 * @returns componentName {string}
	 */
	_createComponentName(className, prefix = this.prefix){

		return `${prefix}-${className.toLowerCase()}`;
	},

	/**
	 * _enableConstructorVars
	 * @param Class {function}
	 * @private
	 */
	_enableConstructorVars(Class){

		let createdCallback = Class.prototype.createdCallback;
		Class.prototype.createdCallback = function(...args){

			if(!args.length && !this.parentElement){
				return;
			}
			createdCallback ? this::createdCallback(...args) : null;
		};

		return Class;
	},

	/**
	 * registerElement
	 * @param Class {function}
	 * @param name {string}
	 * @returns Class {function}
	 */
	_registerElement(Class, name){

		this._enableConstructorVars(Class);

		// register element
		let registeredElement = document.registerElement(name, Class);

		/**
		 * create (add factory)
		 * @param vars {object}
		 */
		Class.create = function(vars) {

			if(arguments.length > 1){
				throw new Error('Its not allowd to pass more than one argument');
			}

			let classof = Register._classof(vars);
			if(!(classof === 'Object' || classof === 'Undefined')) {
				throw new Error('Passed argument must be an object or undefined');
			}

			let element = new registeredElement();

			element.createdCallback(vars || "");
			return element;
		};

		return Class;
	}
};

export {
	Register,
};
<commit_msg>fix minify issue when in jspm bundle no-mangel=false<commit_after>let Register = {

	/**
	 * Prefix of component if used
	 * e.g. com-foo
	 */
	prefix: 'com',

	/**
	 * customElement
	 * @param Class {function}
	 * @param config {{extends: string, name: string}}
	 */
	customElement(Class, config = {}){

		let name = config.name;
		if(!name){
			let className = this._getClassName(Class);
			name = this._createComponentName(className, this.prefix);
		} else {
			delete config.name;
		}

		this._addExtends(Class, config);
		this._registerElement(Class, name);
	},

	/**
	 * _classof
	 * @param value {*}
	 * @returns {string}
	 * @private
	 */
	_classof(value){
		return Object.prototype.toString.call(value).slice(8, -1);
	},

	/**
	 * _addExtends
	 * @param Class {function}
	 * @param config {{extends: string, name: string}}
	 * @returns Class {function}
	 */
	_addExtends(Class, config = {}){

		let inherit = config.extends;
		if(inherit && !Class.extends){
			Class.extends = inherit;
		}

		return Class;
	},

	/**
	 *
	 * @param Class {function}
	 * @returns className {string}ls l
	 */
	_getClassName(Class){

		return Class.$$componentName;
	},

	/**
	 *
	 * @param className {string}
	 * @param prefix {string}
	 * @returns componentName {string}
	 */
	_createComponentName(className, prefix = this.prefix){

		return `${prefix}-${className.toLowerCase()}`;
	},

	/**
	 * _enableConstructorVars
	 * @param Class {function}
	 * @private
	 */
	_enableConstructorVars(Class){

		let createdCallback = Class.prototype.createdCallback;
		Class.prototype.createdCallback = function(...args){

			if(!args.length && !this.parentElement){
				return;
			}
			createdCallback ? this::createdCallback(...args) : null;
		};

		return Class;
	},

	/**
	 * registerElement
	 * @param Class {function}
	 * @param name {string}
	 * @returns Class {function}
	 */
	_registerElement(Class, name){

		this._enableConstructorVars(Class);

		// register element
		let registeredElement = document.registerElement(name, Class);

		/**
		 * create (add factory)
		 * @param vars {object}
		 */
		Class.create = function(vars) {

			if(arguments.length > 1){
				throw new Error('Its not allowd to pass more than one argument');
			}

			let classof = Register._classof(vars);
			if(!(classof === 'Object' || classof === 'Undefined')) {
				throw new Error('Passed argument must be an object or undefined');
			}

			let element = new registeredElement();

			element.createdCallback(vars || "");
			return element;
		};

		return Class;
	}
};

export {
	Register,
};
<|endoftext|>


<commit_before>import path from 'path';
import os from 'os';
import { assert, test } from 'yeoman-generator';

describe('sails-rest-api:services', function () {
  describe('Should properly handle default configuration', () => {
    this.timeout(10000);

    before(done => {
      test
        .run(path.join(__dirname, '../../generators/services'))
        .inDir(path.join(os.tmpdir(), './temp-test'))
        .on('end', done);
    });

    it('Should properly create api files', () => {
      assert.file([
        'api/services/CipherService.js',
        'api/services/HashService.js'
      ]);

      assert.noFile([
        'api/services/ImageService.js',
        'api/services/LocationService.js',
        'api/services/MailerService.js',
        'api/services/PaymentService.js',
        'api/services/PusherService.js',
        'api/services/SmsService.js',
        'api/services/SocialService.js',
        'api/services/StorageService.js'
      ]);
    });

    it('Should properly create config files', () => {
      assert.file([
        'config/services/cipher.js',
        'config/services/hash.js'
      ]);

      assert.noFile([
        'config/services/image.js',
        'config/services/location.js',
        'config/services/mailer.js',
        'config/services/payment.js',
        'config/services/pusher.js',
        'config/services/sms.js',
        'config/services/social.js',
        'config/services/storage.js'
      ])
    });

    it('Should properly create test files', () => {
      assert.file([
        'test/unit/services/CipherService.test.js',
        'test/unit/services/HashService.test.js'
      ]);

      assert.noFile([
        'test/unit/services/ImageService.test.js',
        'test/unit/services/LocationService.test.js',
        'test/unit/services/MailerService.test.js',
        'test/unit/services/PaymentService.test.js',
        'test/unit/services/PusherService.test.js',
        'test/unit/services/SmsService.test.js',
        'test/unit/services/SocialService.test.js',
        'test/unit/services/StorageService.test.js'
      ]);
    });
  });

  describe('Should properly handle full configuration', () => {
    this.timeout(10000);

    before(done => {
      test
        .run(path.join(__dirname, '../../generators/services'))
        .inDir(path.join(os.tmpdir(), './temp-test'))
        .withOptions({
          'services': ['Cipher', 'Hash', 'Image', 'LocationService', 'Mailer', 'PaymentService', 'Pusher', 'Sms', 'Social', 'Storage'].join(','),
          'image-provider': 'IM',
          'location-provider': 'FreeGeoIP',
          'mailer-provider': 'SMTP',
          'payment-provider': 'BrainTree',
          'sms-provider': 'Twilio',
          'storage-provider': 'Local'
        })
        .on('end', done);
    });

    it('Should properly create api files', () => {
      assert.file([
        'api/services/CipherService.js',
        'api/services/HashService.js',
        'api/services/ImageService.js',
        'api/services/LocationService.js',
        'api/services/MailerService.js',
        'api/services/PaymentService.js',
        'api/services/PusherService.js',
        'api/services/SmsService.js',
        'api/services/SocialService.js',
        'api/services/StorageService.js'
      ]);

      assert.fileContent('api/services/ImageService.js', /image\.create\("IM"/);
      assert.fileContent('api/services/LocationService.js', /location\.create\("FreeGeoIP"/);
      assert.fileContent('api/services/MailerService.js', /mailer\.create\("SMTP"/);
      assert.fileContent('api/services/PaymentService.js', /payment\.create\("BrainTree"/);
      assert.fileContent('api/services/SmsService.js', /sms\.create\("Twilio"/);
      assert.fileContent('api/services/StorageService.js', /storage\.create\("Local"/);
    });

    it('Should properly create config files', () => {
      assert.file([
        'config/services/cipher.js',
        'config/services/hash.js',
        'config/services/image.js',
        'config/services/location.js',
        'config/services/mailer.js',
        'config/services/payment.js',
        'config/services/pusher.js',
        'config/services/sms.js',
        'config/services/social.js',
        'config/services/storage.js'
      ]);
    });

    it('Should properly create test files', () => {
      assert.file([
        'test/unit/services/CipherService.test.js',
        'test/unit/services/HashService.test.js',
        'test/unit/services/ImageService.test.js',
        'test/unit/services/LocationService.test.js',
        'test/unit/services/MailerService.test.js',
        'test/unit/services/PaymentService.test.js',
        'test/unit/services/PusherService.test.js',
        'test/unit/services/SmsService.test.js',
        'test/unit/services/SocialService.test.js',
        'test/unit/services/StorageService.test.js'
      ]);
    });
  });
});
<commit_msg>Fix tests for services generator<commit_after>import path from 'path';
import os from 'os';
import { assert, test } from 'yeoman-generator';

describe('sails-rest-api:services', function () {
  describe('Should properly handle default configuration', () => {
    this.timeout(10000);

    before(done => {
      test
        .run(path.join(__dirname, '../../src/services'))
        .inDir(path.join(os.tmpdir(), './temp-test'))
        .on('end', done);
    });

    it('Should properly create api files', () => {
      assert.file([
        'api/services/CipherService.js',
        'api/services/HashService.js'
      ]);

      assert.noFile([
        'api/services/ImageService.js',
        'api/services/LocationService.js',
        'api/services/MailerService.js',
        'api/services/PaymentService.js',
        'api/services/PusherService.js',
        'api/services/SmsService.js',
        'api/services/SocialService.js',
        'api/services/StorageService.js'
      ]);
    });

    it('Should properly create config files', () => {
      assert.file([
        'config/services/cipher.js',
        'config/services/hash.js'
      ]);

      assert.noFile([
        'config/services/image.js',
        'config/services/location.js',
        'config/services/mailer.js',
        'config/services/payment.js',
        'config/services/pusher.js',
        'config/services/sms.js',
        'config/services/social.js',
        'config/services/storage.js'
      ]);

      assert.fileContent('config/services/cipher.js', /secretOrKey: "[a-z0-9]{64}"/);
    });

    it('Should properly create test files', () => {
      assert.file([
        'test/unit/services/CipherService.test.js',
        'test/unit/services/HashService.test.js'
      ]);

      assert.noFile([
        'test/unit/services/ImageService.test.js',
        'test/unit/services/LocationService.test.js',
        'test/unit/services/MailerService.test.js',
        'test/unit/services/PaymentService.test.js',
        'test/unit/services/PusherService.test.js',
        'test/unit/services/SmsService.test.js',
        'test/unit/services/SocialService.test.js',
        'test/unit/services/StorageService.test.js'
      ]);
    });
  });

  describe('Should properly handle full configuration', () => {
    this.timeout(10000);

    before(done => {
      test
        .run(path.join(__dirname, '../../src/services'))
        .inDir(path.join(os.tmpdir(), './temp-test'))
        .withOptions({
          'services': ['Cipher', 'Hash', 'Image', 'LocationService', 'Mailer', 'PaymentService', 'Pusher', 'Sms', 'Social', 'Storage'].join(','),
          'cipher-secret-key': '1234567890',
          'image-provider': 'IM',
          'location-provider': 'FreeGeoIP',
          'mailer-provider': 'SMTP',
          'payment-provider': 'BrainTree',
          'sms-provider': 'Twilio',
          'storage-provider': 'Local'
        })
        .on('end', done);
    });

    it('Should properly create api files', () => {
      assert.file([
        'api/services/CipherService.js',
        'api/services/HashService.js',
        'api/services/ImageService.js',
        'api/services/LocationService.js',
        'api/services/MailerService.js',
        'api/services/PaymentService.js',
        'api/services/PusherService.js',
        'api/services/SmsService.js',
        'api/services/SocialService.js',
        'api/services/StorageService.js'
      ]);

      assert.fileContent('api/services/ImageService.js', /image\("IM"/);
      assert.fileContent('api/services/LocationService.js', /location\("FreeGeoIP"/);
      assert.fileContent('api/services/MailerService.js', /mailer\("SMTP"/);
      assert.fileContent('api/services/PaymentService.js', /payment\("BrainTree"/);
      assert.fileContent('api/services/SmsService.js', /sms\("Twilio"/);
      assert.fileContent('api/services/StorageService.js', /storage\("Local"/);
    });

    it('Should properly create config files', () => {
      assert.file([
        'config/services/cipher.js',
        'config/services/hash.js',
        'config/services/image.js',
        'config/services/location.js',
        'config/services/mailer.js',
        'config/services/payment.js',
        'config/services/pusher.js',
        'config/services/sms.js',
        'config/services/social.js',
        'config/services/storage.js'
      ]);

      assert.fileContent('config/services/cipher.js', /secretOrKey: "1234567890"/);
    });

    it('Should properly create test files', () => {
      assert.file([
        'test/unit/services/CipherService.test.js',
        'test/unit/services/HashService.test.js',
        'test/unit/services/ImageService.test.js',
        'test/unit/services/LocationService.test.js',
        'test/unit/services/MailerService.test.js',
        'test/unit/services/PaymentService.test.js',
        'test/unit/services/PusherService.test.js',
        'test/unit/services/SmsService.test.js',
        'test/unit/services/SocialService.test.js',
        'test/unit/services/StorageService.test.js'
      ]);
    });
  });
});
<|endoftext|>


<commit_before>---
---

$(document).ready(function(){
  // parallax effect
  $.stellar({
    horizontalScrolling: false,
    verticalOffset: 40
  });

  // code example carousel
  $('.carousel').carousel();
  $(document).keyup(function(event) {
    switch (event.keyCode) {
      case 37: // lef t
        $('.carousel').carousel('prev');
        break;
      case 39: // right
        $('.carousel').carousel('next');
        break;
      default:
        break;
    }
  });

  // tweets
  $(function(){
    $("#tweets").liveTwitter('scala_lang');
  });

});

/******************************
 * Events and trainings feeds *
 ******************************/

$(document).ready(function(){
  var $eventsAndTrainingDiv = $('#eventsAndTraining');

  var MAX_EVENTS = 5;
  var MAX_TRAININGS = 5;

  // Stop early if the element does not exist
  if ($eventsAndTrainingDiv.length == 0)
    return;

  function compareFormattedDates(lhs, rhs) {
    var lhsDate = new Date(lhs);
    var rhsDate = new Date(rhs);
    if (lhsDate < rhsDate)
      return -1;
    else if (lhsDate > rhsDate)
      return 1;
    else
      return 0;
  }

  // EVENTS

  function compareEventsByDate(lhs, rhs) {
    return compareFormattedDates(lhs.start, rhs.start);
  }

  var scalaLangEvents = [
  {% for event in site.categories.events %}
  {% if event.date >= site.time %}{% comment %} No point in including outdated events {% endcomment %}
    {
      "title": "{{ event.title }}",
      "logo": "{{ event.logo }}",
      "location": "{{ event.location }}",
      "start": "{{ event.start }}",
      "end": "{{ event.end }}",
      "url": "{{ event.link-out }}",
    },
  {% endif %}
  {% endfor%}
  ];

  function doPopulateEventsPane(allEvents) {
    allEvents = allEvents.filter(function (event) {
      return (event.end ? new Date(event.end) : new Date(event.start)) >= new Date();
    });
    allEvents.sort(compareEventsByDate);
    var content = "";
    for (i = 0; i < allEvents.length && i < MAX_EVENTS; i++) {
      var event = allEvents[i];
      var thisContent =
        event.title + " in " + event.location + "
" +
        event.start;
      if (event.end != "")
        thisContent += " to " + event.end;
      $("#eventspane").append("
" + thisContent + "
");
    }
  };

  function onEventsAjaxSuccess(response, textStatus, jqXHR) {
    var allEvents = scalaLangEvents.concat(response);
    doPopulateEventsPane(allEvents);
  }

  function onEventsAjaxError(jqXHR, textStatus, errorThrown) {
    // log the error to the console
    console.error(
      "Could not load Typesafe event feed: " + textStatus, errorThrown);
    // but at least display events from scala-lang
    doPopulateEventsPane(scalaLangEvents);
  }

  $.ajax({
    url: "{{ site.baseurl }}/cgi-bin/typesafe-feed-events",
    type: "GET",
    dataType: "json",
    success: onEventsAjaxSuccess,
    error: onEventsAjaxError
  });

  // TRAININGS

  function compareTrainingsByDate(lhs, rhs) {
    return compareFormattedDates(lhs.when, rhs.when);
  }

  var scalaLangTrainings = [
  {% for training in site.categories.training %}
  {% if training.date >= site.time %}{% comment %} No point in including outdated training sessions {% endcomment %}
    {
      title: "{{ training.title }}",
      description: "{{ training.description }}",
      url: "{{ training.link-out }}",
      sessions: [
        {
          where: "{{ training.where }}",
          when: "{{ training.when }}",
          trainers: "{{ training.trainers }}",
          organizer: "{{ training.organizer }}",
          status: "{{ training.status }}"
        }
      ]
    },
  {% endif %}
  {% endfor%}
  ];

  function keepOnlyOneSession(trainings) {
    var result = new Array();
    for (i = 0; i < trainings.length && i < MAX_TRAININGS; i++) {
      var training = trainings[i];
      var firstSession = training.sessions[0];
      result[i] = {
        title: training.title,
        description: training.description,
        url: training.url,
        where: firstSession.where,
        when: firstSession.when,
        trainers: firstSession.trainers,
        organizer: firstSession.organizer,
        status: firstSession.status
      };
    }
    return result;
  }

  function doPopulateTrainingsPane(allTrainings0) {
    var allTrainings = keepOnlyOneSession(allTrainings0);
    allTrainings = allTrainings.filter(function (training) {
      return new Date(training.when) >= new Date();
    });
    allTrainings.sort(compareTrainingsByDate);
    var content = "";
    for (i = 0; i < allTrainings.length; i++) {
      var training = allTrainings[i];
      var thisContent =
        training.title + "
" + training.when + ", " + training.where +
        ", by " + training.trainers;
      $("#trainingspane").append("
" + thisContent + "
");
    }
  }

  function onTrainingsAjaxSuccess(response, textStatus, jqXHR) {
    var allTrainings = scalaLangTrainings.concat(response);
    doPopulateTrainingsPane(allTrainings);
  }

  function onTrainingsAjaxError(jqXHR, textStatus, errorThrown) {
    // log the error to the console
    console.error(
      "Could not load Typesafe training feed: " + textStatus, errorThrown);
    // but at least display trainings from scala-lang
    doPopulateTrainingsPane(scalaLangTrainings);
  }

  $.ajax({
    url: "{{ site.baseurl }}/cgi-bin/typesafe-feed-trainings",
    type: "GET",
    dataType: "json",
    success: onTrainingsAjaxSuccess,
    error: onTrainingsAjaxError
  });

});
<commit_msg>Generate css-customizable divs for trainings and events.<commit_after>---
---

$(document).ready(function(){
  // parallax effect
  $.stellar({
    horizontalScrolling: false,
    verticalOffset: 40
  });

  // code example carousel
  $('.carousel').carousel();
  $(document).keyup(function(event) {
    switch (event.keyCode) {
      case 37: // lef t
        $('.carousel').carousel('prev');
        break;
      case 39: // right
        $('.carousel').carousel('next');
        break;
      default:
        break;
    }
  });

  // tweets
  $(function(){
    $("#tweets").liveTwitter('scala_lang');
  });

});

/******************************
 * Events and trainings feeds *
 ******************************/

$(document).ready(function(){
  var $eventsAndTrainingDiv = $('#eventsAndTraining');

  var MAX_EVENTS = 5;
  var MAX_TRAININGS = 5;

  // Stop early if the element does not exist
  if ($eventsAndTrainingDiv.length == 0)
    return;

  function compareFormattedDates(lhs, rhs) {
    var lhsDate = new Date(lhs);
    var rhsDate = new Date(rhs);
    if (lhsDate < rhsDate)
      return -1;
    else if (lhsDate > rhsDate)
      return 1;
    else
      return 0;
  }

  // EVENTS

  function compareEventsByDate(lhs, rhs) {
    return compareFormattedDates(lhs.start, rhs.start);
  }

  var scalaLangEvents = [
  {% for event in site.categories.events %}
  {% if event.date >= site.time %}{% comment %} No point in including outdated events {% endcomment %}
    {
      "title": "{{ event.title }}",
      "logo": "{{ event.logo }}",
      "location": "{{ event.location }}",
      "start": "{{ event.start }}",
      "end": "{{ event.end }}",
      "url": "{{ event.link-out }}",
    },
  {% endif %}
  {% endfor%}
  ];

  function doPopulateEventsPane(allEvents) {
    allEvents = allEvents.filter(function (event) {
      return (event.end ? new Date(event.end) : new Date(event.start)) >= new Date();
    });
    allEvents.sort(compareEventsByDate);
    var content = "";
    for (i = 0; i < allEvents.length && i < MAX_EVENTS; i++) {
      var event = allEvents[i];
      var thisContent =
        '
' +
          '
'+event.title+'
' +
          '

' +
          '
'+event.location+'
' +
          '
 '+
            event.start + (event.end ? ' to '+event.end : '') + '
' +
        '
';
      $("#eventspane").append(thisContent);
    }
  };

  function onEventsAjaxSuccess(response, textStatus, jqXHR) {
    var allEvents = scalaLangEvents.concat(response);
    doPopulateEventsPane(allEvents);
  }

  function onEventsAjaxError(jqXHR, textStatus, errorThrown) {
    // log the error to the console
    console.error(
      "Could not load Typesafe event feed: " + textStatus, errorThrown);
    // but at least display events from scala-lang
    doPopulateEventsPane(scalaLangEvents);
  }

  $.ajax({
    url: "{{ site.baseurl }}/cgi-bin/typesafe-feed-events",
    type: "GET",
    dataType: "json",
    success: onEventsAjaxSuccess,
    error: onEventsAjaxError
  });

  // TRAININGS

  function compareTrainingsByDate(lhs, rhs) {
    return compareFormattedDates(lhs.when, rhs.when);
  }

  var scalaLangTrainings = [
  {% for training in site.categories.training %}
  {% if training.date >= site.time %}{% comment %} No point in including outdated training sessions {% endcomment %}
    {
      title: "{{ training.title }}",
      description: "{{ training.description }}",
      url: "{{ training.link-out }}",
      sessions: [
        {
          where: "{{ training.where }}",
          when: "{{ training.when }}",
          trainers: "{{ training.trainers }}",
          organizer: "{{ training.organizer }}",
          status: "{{ training.status }}"
        }
      ]
    },
  {% endif %}
  {% endfor%}
  ];

  function keepOnlyOneSession(trainings) {
    var result = new Array();
    for (i = 0; i < trainings.length && i < MAX_TRAININGS; i++) {
      var training = trainings[i];
      var firstSession = training.sessions[0];
      result[i] = {
        title: training.title,
        description: training.description,
        url: training.url,
        where: firstSession.where,
        when: firstSession.when,
        trainers: firstSession.trainers,
        organizer: firstSession.organizer,
        status: firstSession.status
      };
    }
    return result;
  }

  function doPopulateTrainingsPane(allTrainings0) {
    var allTrainings = keepOnlyOneSession(allTrainings0);
    allTrainings = allTrainings.filter(function (training) {
      return new Date(training.when) >= new Date();
    });
    allTrainings.sort(compareTrainingsByDate);
    var content = "";
    for (i = 0; i < allTrainings.length; i++) {
      var training = allTrainings[i];
      var thisContent =
        '
' +
          '
'+training.title+'
' +
          '
'+training.description+'
' +
          '
'+training.where+'
' +
          '
 '+training.when+'
' +
          '
By
'+training.trainers+'

' +
          '
'+training.organizer+'
' +
        '
';
      $("#trainingspane").append(thisContent);
    }
  }

  function onTrainingsAjaxSuccess(response, textStatus, jqXHR) {
    var allTrainings = scalaLangTrainings.concat(response);
    doPopulateTrainingsPane(allTrainings);
  }

  function onTrainingsAjaxError(jqXHR, textStatus, errorThrown) {
    // log the error to the console
    console.error(
      "Could not load Typesafe training feed: " + textStatus, errorThrown);
    // but at least display trainings from scala-lang
    doPopulateTrainingsPane(scalaLangTrainings);
  }

  $.ajax({
    url: "{{ site.baseurl }}/cgi-bin/typesafe-feed-trainings",
    type: "GET",
    dataType: "json",
    success: onTrainingsAjaxSuccess,
    error: onTrainingsAjaxError
  });

});
<|endoftext|>


<commit_before>
import BaseVertex from "./BaseVertex";
import SK from "../../sk";

export default class DelayVertex extends BaseVertex {
  constructor({id}) {
    super({id});
    this.videoOutputURL = this.getUDP();
    this.audioOutputURL = this.getUDP();
    this.inputURL = this.getUDP() + "reuse=1";
    SK.vertices.update(id, {
      inputs: {
        default: {
          socket: this.inputURL,
        }
      },
      outputs: {
        video: {
          socket: this.videoOutputURL
        },
        audio: {
          socket: this.audioOutputURL
        }
      },
    }).catch((err) => {
      this.error(err);
    });
  }

  init() {
    try {
      this.ffmpeg = this.createffmpeg()
        .input(this.inputURL)
        .inputFormat("mpegts")
        // .inputOptions("-itsoffset 00:00:05")
        .outputOptions([
        ])
        .videoCodec("libx264")
        .audioCodec("pcm_s16le")
        .outputOptions([
          "-preset ultrafast",
          "-tune zerolatency",
          "-x264opts keyint=5:min-keyint=",
          "-pix_fmt yuv420p",
          "-filter_complex",
          [
            `[0:a]asetpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_audio]`,
            `[0:v]setpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[resize]`,
            "[resize]scale=640:480[out_video]",
          ].join(";")
        ])

        // Video output
        .output(this.videoOutputURL)
        .outputOptions([
          "-map [out_video]",
        ])
        .outputFormat("mpegts")

        // Audio output
        .output(this.audioOutputURL)
        .outputOptions([
          "-map [out_audio]",
        ])
        .outputFormat("mpegts");

      this.ffmpeg.run();
    }
    catch (err) {
      this.error(err);
      this.retry();
    }
  }
}
<commit_msg>remove 640x480 restriction<commit_after>
import BaseVertex from "./BaseVertex";
import SK from "../../sk";

export default class DelayVertex extends BaseVertex {
  constructor({id}) {
    super({id});
    this.videoOutputURL = this.getUDP();
    this.audioOutputURL = this.getUDP();
    this.inputURL = this.getUDP() + "reuse=1";
    SK.vertices.update(id, {
      inputs: {
        default: {
          socket: this.inputURL,
        }
      },
      outputs: {
        video: {
          socket: this.videoOutputURL
        },
        audio: {
          socket: this.audioOutputURL
        }
      },
    }).catch((err) => {
      this.error(err);
    });
  }

  init() {
    try {
      this.ffmpeg = this.createffmpeg()
        .input(this.inputURL)
        .inputFormat("mpegts")
        // .inputOptions("-itsoffset 00:00:05")
        .outputOptions([
        ])
        .videoCodec("libx264")
        .audioCodec("pcm_s16le")
        .outputOptions([
          "-preset ultrafast",
          "-tune zerolatency",
          "-x264opts keyint=5:min-keyint=",
          "-pix_fmt yuv420p",
          "-filter_complex",
          [
            `[0:a]asetpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_audio]`,
            `[0:v]setpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_video]`,
          ].join(";")
        ])

        // Video output
        .output(this.videoOutputURL)
        .outputOptions([
          "-map [out_video]",
        ])
        .outputFormat("mpegts")

        // Audio output
        .output(this.audioOutputURL)
        .outputOptions([
          "-map [out_audio]",
        ])
        .outputFormat("mpegts");

      this.ffmpeg.run();
    }
    catch (err) {
      this.error(err);
      this.retry();
    }
  }
}
<|endoftext|>