<commit_before>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var logger = require("../lib/logger").init(),
    common = require('../lib/common'),
    utils = require("../lib/utils").init(),
    path = require('path');

function readConfig () {
    var fullFilename = common.getConfigName();
    return common.readFileToJson(fullFilename);
}

function writeConfig (data) {
    var fullFilename = common.getConfigName();
    common.writeToJson(fullFilename, data);
}

var configFileKey = {
    gatewayId : 'gateway_id',
    deviceId: 'device_id',
    dataDirectory: 'data_directory',
    activationCode: 'activation_code',
    defaultConnector: 'default_connector',
    loggerLevel: 'logger.LEVEL',
    connectorRestProxyHost: 'connector.rest.proxy.host',
    connectorRestProxyPort: 'connector.rest.proxy.port'
};

var saveToConfig = function () {
    if (arguments.length < 2) {
        logger.error("Not enough arguments : ", arguments);
        process.exit(1);
    }
    var key = arguments[0];
    var value = arguments[1];
    var data = readConfig();
    var keys = key.split('.');
    var configSaver = function (data, keys) {
        var k = keys.splice(0, 1);
        if (data && (data[k[0]] !== undefined)) {
            logger.info("Config Key : ", k[0], " value ", value);
            if (keys.length > 0) {
                data[k[0]] = configSaver(data[k[0]], keys);
            } else {
                data[k[0]] = value;
                logger.debug("Config Key : ", data);
            }
            return data;
        } else {
            logger.error("Key : ", key, " not found");
            return false;
        }
    };
    data = configSaver(data, keys);
    if (data) {
        writeConfig(data);
    }
    return true;
};

var setHostFor = function (host_value, port_value) {
    var data = readConfig();
    var proxy;
    if (data) {
       proxy = data["default_connector"];
       logger.info("Config Key : ", proxy, " value ", host_value);
       var host_key = 'connector.' + proxy + '.host';

       if(proxy === "rest"){
           var protocol;
           var protocol_key = 'connector.' + proxy + '.protocol';
           if(host_value.indexOf("https://")===0){
               host_value = host_value.replace("https://", "");
               protocol = "https";
           }else if(host_value.indexOf("http://")===0){
               host_value = host_value.replace("http://", "");
               protocol = "http";
           }
           if(protocol){
               saveToConfig(protocol_key, protocol);
           }
       }
       saveToConfig(host_key, host_value);
       if (port_value) {
        var port_key = 'connector.' + proxy + '.port';
        saveToConfig(port_key, port_value);
       }
    }
};

var setProxy = function (host_proxy, port_proxy) {
    saveToConfig(configFileKey.connectorRestProxyHost, host_proxy);
    saveToConfig(configFileKey.connectorRestProxyPort, port_proxy);
    logger.info("Set Proxy data");
};
var resetProxy = function () {
    saveToConfig(configFileKey.connectorRestProxyHost, false);
    saveToConfig(configFileKey.connectorRestProxyPort, false);
    logger.info("Set Proxy data");
};

var setGatewayId = function(id, cb) {
    saveToConfig(configFileKey.gatewayId, id);
    cb(id);
};

var getGatewayId = function(cb) {
    utils.getGatewayId(configFileKey.gatewayId, cb);
};

var loggerLevel = {
    info: true,
    warn: true,
    error: true,
    debug: true
};
module.exports = {
    addCommand : function (program) {
        program
            .command('protocol <protocol>')
            .description('Set the protocol to \'mqtt\' or \'rest\'')
            .action(function(protocol){
                if (protocol === 'mqtt' || protocol === 'rest') {
                    saveToConfig(configFileKey.defaultConnector, protocol);
                    logger.info("protocol set to: " + protocol);
                } else {
                    logger.error("invalid protocol: %s - please use \'mqtt\' or \'rest\'", protocol);
                    // do not clear the previous protocol
                }
            });

        program
            .command('host <host> [<port>]')
            .description('Sets the cloud hostname for the current protocol.')
            .action(setHostFor);

        program
            .command('device-id')
            .description('Displays the device id.')
            .action(function() {
                utils.getDeviceId(function (id) {
                    logger.info("Device ID: %s", id);
                });
            });

        program
            .command('set-device-id <id>')
            .description('Overrides the device id.')
            .action(function(id) {
                saveToConfig(configFileKey.deviceId, id);
                logger.info("Device ID set to: %s", id);
            });

        program
            .command('clear-device-id')
            .description('Reverts to using the default device id.')
            .action(function() {
                saveToConfig(configFileKey.deviceId, false);
                logger.info("Device ID cleared.");
            });

        program
            .command('save-code <activation_code>')
            .description('Adds the activation code to the device.')
            .action(function(activation_code) {
                saveToConfig(configFileKey.activationCode, activation_code);
                logger.info("Activation code saved.");
            });

        program
            .command('reset-code')
            .description('Clears the activation code of the device.')
            .action(function() {
                saveToConfig(configFileKey.activationCode, null);
                logger.info("Activation code cleared.");
            });

        program
            .command('proxy <host> <port>')
            .description('Sets proxy For REST protocol.')
            .action(setProxy);

        program
            .command('reset-proxy')
            .description('Clears proxy For REST protocol.')
            .action(resetProxy);

        program
            .command('set-logger-level <level>')
            .description('Set the logger level to \'debug\', \'info\', \'warn\', \'error\'')
            .action(function(level) {
                if (loggerLevel[level]) {
                    saveToConfig(configFileKey.loggerLevel, level);
                    logger.info("Logger Level set to: %s", level);
                } else {
                    logger.error("invalid level: %s - please use %s", level,
                                                Object.keys(loggerLevel).toString());
                }
            });

        program
            .command('set-data-directory <path>')
            .description('Sets path of directory that contains sensor data.')
            .action(function(path) {
                saveToConfig(configFileKey.dataDirectory, path);
                logger.info("Data directory changed.");
            });

        program
            .command('reset-data-directory')
            .description('Resets to default the path of directory that contains sensor data.')
            .action(function() {
                saveToConfig(configFileKey.dataDirectory, path.join(__dirname, '../data/'));
                logger.info("Data directory changed to default.");
            });

        program
            .command('gateway-id')
            .description('Displays the geteway id.')
            .action(function() {
                getGatewayId(function (id) {
                    logger.info("Gateway ID: %s", id);
                });
            });

        program
            .command('set-gateway-id <id>')
            .description('Overrides the geteway id.')
            .action(function(id) {
                setGatewayId(id, function(id){
                    logger.info("Gateway Id set to: %s", id);
                });
            });

    },
    getGatewayId: getGatewayId,
    setGetewayId: setGatewayId
};
<commit_msg>DP-2282 fix typo made in method name<commit_after>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var logger = require("../lib/logger").init(),
    common = require('../lib/common'),
    utils = require("../lib/utils").init(),
    path = require('path');

function readConfig () {
    var fullFilename = common.getConfigName();
    return common.readFileToJson(fullFilename);
}

function writeConfig (data) {
    var fullFilename = common.getConfigName();
    common.writeToJson(fullFilename, data);
}

var configFileKey = {
    gatewayId : 'gateway_id',
    deviceId: 'device_id',
    dataDirectory: 'data_directory',
    activationCode: 'activation_code',
    defaultConnector: 'default_connector',
    loggerLevel: 'logger.LEVEL',
    connectorRestProxyHost: 'connector.rest.proxy.host',
    connectorRestProxyPort: 'connector.rest.proxy.port'
};

var saveToConfig = function () {
    if (arguments.length < 2) {
        logger.error("Not enough arguments : ", arguments);
        process.exit(1);
    }
    var key = arguments[0];
    var value = arguments[1];
    var data = readConfig();
    var keys = key.split('.');
    var configSaver = function (data, keys) {
        var k = keys.splice(0, 1);
        if (data && (data[k[0]] !== undefined)) {
            logger.info("Config Key : ", k[0], " value ", value);
            if (keys.length > 0) {
                data[k[0]] = configSaver(data[k[0]], keys);
            } else {
                data[k[0]] = value;
                logger.debug("Config Key : ", data);
            }
            return data;
        } else {
            logger.error("Key : ", key, " not found");
            return false;
        }
    };
    data = configSaver(data, keys);
    if (data) {
        writeConfig(data);
    }
    return true;
};

var setHostFor = function (host_value, port_value) {
    var data = readConfig();
    var proxy;
    if (data) {
       proxy = data["default_connector"];
       logger.info("Config Key : ", proxy, " value ", host_value);
       var host_key = 'connector.' + proxy + '.host';

       if(proxy === "rest"){
           var protocol;
           var protocol_key = 'connector.' + proxy + '.protocol';
           if(host_value.indexOf("https://")===0){
               host_value = host_value.replace("https://", "");
               protocol = "https";
           }else if(host_value.indexOf("http://")===0){
               host_value = host_value.replace("http://", "");
               protocol = "http";
           }
           if(protocol){
               saveToConfig(protocol_key, protocol);
           }
       }
       saveToConfig(host_key, host_value);
       if (port_value) {
        var port_key = 'connector.' + proxy + '.port';
        saveToConfig(port_key, port_value);
       }
    }
};

var setProxy = function (host_proxy, port_proxy) {
    saveToConfig(configFileKey.connectorRestProxyHost, host_proxy);
    saveToConfig(configFileKey.connectorRestProxyPort, port_proxy);
    logger.info("Set Proxy data");
};
var resetProxy = function () {
    saveToConfig(configFileKey.connectorRestProxyHost, false);
    saveToConfig(configFileKey.connectorRestProxyPort, false);
    logger.info("Set Proxy data");
};

var setGatewayId = function(id, cb) {
    saveToConfig(configFileKey.gatewayId, id);
    cb(id);
};

var getGatewayId = function(cb) {
    utils.getGatewayId(configFileKey.gatewayId, cb);
};

var loggerLevel = {
    info: true,
    warn: true,
    error: true,
    debug: true
};
module.exports = {
    addCommand : function (program) {
        program
            .command('protocol <protocol>')
            .description('Set the protocol to \'mqtt\' or \'rest\'')
            .action(function(protocol){
                if (protocol === 'mqtt' || protocol === 'rest') {
                    saveToConfig(configFileKey.defaultConnector, protocol);
                    logger.info("protocol set to: " + protocol);
                } else {
                    logger.error("invalid protocol: %s - please use \'mqtt\' or \'rest\'", protocol);
                    // do not clear the previous protocol
                }
            });

        program
            .command('host <host> [<port>]')
            .description('Sets the cloud hostname for the current protocol.')
            .action(setHostFor);

        program
            .command('device-id')
            .description('Displays the device id.')
            .action(function() {
                utils.getDeviceId(function (id) {
                    logger.info("Device ID: %s", id);
                });
            });

        program
            .command('set-device-id <id>')
            .description('Overrides the device id.')
            .action(function(id) {
                saveToConfig(configFileKey.deviceId, id);
                logger.info("Device ID set to: %s", id);
            });

        program
            .command('clear-device-id')
            .description('Reverts to using the default device id.')
            .action(function() {
                saveToConfig(configFileKey.deviceId, false);
                logger.info("Device ID cleared.");
            });

        program
            .command('save-code <activation_code>')
            .description('Adds the activation code to the device.')
            .action(function(activation_code) {
                saveToConfig(configFileKey.activationCode, activation_code);
                logger.info("Activation code saved.");
            });

        program
            .command('reset-code')
            .description('Clears the activation code of the device.')
            .action(function() {
                saveToConfig(configFileKey.activationCode, null);
                logger.info("Activation code cleared.");
            });

        program
            .command('proxy <host> <port>')
            .description('Sets proxy For REST protocol.')
            .action(setProxy);

        program
            .command('reset-proxy')
            .description('Clears proxy For REST protocol.')
            .action(resetProxy);

        program
            .command('set-logger-level <level>')
            .description('Set the logger level to \'debug\', \'info\', \'warn\', \'error\'')
            .action(function(level) {
                if (loggerLevel[level]) {
                    saveToConfig(configFileKey.loggerLevel, level);
                    logger.info("Logger Level set to: %s", level);
                } else {
                    logger.error("invalid level: %s - please use %s", level,
                                                Object.keys(loggerLevel).toString());
                }
            });

        program
            .command('set-data-directory <path>')
            .description('Sets path of directory that contains sensor data.')
            .action(function(path) {
                saveToConfig(configFileKey.dataDirectory, path);
                logger.info("Data directory changed.");
            });

        program
            .command('reset-data-directory')
            .description('Resets to default the path of directory that contains sensor data.')
            .action(function() {
                saveToConfig(configFileKey.dataDirectory, path.join(__dirname, '../data/'));
                logger.info("Data directory changed to default.");
            });

        program
            .command('gateway-id')
            .description('Displays the geteway id.')
            .action(function() {
                getGatewayId(function (id) {
                    logger.info("Gateway ID: %s", id);
                });
            });

        program
            .command('set-gateway-id <id>')
            .description('Overrides the geteway id.')
            .action(function(id) {
                setGatewayId(id, function(id){
                    logger.info("Gateway Id set to: %s", id);
                });
            });

    },
    getGatewayId: getGatewayId,
    setGatewayId: setGatewayId
};
<|endoftext|>


<commit_before>angular.module( 'wedSite', [
    'templates-app',
    'templates-common',
    'ui.router',
    'ui.bootstrap',
    'ui.utils.masks',
    'ui.utils.masks.helpers',
    'angularMoment',
    'wedSite.home',
    'wedSite.home.events',
    'wedSite.test',
    'wedSite.links',
    'ngMaterial',
    'ui.grid',
    'ngAnimate',
    'duParallax'
])

.config(['$stateProvider','$urlRouterProvider' ,function ( $stateProvider, $urlRouterProvider ) {
    $urlRouterProvider.otherwise( '/home' );
}])

.config(['$mdThemingProvider', function ($mdThemingProvider) {
    $mdThemingProvider.theme('default')
        .dark()
        .primaryPalette('grey',{
            'default': '800',
            'hue-1': '500',
            'hue-2': '200',
            'hue-3': '50'
        })
        .accentPalette('red',{
            'default': '800'
        })
        .backgroundPalette('blue-grey', {
            'default': '900',
            'hue-1': '500',
            'hue-2': '200',
            'hue-3': '50'
        })
        .warnPalette('deep-purple', {
            'default': '700'
        })

    ;
}])

.run([ function run () {
}])

.controller( 'AppCtrl',[
        '$scope',
        '$location',
        'parallaxHelper',
        function(
            $scope,
            $location,
            parallaxHelper
        ){
            $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
                if ( angular.isDefined( toState.data.pageTitle ) ) {
                    $scope.pageTitle = 'wedSite | ' + toState.data.pageTitle;
                    $scope.$broadcast('stateChanged');

                }
            });
            $scope.background = parallaxHelper.createAnimator(-0.3);
}])

.controller('NavCtrl',[
        '$scope',
        '$mdSidenav',

        function($scope, $mdSidenav){
            $scope.snapOpts = {
                tapToClose: true,
                touchToDrag: true
            };
            $scope.openLeftMenu = function() {
                $mdSidenav('left').toggle();
            };
            $scope.$on('stateChanged', function(){
                $mdSidenav('left').close();
            });

    }])

;

<commit_msg>pushToMasterOP<commit_after>angular.module( 'wedSite', [
    'templates-app',
    'templates-common',
    'ui.router',
    'ui.bootstrap',
    'angularMoment',
    'wedSite.home',
    'wedSite.home.events',
    'wedSite.test',
    'wedSite.links',
    'ngMaterial',
    'ui.grid',
    'ngAnimate',
    'duParallax'
])

.config(['$stateProvider','$urlRouterProvider' ,function ( $stateProvider, $urlRouterProvider ) {
    $urlRouterProvider.otherwise( '/home' );
}])

.config(['$mdThemingProvider', function ($mdThemingProvider) {
    $mdThemingProvider.theme('default')
        .dark()
        .primaryPalette('grey',{
            'default': '800',
            'hue-1': '500',
            'hue-2': '200',
            'hue-3': '50'
        })
        .accentPalette('red',{
            'default': '800'
        })
        .backgroundPalette('blue-grey', {
            'default': '900',
            'hue-1': '500',
            'hue-2': '200',
            'hue-3': '50'
        })
        .warnPalette('deep-purple', {
            'default': '700'
        })

    ;
}])

.run([ function run () {
}])

.controller( 'AppCtrl',[
        '$scope',
        '$location',
        'parallaxHelper',
        function(
            $scope,
            $location,
            parallaxHelper
        ){
            $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
                if ( angular.isDefined( toState.data.pageTitle ) ) {
                    $scope.pageTitle = 'wedSite | ' + toState.data.pageTitle;
                    $scope.$broadcast('stateChanged');

                }
            });
            $scope.background = parallaxHelper.createAnimator(-0.3);
}])

.controller('NavCtrl',[
        '$scope',
        '$mdSidenav',

        function($scope, $mdSidenav){
            $scope.snapOpts = {
                tapToClose: true,
                touchToDrag: true
            };
            $scope.openLeftMenu = function() {
                $mdSidenav('left').toggle();
            };
            $scope.$on('stateChanged', function(){
                $mdSidenav('left').close();
            });

    }])

;

<|endoftext|>


<commit_before>angular.module( 'Feathers', [
    'config',
    'Login',
    'Home',

    'templates-app',
    'templates-common',

    'ui.router'
])

.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function ( $stateProvider, $urlRouterProvider, $httpProvider) {

    /**
    * custom httpProvider response
    */
    $httpProvider.interceptors.push(function($rootScope, $q) {
        return {
            'response': function(response) {
                return response;
            },

            'responseError': function(rejection) {
                switch (rejection.status) {
                    case 401 :
                        $rootScope.$emit('httperror', {
                            code : 401
                        })
                        break;
                    case 404 :
                        $rootScope.$emit('httperror', {
                            code : 404
                        })
                        break;
                    case 0 :
                    case 500 :
                        $rootScope.$emit('httperror', {
                            code : 500
                        })
                        break;
                    case 502 :
                        $rootScope.$emit('httperror', {
                            code : 502
                        })
                        break;
                    default :
                        $rootScope.$emit('httperror', {
                            code : 404
                        })
                        break;
                }

                return $q.reject(rejection);
            }
        };
    });

    // if its a wrong url will force redirect to login page
    $urlRouterProvider.otherwise( '/login' );

    $stateProvider.state('index', {
        url: '',
        controller: 'FeathersCtrl'
    })
}])

.run(['$rootScope', '$state', function($rootScope, $state) {

}])

.controller( 'FeathersCtrl', ['$rootScope', '$scope', '$state', 'ENV', '$log', function FeathersCtrl ($rootScope, $scope, $state, ENV , $log) {

    $scope.mode = (ENV === 'development') ? ENV : 'production';
    $state.go('home');

    // when http error
    $rootScope.$on('httperror', function(listener, params) {
        location.href = '/' + params.code + '.html';
    })
}])

;
<commit_msg>remove old app.js file<commit_after><|endoftext|>


<commit_before>var evalApp = angular.module( 'evalApp',
[ 'templates-app',
  'templates-common',
  'evalApp.home',
  'evalApp.about',
  'evalApp.login',
  'evalApp.admin',
  'evalApp.user',
  'evalApp.newTemplate',
  'ui.router'
]);

evalApp.constant('SERVER_URL', 'http://dispatch.ru.is/h37/api/v1/');

evalApp.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( '/login' );
});

evalApp.run( function run () {
});

evalApp.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if ( angular.isDefined( toState.data.pageTitle ) ) {
      $scope.pageTitle = toState.data.pageTitle + ' | Evaluation App' ;
    }
  });
});

evalApp.directive('evaluation-question', function() {
  return ;
});<commit_msg>changed the database location<commit_after>var evalApp = angular.module( 'evalApp',
[ 'templates-app',
  'templates-common',
  'evalApp.home',
  'evalApp.about',
  'evalApp.login',
  'evalApp.admin',
  'evalApp.user',
  'evalApp.newTemplate',
  'ui.router'
]);

evalApp.constant('SERVER_URL', 'http://dispatch.ru.is/h48/api/v1/');

evalApp.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( '/login' );
});

evalApp.run( function run () {
});

evalApp.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if ( angular.isDefined( toState.data.pageTitle ) ) {
      $scope.pageTitle = toState.data.pageTitle + ' | Evaluation App' ;
    }
  });
});

evalApp.directive('evaluation-question', function() {
  return ;
});<|endoftext|>


<commit_before>/*
 * backend.js - backend for scratch86
 * entrypoint to the backend of scratch86 --
 * all code generation is done in this file or required files from here
 * HERE BE DRAGONS!
 */

module.exports = function(project, output) {
    console.log(project);

    console.log("Backend stub");
}
<commit_msg>Code structure to process sprites and scripts<commit_after>/*
 * backend.js - backend for scratch86
 * entrypoint to the backend of scratch86 --
 * all code generation is done in this file or required files from here
 * HERE BE DRAGONS!
 */

// process a script
// this method actually hooks into code generation :)

function processScript(context, script) {
    console.log("Compiling script:");
    console.log(script);
}

// processes a child (basically a sprite)

function processChild(child) {
    // attach some metadata to tag the sprite

    child["86"] = {
        type: "sprite"
    };

    // sprites can have scripts
    // process those seperately

    if(typeof child.scripts !== 'undefined') {
        child.scripts.forEach(function(script) {
            processScript(child, script[2]);
        });
    }
}

module.exports = function(project, output) {
    project.children.forEach(function(child) {
        processChild(child);
    });

    console.log("Backend stub");
}
<|endoftext|>


<commit_before>var toHash = function (object) {
  if (object && !object.smap) {
    return Opal.hash(object);
  }
  return object;
};

// Asciidoctor API

Opal.Asciidoctor['$$class'].$$proto.convert = function (input, options) {
  if (typeof input === 'object' && input.constructor.name === 'Buffer') {
    input = input.toString('utf8');
  }
  var result = this.$convert(input, toHash(options));
  if (result === Opal.nil) {
    return '';
  }
  return result;
};

Opal.Asciidoctor['$$class'].$$proto.convertFile = function (filename, options) {
  return this.$convert_file(filename, toHash(options));
};

Opal.Asciidoctor['$$class'].$$proto.load = function (input, options) {
  if (typeof input === 'object' && input.constructor.name === 'Buffer') {
    input = input.toString('utf8');
  }
  return this.$load(input, toHash(options));
};

Opal.Asciidoctor['$$class'].$$proto.loadFile = function (filename, options) {
  return this.$load_file(filename, toHash(options));
};

// AbstractBlock API

Opal.Asciidoctor.AbstractBlock.$$proto.getTitle = function () {
  var result = this.title;
  if (result === Opal.nil) {
    return '';
  }
  return result;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getStyle = function () {
  return this.style;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getCaption = function () {
  return this.caption;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getLevel = function () {
  return this.level;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getBlocks = function () {
  return this.blocks;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getContent = function () {
  return this.$content();
};

Opal.Asciidoctor.AbstractBlock.$$proto.convert = function () {
  return this.$convert();
};

Opal.Asciidoctor.AbstractBlock.$$proto.delegate = function () {
  return this.$delegate();
};

Opal.Asciidoctor.AbstractBlock.$$proto.findBy = function (selector, block) {
  if (typeof block === 'undefined' && typeof selector === 'function') {
    return Opal.block_send(this, 'find_by', selector);
  }
  else if (typeof block === 'function') {
    return Opal.block_send(this, 'find_by', block, toHash(selector));
  }
  else {
    return this.$find_by(toHash(selector));
  }
};

Opal.Asciidoctor.AbstractBlock.$$proto.convert = function () {
  return this.$convert();
};

// AbstractNode API

Opal.Asciidoctor.AbstractNode.$$proto.getAttributes = function () {
  return this.attributes;
};

Opal.Asciidoctor.AbstractNode.$$proto.getAttribute = function (name, defaultValue, inherit) {
  var value = this.$attr(name, defaultValue, inherit);
  if (value === Opal.nil) {
    return undefined;
  }
  return value;
};

Opal.Asciidoctor.AbstractNode.$$proto.isAttribute = function (name, expectedValue, inherit) {
  var value = this['$attr?'](name, expectedValue, inherit);
  if (value === Opal.nil) {
    return undefined;
  }
  return value;
};

Opal.Asciidoctor.AbstractNode.$$proto.setAttribute = function (name, value, overwrite) {
  if (typeof overwrite === 'undefined') {
    overwrite = true;
  }
  return this.$set_attribute(name, value, overwrite);
};

Opal.Asciidoctor.AbstractNode.$$proto.isInline = function () {
  return this['$inline?']();
};

Opal.Asciidoctor.AbstractNode.$$proto.isBlock = function () {
  return this['$block?']();
};

Opal.Asciidoctor.AbstractNode.$$proto.isRole = function (expected) {
  return this['$role?'](expected);
};

Opal.Asciidoctor.AbstractNode.$$proto.getRole = function () {
  return this.$role();
};

Opal.Asciidoctor.AbstractNode.$$proto.hasRole = function (name) {
  return this['$has_role?'](name);
};

Opal.Asciidoctor.AbstractNode.$$proto.getRoles = function () {
  return this.$roles();
};

Opal.Asciidoctor.AbstractNode.$$proto.addRole = function (name) {
  return this.$add_role(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.removeRole = function (name) {
  return this.$remove_role(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.isReftext = function () {
  return this['$reftext?']();
};

Opal.Asciidoctor.AbstractNode.$$proto.getReftext = function () {
  return this.$reftext();
};

Opal.Asciidoctor.AbstractNode.$$proto.getContext = function () {
  var context =  this.context;
  if (context && typeof context.$to_s === 'function') {
    // Convert Ruby Symbol to String
    return context.$to_s();
  }
  return context;
};

Opal.Asciidoctor.AbstractNode.$$proto.getId = function () {
  return this.id;
};

Opal.Asciidoctor.AbstractNode.$$proto.isOption = function (name) {
  return this['$option?'](name);
};

Opal.Asciidoctor.AbstractNode.$$proto.setOption = function (name) {
  return this.$set_option(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.getIconURI = function (name) {
  return this.$icon_uri(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.getMediaURI = function (target, assetDirKey) {
  return this.$media_uri(target, assetDirKey);
};

Opal.Asciidoctor.AbstractNode.$$proto.getImageURI = function (targetImage, assetDirKey) {
  return this.$image_uri(targetImage, assetDirKey);
};

Opal.Asciidoctor.AbstractNode.$$proto.getConverter = function () {
  return this.$converter();
};

Opal.Asciidoctor.AbstractNode.$$proto.readContents = function (target, options) {
  return this.$read_contents(target, toHash(options));
};

Opal.Asciidoctor.AbstractNode.$$proto.readAsset = function (path, options) {
  return this.$read_asset(path, toHash(options));
};

Opal.Asciidoctor.AbstractNode.$$proto.normalizeWebPath = function (target, start, preserveTargetURI) {
  return this.$normalize_web_path(target, start, preserveTargetURI);
};

Opal.Asciidoctor.AbstractNode.$$proto.normalizeSystemPath = function (target, start, jail, options) {
  return this.$normalize_system_path(target, start, jail, toHash(options));
};

Opal.Asciidoctor.AbstractNode.$$proto.normalizeAssetPath = function (assetRef, assetName, autoCorrect) {
  return this.$normalize_asset_path(assetRef, assetName, autoCorrect);
};

// Document API

Opal.Asciidoctor.Document.$$proto.getHeader = function () {
  return this.header;
};

Opal.Asciidoctor.Document.$$proto.setAttribute = function (name, value) {
  return this.$set_attribute(name, value);
};

Opal.Asciidoctor.Document.$$proto.removeAttribute = function (name) {
  this.attributes.$delete(name);
  this.attribute_overrides.$delete(name);
};

Opal.Asciidoctor.Document.$$proto.convert = function (options) {
  var result = this.$convert(toHash(options));
  if (result === Opal.nil) {
    return '';
  }
  return result;
};

Opal.Asciidoctor.Document.$$proto.write = function (output, target) {
  return this.$write(output, target);
};

Opal.Asciidoctor.Document.$$proto.getAuthor = function () {
  return this.$author();
};

Opal.Asciidoctor.Document.$$proto.getSource = function () {
  return this.$source();
};

Opal.Asciidoctor.Document.$$proto.getSourceLines = function () {
  return this.$source_lines();
};

Opal.Asciidoctor.Document.$$proto.isNested = function () {
  return this['$nested?']();
};

Opal.Asciidoctor.Document.$$proto.hasFootnotes = function () {
  return this['$footnotes?']();
};

Opal.Asciidoctor.Document.$$proto.getFootnotes = function () {
  return this.$footnotes();
};

Opal.Asciidoctor.Document.$$proto.isEmbedded = function () {
  return this['$embedded?']();
};

Opal.Asciidoctor.Document.$$proto.hasExtensions = function () {
  return this['$extensions?']();
};

Opal.Asciidoctor.Document.$$proto.getDoctype = function () {
  return this.$doctype();
};

Opal.Asciidoctor.Document.$$proto.getBackend = function () {
  return this.$backend();
};

Opal.Asciidoctor.Document.$$proto.isBasebackend = function (base) {
  return this['$basebackend?'](base);
};

Opal.Asciidoctor.Document.$$proto.getTitle = function () {
  return this.$title();
};

Opal.Asciidoctor.Document.$$proto.setTitle = function (title) {
  return this['$title='](title);
};

Opal.Asciidoctor.Document.$$proto.getDoctitle = function (options) {
  return this.$doctitle(toHash(options));
};

Opal.Asciidoctor.Document.$$proto.getRevdate = function () {
  return this.$revdate();
};

Opal.Asciidoctor.Document.$$proto.getNotitle = function () {
  return this.$notitle();
};

Opal.Asciidoctor.Document.$$proto.getNoheader = function () {
  return this.$noheader();
};

Opal.Asciidoctor.Document.$$proto.getNofooter = function () {
  return this.$nofooter();
};

Opal.Asciidoctor.Document.$$proto.hasHeader = function () {
  return this['$header?']();
};

Opal.Asciidoctor.Document.$$proto.deleteAttribute = function (name) {
  return this.$delete_attribute(name);
};

Opal.Asciidoctor.Document.$$proto.isAttributeLocked = function (name) {
  return this['$attribute_locked?'](name);
};

Opal.Asciidoctor.Document.$$proto.parse = function (data) {
  return this.$parse(data);
};

Opal.Asciidoctor.Document.$$proto.getDocinfo = function (docinfoLocation, suffix) {
  return this.$docinfo(docinfoLocation, suffix);
};

Opal.Asciidoctor.Document.$$proto.hasDocinfoProcessors = function (docinfoLocation) {
  return this['$docinfo_processors?'](docinfoLocation);
};

Opal.Asciidoctor.Document.$$proto.counterIncrement = function (counterName, block) {
  return this.$counter_increment(counterName, block);
};

Opal.Asciidoctor.Document.$$proto.counter = function (name, seed) {
  return this.$counter(name, seed);
};

Opal.Asciidoctor.Document.$$proto.getSafe = function () {
  return this.$safe;
};

Opal.Asciidoctor.Document.$$proto.getCompatMode = function () {
  return this.$compat_mode;
};

Opal.Asciidoctor.Document.$$proto.getSourcemap = function () {
  return this.$sourcemap;
};

Opal.Asciidoctor.Document.$$proto.getReferences = function () {
  return this.$references;
};

Opal.Asciidoctor.Document.$$proto.getCounters = function () {
  return this.$counters;
};

Opal.Asciidoctor.Document.$$proto.getCallouts = function () {
  return this.$callouts;
};

Opal.Asciidoctor.Document.$$proto.getBaseDir = function () {
  return this.$base_dir;
};

Opal.Asciidoctor.Document.$$proto.getOptions = function () {
  return this.$options;
};

Opal.Asciidoctor.Document.$$proto.getOutfilesuffix = function () {
  return this.$outfilesuffix;
};

Opal.Asciidoctor.Document.$$proto.getParentDocument = function () {
  return this.$parent_document;
};

Opal.Asciidoctor.Document.$$proto.getReader = function () {
  return this.$reader;
};

Opal.Asciidoctor.Document.$$proto.getConverter = function () {
  return this.$converter;
};

Opal.Asciidoctor.Document.$$proto.getExtensions = function () {
  return this.$extensions;
};

// Document.Title API

Opal.Asciidoctor.Document.Title.$$proto.getMain = function () {
  return this.main;
};

Opal.Asciidoctor.Document.Title.$$proto.getCombined = function () {
  return this.combined;
};

Opal.Asciidoctor.Document.Title.$$proto.getSubtitle = function () {
  return this.subtitle;
};

Opal.Asciidoctor.Document.Title.$$proto.isSanitized = function () {
  var sanitized = this['$sanitized?']();
  if (sanitized === Opal.nil) {
    return false;
  }
  return sanitized;
};

Opal.Asciidoctor.Document.Title.$$proto.hasSubtitle = function () {
  return this['$subtitle?']();
};
<commit_msg>findBy API: upgrade code to Opal 0.11<commit_after>var toHash = function (object) {
  if (object && !object.smap) {
    return Opal.hash(object);
  }
  return object;
};

// Asciidoctor API

Opal.Asciidoctor['$$class'].$$proto.convert = function (input, options) {
  if (typeof input === 'object' && input.constructor.name === 'Buffer') {
    input = input.toString('utf8');
  }
  var result = this.$convert(input, toHash(options));
  if (result === Opal.nil) {
    return '';
  }
  return result;
};

Opal.Asciidoctor['$$class'].$$proto.convertFile = function (filename, options) {
  return this.$convert_file(filename, toHash(options));
};

Opal.Asciidoctor['$$class'].$$proto.load = function (input, options) {
  if (typeof input === 'object' && input.constructor.name === 'Buffer') {
    input = input.toString('utf8');
  }
  return this.$load(input, toHash(options));
};

Opal.Asciidoctor['$$class'].$$proto.loadFile = function (filename, options) {
  return this.$load_file(filename, toHash(options));
};

// AbstractBlock API

Opal.Asciidoctor.AbstractBlock.$$proto.getTitle = function () {
  var result = this.title;
  if (result === Opal.nil) {
    return '';
  }
  return result;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getStyle = function () {
  return this.style;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getCaption = function () {
  return this.caption;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getLevel = function () {
  return this.level;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getBlocks = function () {
  return this.blocks;
};

Opal.Asciidoctor.AbstractBlock.$$proto.getContent = function () {
  return this.$content();
};

Opal.Asciidoctor.AbstractBlock.$$proto.convert = function () {
  return this.$convert();
};

Opal.Asciidoctor.AbstractBlock.$$proto.delegate = function () {
  return this.$delegate();
};

Opal.Asciidoctor.AbstractBlock.$$proto.findBy = function (selector, block) {
  if (typeof block === 'undefined' && typeof selector === 'function') {
    return Opal.send(this, 'find_by', null, selector);
  }
  else if (typeof block === 'function') {
    return Opal.send(this, 'find_by', toHash(selector), block);
  }
  else {
    return this.$find_by(toHash(selector));
  }
};

Opal.Asciidoctor.AbstractBlock.$$proto.convert = function () {
  return this.$convert();
};

// AbstractNode API

Opal.Asciidoctor.AbstractNode.$$proto.getAttributes = function () {
  return this.attributes;
};

Opal.Asciidoctor.AbstractNode.$$proto.getAttribute = function (name, defaultValue, inherit) {
  var value = this.$attr(name, defaultValue, inherit);
  if (value === Opal.nil) {
    return undefined;
  }
  return value;
};

Opal.Asciidoctor.AbstractNode.$$proto.isAttribute = function (name, expectedValue, inherit) {
  var value = this['$attr?'](name, expectedValue, inherit);
  if (value === Opal.nil) {
    return undefined;
  }
  return value;
};

Opal.Asciidoctor.AbstractNode.$$proto.setAttribute = function (name, value, overwrite) {
  if (typeof overwrite === 'undefined') {
    overwrite = true;
  }
  return this.$set_attribute(name, value, overwrite);
};

Opal.Asciidoctor.AbstractNode.$$proto.isInline = function () {
  return this['$inline?']();
};

Opal.Asciidoctor.AbstractNode.$$proto.isBlock = function () {
  return this['$block?']();
};

Opal.Asciidoctor.AbstractNode.$$proto.isRole = function (expected) {
  return this['$role?'](expected);
};

Opal.Asciidoctor.AbstractNode.$$proto.getRole = function () {
  return this.$role();
};

Opal.Asciidoctor.AbstractNode.$$proto.hasRole = function (name) {
  return this['$has_role?'](name);
};

Opal.Asciidoctor.AbstractNode.$$proto.getRoles = function () {
  return this.$roles();
};

Opal.Asciidoctor.AbstractNode.$$proto.addRole = function (name) {
  return this.$add_role(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.removeRole = function (name) {
  return this.$remove_role(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.isReftext = function () {
  return this['$reftext?']();
};

Opal.Asciidoctor.AbstractNode.$$proto.getReftext = function () {
  return this.$reftext();
};

Opal.Asciidoctor.AbstractNode.$$proto.getContext = function () {
  var context =  this.context;
  if (context && typeof context.$to_s === 'function') {
    // Convert Ruby Symbol to String
    return context.$to_s();
  }
  return context;
};

Opal.Asciidoctor.AbstractNode.$$proto.getId = function () {
  return this.id;
};

Opal.Asciidoctor.AbstractNode.$$proto.isOption = function (name) {
  return this['$option?'](name);
};

Opal.Asciidoctor.AbstractNode.$$proto.setOption = function (name) {
  return this.$set_option(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.getIconURI = function (name) {
  return this.$icon_uri(name);
};

Opal.Asciidoctor.AbstractNode.$$proto.getMediaURI = function (target, assetDirKey) {
  return this.$media_uri(target, assetDirKey);
};

Opal.Asciidoctor.AbstractNode.$$proto.getImageURI = function (targetImage, assetDirKey) {
  return this.$image_uri(targetImage, assetDirKey);
};

Opal.Asciidoctor.AbstractNode.$$proto.getConverter = function () {
  return this.$converter();
};

Opal.Asciidoctor.AbstractNode.$$proto.readContents = function (target, options) {
  return this.$read_contents(target, toHash(options));
};

Opal.Asciidoctor.AbstractNode.$$proto.readAsset = function (path, options) {
  return this.$read_asset(path, toHash(options));
};

Opal.Asciidoctor.AbstractNode.$$proto.normalizeWebPath = function (target, start, preserveTargetURI) {
  return this.$normalize_web_path(target, start, preserveTargetURI);
};

Opal.Asciidoctor.AbstractNode.$$proto.normalizeSystemPath = function (target, start, jail, options) {
  return this.$normalize_system_path(target, start, jail, toHash(options));
};

Opal.Asciidoctor.AbstractNode.$$proto.normalizeAssetPath = function (assetRef, assetName, autoCorrect) {
  return this.$normalize_asset_path(assetRef, assetName, autoCorrect);
};

// Document API

Opal.Asciidoctor.Document.$$proto.getHeader = function () {
  return this.header;
};

Opal.Asciidoctor.Document.$$proto.setAttribute = function (name, value) {
  return this.$set_attribute(name, value);
};

Opal.Asciidoctor.Document.$$proto.removeAttribute = function (name) {
  this.attributes.$delete(name);
  this.attribute_overrides.$delete(name);
};

Opal.Asciidoctor.Document.$$proto.convert = function (options) {
  var result = this.$convert(toHash(options));
  if (result === Opal.nil) {
    return '';
  }
  return result;
};

Opal.Asciidoctor.Document.$$proto.write = function (output, target) {
  return this.$write(output, target);
};

Opal.Asciidoctor.Document.$$proto.getAuthor = function () {
  return this.$author();
};

Opal.Asciidoctor.Document.$$proto.getSource = function () {
  return this.$source();
};

Opal.Asciidoctor.Document.$$proto.getSourceLines = function () {
  return this.$source_lines();
};

Opal.Asciidoctor.Document.$$proto.isNested = function () {
  return this['$nested?']();
};

Opal.Asciidoctor.Document.$$proto.hasFootnotes = function () {
  return this['$footnotes?']();
};

Opal.Asciidoctor.Document.$$proto.getFootnotes = function () {
  return this.$footnotes();
};

Opal.Asciidoctor.Document.$$proto.isEmbedded = function () {
  return this['$embedded?']();
};

Opal.Asciidoctor.Document.$$proto.hasExtensions = function () {
  return this['$extensions?']();
};

Opal.Asciidoctor.Document.$$proto.getDoctype = function () {
  return this.$doctype();
};

Opal.Asciidoctor.Document.$$proto.getBackend = function () {
  return this.$backend();
};

Opal.Asciidoctor.Document.$$proto.isBasebackend = function (base) {
  return this['$basebackend?'](base);
};

Opal.Asciidoctor.Document.$$proto.getTitle = function () {
  return this.$title();
};

Opal.Asciidoctor.Document.$$proto.setTitle = function (title) {
  return this['$title='](title);
};

Opal.Asciidoctor.Document.$$proto.getDoctitle = function (options) {
  return this.$doctitle(toHash(options));
};

Opal.Asciidoctor.Document.$$proto.getRevdate = function () {
  return this.$revdate();
};

Opal.Asciidoctor.Document.$$proto.getNotitle = function () {
  return this.$notitle();
};

Opal.Asciidoctor.Document.$$proto.getNoheader = function () {
  return this.$noheader();
};

Opal.Asciidoctor.Document.$$proto.getNofooter = function () {
  return this.$nofooter();
};

Opal.Asciidoctor.Document.$$proto.hasHeader = function () {
  return this['$header?']();
};

Opal.Asciidoctor.Document.$$proto.deleteAttribute = function (name) {
  return this.$delete_attribute(name);
};

Opal.Asciidoctor.Document.$$proto.isAttributeLocked = function (name) {
  return this['$attribute_locked?'](name);
};

Opal.Asciidoctor.Document.$$proto.parse = function (data) {
  return this.$parse(data);
};

Opal.Asciidoctor.Document.$$proto.getDocinfo = function (docinfoLocation, suffix) {
  return this.$docinfo(docinfoLocation, suffix);
};

Opal.Asciidoctor.Document.$$proto.hasDocinfoProcessors = function (docinfoLocation) {
  return this['$docinfo_processors?'](docinfoLocation);
};

Opal.Asciidoctor.Document.$$proto.counterIncrement = function (counterName, block) {
  return this.$counter_increment(counterName, block);
};

Opal.Asciidoctor.Document.$$proto.counter = function (name, seed) {
  return this.$counter(name, seed);
};

Opal.Asciidoctor.Document.$$proto.getSafe = function () {
  return this.$safe;
};

Opal.Asciidoctor.Document.$$proto.getCompatMode = function () {
  return this.$compat_mode;
};

Opal.Asciidoctor.Document.$$proto.getSourcemap = function () {
  return this.$sourcemap;
};

Opal.Asciidoctor.Document.$$proto.getReferences = function () {
  return this.$references;
};

Opal.Asciidoctor.Document.$$proto.getCounters = function () {
  return this.$counters;
};

Opal.Asciidoctor.Document.$$proto.getCallouts = function () {
  return this.$callouts;
};

Opal.Asciidoctor.Document.$$proto.getBaseDir = function () {
  return this.$base_dir;
};

Opal.Asciidoctor.Document.$$proto.getOptions = function () {
  return this.$options;
};

Opal.Asciidoctor.Document.$$proto.getOutfilesuffix = function () {
  return this.$outfilesuffix;
};

Opal.Asciidoctor.Document.$$proto.getParentDocument = function () {
  return this.$parent_document;
};

Opal.Asciidoctor.Document.$$proto.getReader = function () {
  return this.$reader;
};

Opal.Asciidoctor.Document.$$proto.getConverter = function () {
  return this.$converter;
};

Opal.Asciidoctor.Document.$$proto.getExtensions = function () {
  return this.$extensions;
};

// Document.Title API

Opal.Asciidoctor.Document.Title.$$proto.getMain = function () {
  return this.main;
};

Opal.Asciidoctor.Document.Title.$$proto.getCombined = function () {
  return this.combined;
};

Opal.Asciidoctor.Document.Title.$$proto.getSubtitle = function () {
  return this.subtitle;
};

Opal.Asciidoctor.Document.Title.$$proto.isSanitized = function () {
  var sanitized = this['$sanitized?']();
  if (sanitized === Opal.nil) {
    return false;
  }
  return sanitized;
};

Opal.Asciidoctor.Document.Title.$$proto.hasSubtitle = function () {
  return this['$subtitle?']();
};
<|endoftext|>


<commit_before>const ID_PROP = '__Inferno__id__';
let counter = 1;

export default function InfernoNodeID(node, onlyGet) {
    return node[ID_PROP] || (onlyGet? null : node[ID_PROP] = counter++);
}<commit_msg>changed null to 0<commit_after>const INFERNO_PROP = '__Inferno__id__';
let counter = 1;

export default function InfernoNodeID(node, get) {
    return node[INFERNO_PROP] ||
	       (get ? 0 : node[INFERNO_PROP] = counter++);
}<|endoftext|>


<commit_before>import Context from "../context"
import ContextTypes from "../context-types"
import Operation from "./operation"
import Expression from "./expression"
import Doc from "./doc"
export default class Unary extends Operation {
    /** @type {string} */
    get type() {
        return this.node.type
    }
    /** @type {Expression} */
    get what() {
        return this.cacheNode("what")
    }
    /**
     * Checks that syntax seems ok
     * @param {Context} context
     * @param {boolean} [in_call]
     * @param {?Doc} [doc]
     * @returns {?ContextTypes} The set of types applicable to this value
     */
    check(context, in_call = false, doc = null) {
        super.check(context, in_call, doc)
        return this.what.check(context, false, null) // FIXME infer from type
    }
}
<commit_msg>Add a unary operator (!)<commit_after>import Context from "../context"
import ContextTypes from "../context-types"
import Operation from "./operation"
import Expression from "./expression"
import Doc from "./doc"
import {PHPSimpleType} from "../phptype"
export default class Unary extends Operation {
    /** @type {string} */
    get type() {
        return this.node.type
    }
    /** @type {Expression} */
    get what() {
        return this.cacheNode("what")
    }
    /**
     * Checks that syntax seems ok
     * @param {Context} context
     * @param {boolean} [in_call]
     * @param {?Doc} [doc]
     * @returns {?ContextTypes} The set of types applicable to this value
     */
    check(context, in_call = false, doc = null) {
        super.check(context, in_call, doc)
        if(this.type == "!") {
            let etype = this.what.check(context, false, null).expressionType
            let etype_single
            if(
                etype.types.length == 1 &&
                (etype_single = etype.types[0]) &&
                etype_single instanceof PHPSimpleType &&
                etype_single.values.length > 0
            ) {
                let possible_values = {}
                etype_single.values.forEach(
                    v => possible_values[+!v] = !v
                )
                if(Object.keys(possible_values).length == 1) {
                    return new ContextTypes(PHPSimpleType.coreTypes.bool.withValue(Object.values(possible_values)[0]))
                }
            }
            return new ContextTypes(PHPSimpleType.coreTypes.bool)
        } else {
            console.log(`TODO: Unary type ${this.type} not handled yet`)
            return this.what.check(context, false, null)
        }
    }
}
<|endoftext|>


<commit_before>"use strict";

const noop = () => {};

require("./res/stylesheet.css");

module.exports = setup => {

    window.addEventListener("load", () => {
        let
            touchEvent;
        const
            mapping = setup(),
            click = e => {
                let
                    x = e.clientX,
                    y = e.clientY;
                if (Object.keys(mapping).every(id => {
                    if ("undefined" === id) {
                        return true; // skip
                    }
                    const rect = document.getElementById(id).getBoundingClientRect();
                    if (!(x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)) {
                        mapping[id]();
                        return false;
                    }
                    return true;

                })) {
                    (mapping["undefined"] || noop)();
                }
            };

        window.addEventListener("click", click, true);
        window.addEventListener("touchstart", e => {
            touchEvent = e;
        }, false);
        window.addEventListener("touchmove", () => {
            touchEvent = null;
        }, false);
        window.addEventListener("touchend", () => {
            if (null !== touchEvent) {
                click(touchEvent);
                touchEvent = null;
            }
        }, false);
    });

};
<commit_msg>Fixing coordinates extraction and double click when touch enabled<commit_after>"use strict";

const noop = () => {};

require("./res/stylesheet.css");

module.exports = setup => {

    window.addEventListener("load", () => {
        let
            touchDisabled = true,
            touchEvent;
        const
            mapping = setup(),
            coords = e => e.touches
                ? {x: e.touches[0].clientX, y: e.touches[0].clientY}
                : {x: e.clientX, y: e.clientY},
            click = e => {
                const {x, y} = coords(e);
                if (Object.keys(mapping).every(id => {
                    if ("undefined" === id) {
                        return true; // skip
                    }
                    const rect = document.getElementById(id).getBoundingClientRect();
                    if (!(x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)) {
                        mapping[id]();
                        return false;
                    }
                    return true;

                })) {
                    (mapping["undefined"] || noop)();
                }
            };

        window.addEventListener("click", e => touchDisabled ? click(e) : 0, true);
        window.addEventListener("touchstart", e => {
            touchDisabled = false;
            touchEvent = e;
        }, false);
        window.addEventListener("touchmove", () => {
            touchEvent = null;
        }, false);
        window.addEventListener("touchend", () => {
            if (null !== touchEvent) {
                click(touchEvent);
                touchEvent = null;
            }
        }, false);
    });

};
<|endoftext|>


<commit_before>/**
 * This is the web browser implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
               && 'undefined' != typeof chrome.storage
                  ? chrome.storage.local
                  : localstorage();

/**
 * Colors.
 */

exports.colors = [
  'lightseagreen',
  'forestgreen',
  'goldenrod',
  'dodgerblue',
  'darkorchid',
  'crimson'
];

/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */

function useColors() {
  // NB: In an Electron preload script, document will be defined but not fully
  // initialized. Since we know we're in Chrome, we'll just detect this case
  // explicitly
  if (typeof window !== 'undefined' && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
    return true;
  }

  // is webkit? http://stackoverflow.com/a/16459606/376773
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
    // is firebug? http://stackoverflow.com/a/398120/376773
    (typeof window !== 'undefined' && window.console && (console.firebug || (console.exception && console.table))) ||
    // is firefox >= v31?
    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
    (navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
    // double check webkit in userAgent just in case we are in a worker
    (navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}

/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */

exports.formatters.j = function(v) {
  try {
    return JSON.stringify(v);
  } catch (err) {
    return '[UnexpectedJSONParseError]: ' + err.message;
  }
};

/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */

function formatArgs(args) {
  var useColors = this.useColors;

  args[0] = (useColors ? '%c' : '')
    + this.namespace
    + (useColors ? ' %c' : ' ')
    + args[0]
    + (useColors ? '%c ' : ' ')
    + '+' + exports.humanize(this.diff);

  if (!useColors) return;

  var c = 'color: ' + this.color;
  args.splice(1, 0, c, 'color: inherit')

  // the final "%c" is somewhat tricky, because there could be other
  // arguments passed either before or after the %c, so we need to
  // figure out the correct index to insert the CSS into
  var index = 0;
  var lastC = 0;
  args[0].replace(/%[a-zA-Z%]/g, function(match) {
    if ('%%' === match) return;
    index++;
    if ('%c' === match) {
      // we only are interested in the *last* %c
      // (the user may have provided their own)
      lastC = index;
    }
  });

  args.splice(lastC, 0, c);
}

/**
 * Invokes `console.log()` when available.
 * No-op when `console.log` is not a "function".
 *
 * @api public
 */

function log() {
  // this hackery is required for IE8/9, where
  // the `console.log` function doesn't have 'apply'
  return 'object' === typeof console
    && console.log
    && Function.prototype.apply.call(console.log, console, arguments);
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */

function save(namespaces) {
  try {
    if (null == namespaces) {
      exports.storage.removeItem('debug');
    } else {
      exports.storage.debug = namespaces;
    }
  } catch(e) {}
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
  try {
    return exports.storage.debug;
  } catch(e) {}

  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (typeof process !== 'undefined' && 'env' in process) {
    return process.env.DEBUG;
  }
}

/**
 * Enable namespaces listed in `localStorage.debug` initially.
 */

exports.enable(load());

/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */

function localstorage() {
  try {
    return window.localStorage;
  } catch (e) {}
}
<commit_msg>better null pointer checks for browser useColors<commit_after>/**
 * This is the web browser implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
               && 'undefined' != typeof chrome.storage
                  ? chrome.storage.local
                  : localstorage();

/**
 * Colors.
 */

exports.colors = [
  'lightseagreen',
  'forestgreen',
  'goldenrod',
  'dodgerblue',
  'darkorchid',
  'crimson'
];

/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */

function useColors() {
  // NB: In an Electron preload script, document will be defined but not fully
  // initialized. Since we know we're in Chrome, we'll just detect this case
  // explicitly
  if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
    return true;
  }

  // is webkit? http://stackoverflow.com/a/16459606/376773
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||
    // is firebug? http://stackoverflow.com/a/398120/376773
    (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||
    // is firefox >= v31?
    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
    (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
    // double check webkit in userAgent just in case we are in a worker
    (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}

/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */

exports.formatters.j = function(v) {
  try {
    return JSON.stringify(v);
  } catch (err) {
    return '[UnexpectedJSONParseError]: ' + err.message;
  }
};

/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */

function formatArgs(args) {
  var useColors = this.useColors;

  args[0] = (useColors ? '%c' : '')
    + this.namespace
    + (useColors ? ' %c' : ' ')
    + args[0]
    + (useColors ? '%c ' : ' ')
    + '+' + exports.humanize(this.diff);

  if (!useColors) return;

  var c = 'color: ' + this.color;
  args.splice(1, 0, c, 'color: inherit')

  // the final "%c" is somewhat tricky, because there could be other
  // arguments passed either before or after the %c, so we need to
  // figure out the correct index to insert the CSS into
  var index = 0;
  var lastC = 0;
  args[0].replace(/%[a-zA-Z%]/g, function(match) {
    if ('%%' === match) return;
    index++;
    if ('%c' === match) {
      // we only are interested in the *last* %c
      // (the user may have provided their own)
      lastC = index;
    }
  });

  args.splice(lastC, 0, c);
}

/**
 * Invokes `console.log()` when available.
 * No-op when `console.log` is not a "function".
 *
 * @api public
 */

function log() {
  // this hackery is required for IE8/9, where
  // the `console.log` function doesn't have 'apply'
  return 'object' === typeof console
    && console.log
    && Function.prototype.apply.call(console.log, console, arguments);
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */

function save(namespaces) {
  try {
    if (null == namespaces) {
      exports.storage.removeItem('debug');
    } else {
      exports.storage.debug = namespaces;
    }
  } catch(e) {}
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
  try {
    return exports.storage.debug;
  } catch(e) {}

  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (typeof process !== 'undefined' && 'env' in process) {
    return process.env.DEBUG;
  }
}

/**
 * Enable namespaces listed in `localStorage.debug` initially.
 */

exports.enable(load());

/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */

function localstorage() {
  try {
    return window.localStorage;
  } catch (e) {}
}
<|endoftext|>


<commit_before>goog.provide('ol.source.WMTS');
goog.provide('ol.source.WMTSRequestEncoding');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.math');
goog.require('goog.object');
goog.require('goog.uri.utils');
goog.require('ol.TileCoord');
goog.require('ol.TileUrlFunction');
goog.require('ol.TileUrlFunctionType');
goog.require('ol.extent');
goog.require('ol.proj');
goog.require('ol.source.ImageTileSource');
goog.require('ol.tilegrid.WMTS');

/**
 * @enum {string}
 */
ol.source.WMTSRequestEncoding = {
  KVP: 'KVP',  // see spec §8
  REST: 'REST' // see spec §10
};

/**
 * @constructor
 * @extends {ol.source.ImageTileSource}
 * @param {ol.source.WMTSOptions} options WMTS options.
 */
ol.source.WMTS = function(options) {

  // TODO: add support for TileMatrixLimits

  var version = goog.isDef(options.version) ? options.version : '1.0.0';
  var format = goog.isDef(options.format) ? options.format : 'image/jpeg';
  var dimensions = options.dimensions || {};

  // FIXME: should we guess this requestEncoding from options.url(s)
  //        structure? that would mean KVP only if a template is not provided.
  var requestEncoding = goog.isDef(options.requestEncoding) ?
      options.requestEncoding : ol.source.WMTSRequestEncoding.KVP;

  // FIXME: should we create a default tileGrid?
  // we could issue a getCapabilities xhr to retrieve missing configuration
  var tileGrid = options.tileGrid;

  var context = {
    'Layer': options.layer,
    'style': options.style,
    'Style': options.style,
    'TileMatrixSet': options.matrixSet
  };
  goog.object.extend(context, dimensions);
  var kvpParams;
  if (requestEncoding == ol.source.WMTSRequestEncoding.KVP) {
    kvpParams = {
      'Service': 'WMTS',
      'Request': 'GetTile',
      'Version': version,
      'Format': format,
      'TileMatrix': '{TileMatrix}',
      'TileRow': '{TileRow}',
      'TileCol': '{TileCol}'
    };
    goog.object.extend(kvpParams, context);
  }

  /**
   * @param {string} template Template.
   * @return {ol.TileUrlFunctionType} Tile URL function.
   */
  function createFromWMTSTemplate(template) {
    return (
        /**
         * @this {ol.source.WMTS}
         * @param {ol.TileCoord} tileCoord Tile coordinate.
         * @param {ol.Projection} projection Projection.
         * @return {string|undefined} Tile URL.
         */
        function(tileCoord, projection) {
          if (goog.isNull(tileCoord)) {
            return undefined;
          } else {
            var localContext = {
              'TileMatrix': tileGrid.getMatrixId(tileCoord.z),
              'TileCol': tileCoord.x,
              'TileRow': tileCoord.y
            };
            if (requestEncoding != ol.source.WMTSRequestEncoding.KVP) {
              goog.object.extend(localContext, context);
            }
            var url = template;
            for (var key in localContext) {
              // FIXME: should we filter properties with hasOwnProperty?
              url = url.replace('{' + key + '}', localContext[key])
                  .replace('%7B' + key + '%7D', localContext[key]);
            }
            return url;
          }
        });
  }

  var tileUrlFunction = ol.TileUrlFunction.nullTileUrlFunction;
  var urls = options.urls;
  if (!goog.isDef(urls) && goog.isDef(options.url)) {
    urls = ol.TileUrlFunction.expandUrl(options.url);
  }
  if (goog.isDef(urls)) {
    tileUrlFunction = ol.TileUrlFunction.createFromTileUrlFunctions(
        goog.array.map(urls, function(url) {
          if (goog.isDef(kvpParams)) {
            // TODO: we may want to create our own appendParams function
            // so that params order conforms to wmts spec guidance,
            // and so that we can avoid to escape special template params
            url = goog.uri.utils.appendParamsFromMap(url, kvpParams);
          }
          return createFromWMTSTemplate(url);
        }));
  }

  var tmpExtent = ol.extent.createEmpty();
  var tmpTileCoord = new ol.TileCoord(0, 0, 0);
  tileUrlFunction = ol.TileUrlFunction.withTileCoordTransform(
      /**
       * @param {ol.TileCoord} tileCoord Tile coordinate.
       * @param {ol.Projection} projection Projection.
       * @param {ol.TileCoord=} opt_tileCoord Tile coordinate.
       * @return {ol.TileCoord} Tile coordinate.
       */
      function(tileCoord, projection, opt_tileCoord) {
        var tileGrid = this.getTileGrid();
        goog.asserts.assert(!goog.isNull(tileGrid));
        if (tileGrid.getResolutions().length <= tileCoord.z) {
          return null;
        }
        var x = tileCoord.x;
        var y = -tileCoord.y - 1;
        var tileExtent = tileGrid.getTileCoordExtent(tileCoord);
        var projectionExtent = projection.getExtent();
        var extent = goog.isDef(options.extent) ?
            options.extent : projectionExtent;

        if (!goog.isNull(extent) && projection.isGlobal() &&
            extent[0] === projectionExtent[0] &&
            extent[1] === projectionExtent[1]) {
          var numCols = Math.ceil(
              (extent[1] - extent[0]) / (tileExtent[1] - tileExtent[0]));
          x = goog.math.modulo(x, numCols);
          tmpTileCoord.z = tileCoord.z;
          tmpTileCoord.x = x;
          tmpTileCoord.y = tileCoord.y;
          tileExtent = tileGrid.getTileCoordExtent(tmpTileCoord, tmpExtent);
        }
        if (!ol.extent.intersects(tileExtent, extent)) {
          return null;
        }
        return new ol.TileCoord(tileCoord.z, x, y);
      },
      tileUrlFunction);

  goog.base(this, {
    attributions: options.attributions,
    crossOrigin: options.crossOrigin,
    extent: options.extent,
    projection: options.projection,
    tileGrid: tileGrid,
    tileUrlFunction: tileUrlFunction
  });

};
goog.inherits(ol.source.WMTS, ol.source.ImageTileSource);

/**
 * @param {Object} wmtsCap An object representing the capabilities document.
 * @param {string} layer The layer identifier.
 * @return {ol.source.WMTSOptions} WMTS source options object.
 */
ol.source.WMTS.optionsFromCapabilities = function(wmtsCap, layer) {

  // TODO: add support for TileMatrixLimits

  var layers = wmtsCap['contents']['layers'];
  var l = goog.array.find(layers, function(elt, index, array) {
    return elt['identifier'] == layer;
  });
  goog.asserts.assert(!goog.isNull(l));
  goog.asserts.assert(l['tileMatrixSetLinks'].length > 0);
  var matrixSet = /** @type {string} */
      (l['tileMatrixSetLinks'][0]['tileMatrixSet']);
  var format = /** @type {string} */ (l['formats'][0]);
  var idx = goog.array.findIndex(l['styles'], function(elt, index, array) {
    return elt['isDefault'];
  });
  if (idx < 0) {
    idx = 0;
  }
  var style = /** @type {string} */ (l['styles'][idx]['identifier']);

  var dimensions = {};
  goog.array.forEach(l['dimensions'], function(elt, index, array) {
    var key = elt['identifier'];
    var value = elt['default'];
    if (goog.isDef(value)) {
      goog.asserts.assert(goog.array.indexOf(elt['values'], value) >= 0);
    } else {
      value = elt['values'][0];
    }
    goog.asserts.assert(goog.isDef(value));
    dimensions[key] = value;
  });

  var matrixSets = wmtsCap['contents']['tileMatrixSets'];
  goog.asserts.assert(matrixSet in matrixSets);
  var matrixSetObj = matrixSets[matrixSet];

  var tileGrid = ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet(
      matrixSetObj);

  var projection = ol.proj.get(matrixSetObj['supportedCRS']);

  var gets = wmtsCap['operationsMetadata']['GetTile']['dcp']['http']['get'];
  var encodings = goog.object.getKeys(
      gets[0]['constraints']['GetEncoding']['allowedValues']);
  goog.asserts.assert(encodings.length > 0);

  var urls;
  var requestEncoding;
  switch (encodings[0]) {
    case 'REST':
    case 'RESTful':
      // The OGC documentation is not clear if we should use REST or RESTful,
      // ArcGis use RESTful, and OpenLayers use REST.
      requestEncoding = ol.source.WMTSRequestEncoding.REST;
      goog.asserts.assert(l['resourceUrls'].hasOwnProperty('tile'));
      goog.asserts.assert(l['resourceUrls']['tile'].hasOwnProperty(format));
      urls = /** @type {Array.<string>} */
          (l['resourceUrls']['tile'][format]);
      break;
    case 'KVP':
      requestEncoding = ol.source.WMTSRequestEncoding.KVP;
      urls = [];
      goog.array.forEach(gets, function(elt, index, array) {
        if (elt['constraints']['GetEncoding']['allowedValues'].hasOwnProperty(
            ol.source.WMTSRequestEncoding.KVP)) {
          urls.push(/** @type {string} */ (elt['url']));
        }
      });
      goog.asserts.assert(urls.length > 0);
      break;
    default:
      goog.asserts.fail();
  }

  return {
    urls: urls,
    layer: layer,
    matrixSet: matrixSet,
    format: format,
    projection: projection,
    requestEncoding: requestEncoding,
    tileGrid: tileGrid,
    style: style,
    dimensions: dimensions
  };
};
<commit_msg>Remove unneeded FIXME<commit_after>goog.provide('ol.source.WMTS');
goog.provide('ol.source.WMTSRequestEncoding');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.math');
goog.require('goog.object');
goog.require('goog.uri.utils');
goog.require('ol.TileCoord');
goog.require('ol.TileUrlFunction');
goog.require('ol.TileUrlFunctionType');
goog.require('ol.extent');
goog.require('ol.proj');
goog.require('ol.source.ImageTileSource');
goog.require('ol.tilegrid.WMTS');

/**
 * @enum {string}
 */
ol.source.WMTSRequestEncoding = {
  KVP: 'KVP',  // see spec §8
  REST: 'REST' // see spec §10
};

/**
 * @constructor
 * @extends {ol.source.ImageTileSource}
 * @param {ol.source.WMTSOptions} options WMTS options.
 */
ol.source.WMTS = function(options) {

  // TODO: add support for TileMatrixLimits

  var version = goog.isDef(options.version) ? options.version : '1.0.0';
  var format = goog.isDef(options.format) ? options.format : 'image/jpeg';
  var dimensions = options.dimensions || {};

  // FIXME: should we guess this requestEncoding from options.url(s)
  //        structure? that would mean KVP only if a template is not provided.
  var requestEncoding = goog.isDef(options.requestEncoding) ?
      options.requestEncoding : ol.source.WMTSRequestEncoding.KVP;

  // FIXME: should we create a default tileGrid?
  // we could issue a getCapabilities xhr to retrieve missing configuration
  var tileGrid = options.tileGrid;

  var context = {
    'Layer': options.layer,
    'style': options.style,
    'Style': options.style,
    'TileMatrixSet': options.matrixSet
  };
  goog.object.extend(context, dimensions);
  var kvpParams;
  if (requestEncoding == ol.source.WMTSRequestEncoding.KVP) {
    kvpParams = {
      'Service': 'WMTS',
      'Request': 'GetTile',
      'Version': version,
      'Format': format,
      'TileMatrix': '{TileMatrix}',
      'TileRow': '{TileRow}',
      'TileCol': '{TileCol}'
    };
    goog.object.extend(kvpParams, context);
  }

  /**
   * @param {string} template Template.
   * @return {ol.TileUrlFunctionType} Tile URL function.
   */
  function createFromWMTSTemplate(template) {
    return (
        /**
         * @this {ol.source.WMTS}
         * @param {ol.TileCoord} tileCoord Tile coordinate.
         * @param {ol.Projection} projection Projection.
         * @return {string|undefined} Tile URL.
         */
        function(tileCoord, projection) {
          if (goog.isNull(tileCoord)) {
            return undefined;
          } else {
            var localContext = {
              'TileMatrix': tileGrid.getMatrixId(tileCoord.z),
              'TileCol': tileCoord.x,
              'TileRow': tileCoord.y
            };
            if (requestEncoding != ol.source.WMTSRequestEncoding.KVP) {
              goog.object.extend(localContext, context);
            }
            var url = template;
            for (var key in localContext) {
              url = url.replace('{' + key + '}', localContext[key])
                  .replace('%7B' + key + '%7D', localContext[key]);
            }
            return url;
          }
        });
  }

  var tileUrlFunction = ol.TileUrlFunction.nullTileUrlFunction;
  var urls = options.urls;
  if (!goog.isDef(urls) && goog.isDef(options.url)) {
    urls = ol.TileUrlFunction.expandUrl(options.url);
  }
  if (goog.isDef(urls)) {
    tileUrlFunction = ol.TileUrlFunction.createFromTileUrlFunctions(
        goog.array.map(urls, function(url) {
          if (goog.isDef(kvpParams)) {
            // TODO: we may want to create our own appendParams function
            // so that params order conforms to wmts spec guidance,
            // and so that we can avoid to escape special template params
            url = goog.uri.utils.appendParamsFromMap(url, kvpParams);
          }
          return createFromWMTSTemplate(url);
        }));
  }

  var tmpExtent = ol.extent.createEmpty();
  var tmpTileCoord = new ol.TileCoord(0, 0, 0);
  tileUrlFunction = ol.TileUrlFunction.withTileCoordTransform(
      /**
       * @param {ol.TileCoord} tileCoord Tile coordinate.
       * @param {ol.Projection} projection Projection.
       * @param {ol.TileCoord=} opt_tileCoord Tile coordinate.
       * @return {ol.TileCoord} Tile coordinate.
       */
      function(tileCoord, projection, opt_tileCoord) {
        var tileGrid = this.getTileGrid();
        goog.asserts.assert(!goog.isNull(tileGrid));
        if (tileGrid.getResolutions().length <= tileCoord.z) {
          return null;
        }
        var x = tileCoord.x;
        var y = -tileCoord.y - 1;
        var tileExtent = tileGrid.getTileCoordExtent(tileCoord);
        var projectionExtent = projection.getExtent();
        var extent = goog.isDef(options.extent) ?
            options.extent : projectionExtent;

        if (!goog.isNull(extent) && projection.isGlobal() &&
            extent[0] === projectionExtent[0] &&
            extent[1] === projectionExtent[1]) {
          var numCols = Math.ceil(
              (extent[1] - extent[0]) / (tileExtent[1] - tileExtent[0]));
          x = goog.math.modulo(x, numCols);
          tmpTileCoord.z = tileCoord.z;
          tmpTileCoord.x = x;
          tmpTileCoord.y = tileCoord.y;
          tileExtent = tileGrid.getTileCoordExtent(tmpTileCoord, tmpExtent);
        }
        if (!ol.extent.intersects(tileExtent, extent)) {
          return null;
        }
        return new ol.TileCoord(tileCoord.z, x, y);
      },
      tileUrlFunction);

  goog.base(this, {
    attributions: options.attributions,
    crossOrigin: options.crossOrigin,
    extent: options.extent,
    projection: options.projection,
    tileGrid: tileGrid,
    tileUrlFunction: tileUrlFunction
  });

};
goog.inherits(ol.source.WMTS, ol.source.ImageTileSource);

/**
 * @param {Object} wmtsCap An object representing the capabilities document.
 * @param {string} layer The layer identifier.
 * @return {ol.source.WMTSOptions} WMTS source options object.
 */
ol.source.WMTS.optionsFromCapabilities = function(wmtsCap, layer) {

  // TODO: add support for TileMatrixLimits

  var layers = wmtsCap['contents']['layers'];
  var l = goog.array.find(layers, function(elt, index, array) {
    return elt['identifier'] == layer;
  });
  goog.asserts.assert(!goog.isNull(l));
  goog.asserts.assert(l['tileMatrixSetLinks'].length > 0);
  var matrixSet = /** @type {string} */
      (l['tileMatrixSetLinks'][0]['tileMatrixSet']);
  var format = /** @type {string} */ (l['formats'][0]);
  var idx = goog.array.findIndex(l['styles'], function(elt, index, array) {
    return elt['isDefault'];
  });
  if (idx < 0) {
    idx = 0;
  }
  var style = /** @type {string} */ (l['styles'][idx]['identifier']);

  var dimensions = {};
  goog.array.forEach(l['dimensions'], function(elt, index, array) {
    var key = elt['identifier'];
    var value = elt['default'];
    if (goog.isDef(value)) {
      goog.asserts.assert(goog.array.indexOf(elt['values'], value) >= 0);
    } else {
      value = elt['values'][0];
    }
    goog.asserts.assert(goog.isDef(value));
    dimensions[key] = value;
  });

  var matrixSets = wmtsCap['contents']['tileMatrixSets'];
  goog.asserts.assert(matrixSet in matrixSets);
  var matrixSetObj = matrixSets[matrixSet];

  var tileGrid = ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet(
      matrixSetObj);

  var projection = ol.proj.get(matrixSetObj['supportedCRS']);

  var gets = wmtsCap['operationsMetadata']['GetTile']['dcp']['http']['get'];
  var encodings = goog.object.getKeys(
      gets[0]['constraints']['GetEncoding']['allowedValues']);
  goog.asserts.assert(encodings.length > 0);

  var urls;
  var requestEncoding;
  switch (encodings[0]) {
    case 'REST':
    case 'RESTful':
      // The OGC documentation is not clear if we should use REST or RESTful,
      // ArcGis use RESTful, and OpenLayers use REST.
      requestEncoding = ol.source.WMTSRequestEncoding.REST;
      goog.asserts.assert(l['resourceUrls'].hasOwnProperty('tile'));
      goog.asserts.assert(l['resourceUrls']['tile'].hasOwnProperty(format));
      urls = /** @type {Array.<string>} */
          (l['resourceUrls']['tile'][format]);
      break;
    case 'KVP':
      requestEncoding = ol.source.WMTSRequestEncoding.KVP;
      urls = [];
      goog.array.forEach(gets, function(elt, index, array) {
        if (elt['constraints']['GetEncoding']['allowedValues'].hasOwnProperty(
            ol.source.WMTSRequestEncoding.KVP)) {
          urls.push(/** @type {string} */ (elt['url']));
        }
      });
      goog.asserts.assert(urls.length > 0);
      break;
    default:
      goog.asserts.fail();
  }

  return {
    urls: urls,
    layer: layer,
    matrixSet: matrixSet,
    format: format,
    projection: projection,
    requestEncoding: requestEncoding,
    tileGrid: tileGrid,
    style: style,
    dimensions: dimensions
  };
};
<|endoftext|>


<commit_before>import { Timer } from './util';
import { EventEmitter } from 'events';

class Pipeline extends EventEmitter {
  constructor() {
    super();
    this.steps = [];
    this.results = {};
  }

  after(fn) {
    let name = 'execution';
    if (typeof fn === 'string') {
      name = fn;
      fn = arguments[1];
    }
    this.on(name + '-ended', fn);
  }

  afterStep(name, fn) {
    this.on('step-ended', (evName) => {
      if (name === evName) {
        fn(this.results[name].result, this.results[name].elapsed);
      }
    });
  }

  before(fn) {
    let name = 'execution';
    if (typeof fn === 'string') {
      name = fn;
      fn = arguments[1];
    }
    this.on(name + '-started', fn);
  }

  addStep(name, lambda) {
    this.steps.push([name, lambda]);
  }

  execute(jar) {
    this.emit('execution-started', jar);
    let elapsed = Timer.time(() => {
      this._runSteps(jar);
    });
    this.emit('execution-ended', elapsed);
  }

  stepResult(name) {
    return this.results[name].result;
  }

  _runSteps(jar) {
    for (let [name, lambda] of this.steps) {
      this.emit('step-started', name);
      let elapsed = this._runStep(jar, name, lambda);
      this.emit('step-ended', name, elapsed);
    }
  }

  _runStep(jar, name, lambda) {
    let result = null;
    let elapsed = Timer.time(() => {
      result = lambda(jar);
    });
    this.results[name] = {elapsed, result };
    return elapsed;
  }
}

export {
  Pipeline
};
<commit_msg>add named logging method to Pipeline<commit_after>import { Timer } from './util';
import { EventEmitter } from 'events';

class Pipeline extends EventEmitter {
  constructor(name) {
    super();
    this.name = name;
    this.steps = [];
    this.results = {};
  }

  after(fn) {
    let name = 'execution';
    if (typeof fn === 'string') {
      name = fn;
      fn = arguments[1];
    }
    this.on(name + '-ended', fn);
  }

  afterStep(name, fn) {
    this.on('step-ended', (evName) => {
      if (name === evName) {
        fn(this.results[name].result, this.results[name].elapsed);
      }
    });
  }

  before(fn) {
    let name = 'execution';
    if (typeof fn === 'string') {
      name = fn;
      fn = arguments[1];
    }
    this.on(name + '-started', fn);
  }

  addStep(name, lambda) {
    this.steps.push([name, lambda]);
  }

  execute(jar) {
    this.emit('execution-started', jar);
    let elapsed = Timer.time(() => {
      this._runSteps(jar);
    });
    this.emit('execution-ended', elapsed);
  }

  log() {
    let args = [...arguments];
    args[0] = '[' + this.name + '] ' + args[0];
    console.log.apply(console, args);
  }

  stepResult(name) {
    return this.results[name].result;
  }

  _runSteps(jar) {
    for (let [name, lambda] of this.steps) {
      this.emit('step-started', name);
      let elapsed = this._runStep(jar, name, lambda);
      this.emit('step-ended', name, elapsed);
    }
  }

  _runStep(jar, name, lambda) {
    let result = null;
    let elapsed = Timer.time(() => {
      result = lambda(jar);
    });
    this.results[name] = {elapsed, result };
    return elapsed;
  }
}

export {
  Pipeline
};
<|endoftext|>


<commit_before>$.register({
  rule: [
    {
      host: [
        /^(www\.)?sylnk\.net$/,
        /^dlneko\.(com|net)$/,
      ],
      query: /link=([^&]+)/,
    },
    {
      host: /^(www\.)?compul\.in$/,
      path: /^\/n\.php$/,
      query: /v=([^&]+)/,
    },
    {
      host: /^(www\.)?safelinkair\.com$/,
      path: /^\/code$/,
      query: /(?:\?|&)link=([a-zA-Z0-9=]+)(?:$|&)/,
    },
  ],
  start: function (m) {
    'use strict';
    var rawLink = atob(m.query[1]);

    $.openLink(rawLink);
  },
});

$.register({
  rule: [
    {
      host: /^(www\.)?(link\.)?safelink(converter2?|s?review)\.com$/,
      query: /id=(\w+=*)/,
    },
    {
      host: [
        /^(www\.)?dlneko\.com$/,
        /^(satuasia|tawaku)\.com$/,
        /^ww3\.manteb\.in$/,
      ],
      query: /go=(\w+=*)/,
    },
  ],
  start: function (m) {
    'use strict';

    var l = atob(m.query[1]);
    var table = {
      '!': 'a',
      ')': 'e',
      '_': 'i',
      '(': 'o',
      '*': 'u',
    };
    l = l.replace(/[!)_(*]/g, function (m) {
      return table[m];
    });
    $.openLink(l);
  },
});

$.register({
  rule: {
    host: /^(www\.)?safelinkreview\.com$/,
    path: /^\/\w+\/cost\/([\w\.]+)\/?$/,
  },
  start: function (m) {
    'use strict';

    var l = 'http://' + m.path[1];
    $.openLink(l);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>link.filmku.net<commit_after>$.register({
  rule: [
    {
      host: [
        /^(www\.)?sylnk\.net$/,
        /^dlneko\.(com|net)$/,
      ],
      query: /link=([^&]+)/,
    },
    {
      host: /^(www\.)?compul\.in$/,
      path: /^\/n\.php$/,
      query: /v=([^&]+)/,
    },
    {
      host: /^(www\.)?safelinkair\.com$/,
      path: /^\/code$/,
      query: /(?:\?|&)link=([a-zA-Z0-9=]+)(?:$|&)/,
    },
    {
      host: /^link\.filmku\.net$/,
      path: /^\/p\/go\.html$/,
      query: /^\?url=([a-zA-Z0-9=]+)$/,
    },
  ],
  start: function (m) {
    'use strict';
    var rawLink = atob(m.query[1]);

    $.openLink(rawLink);
  },
});

$.register({
  rule: [
    {
      host: /^(www\.)?(link\.)?safelink(converter2?|s?review)\.com$/,
      query: /id=(\w+=*)/,
    },
    {
      host: [
        /^(www\.)?dlneko\.com$/,
        /^(satuasia|tawaku)\.com$/,
        /^ww3\.manteb\.in$/,
      ],
      query: /go=(\w+=*)/,
    },
  ],
  start: function (m) {
    'use strict';

    var l = atob(m.query[1]);
    var table = {
      '!': 'a',
      ')': 'e',
      '_': 'i',
      '(': 'o',
      '*': 'u',
    };
    l = l.replace(/[!)_(*]/g, function (m) {
      return table[m];
    });
    $.openLink(l);
  },
});

$.register({
  rule: {
    host: /^(www\.)?safelinkreview\.com$/,
    path: /^\/\w+\/cost\/([\w\.]+)\/?$/,
  },
  start: function (m) {
    'use strict';

    var l = 'http://' + m.path[1];
    $.openLink(l);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>define(['angular'], function(angular) {
  'use strict';

  angular.module('stream', [])
    .factory('Stream', ['$window', function(window){
      if (window.streams === undefined) {
        window.streams = {};
      }

      return function($scope, url, callback) {
        if (window.streams[url]) {
          console.log('[Stream] Closing connection to ' + url);
          window.streams[url].close();
        }
        console.log('[Stream] Initiating connection to ' + url);

        window.streams[url] = new EventSource(url + '?_=' + new Date().getTime());
        window.streams[url].onopen = function(e) {
          console.log('[Stream] Connection opened to ' + url);
        };

        $scope.$on("$destroy", function() {
          if (!window.streams[url]) {
            return;
          }
          console.log('[Stream] Closing connection to ' + url);
          window.streams[url].close();
          delete window.streams[url];
        });

        return {
          subscribe: function(event, callback){
            window.streams[url].addEventListener(event, function(e) {
              var data = $.parseJSON(e.data);
              console.log('[Stream] Got event for ' + event);
              callback(data);
            }, false);
          }
        };
      };
    }]);
});
<commit_msg>Use log provider<commit_after>define(['angular'], function(angular) {
  'use strict';

  angular.module('stream', [])
    .factory('Stream', function($window, $log){
      if ($window.streams === undefined) {
        $window.streams = {};
      }

      return function($scope, url, callback) {
        if ($window.streams[url]) {
          $log.info('[Stream] Closing connection to ' + url);
          window.streams[url].close();
        }
        $log.info('[Stream] Initiating connection to ' + url);

        $window.streams[url] = new EventSource(url + '?_=' + new Date().getTime());
        $window.streams[url].onopen = function(e) {
          $log.info('[Stream] Connection opened to ' + url);
        };

        $scope.$on("$destroy", function() {
          if (!$window.streams[url]) {
            return;
          }
          $log.info('[Stream] Closing connection to ' + url);
          $window.streams[url].close();
          delete window.streams[url];
        });

        return {
          subscribe: function(event, callback){
            $window.streams[url].addEventListener(event, function(e) {
              var data = $.parseJSON(e.data);
              $log.info('[Stream] Got event for ' + event);
              callback(data);
            }, false);
          }
        };
      };
    });
});
<|endoftext|>