<commit_before>'use strict';

var app = angular.module('myApp.logs.directives', []);

app.directive('logging', ['Logs', 'Location', 'Box', '$routeParams', 'gettextCatalog', 'pagination_labels', '$pusher', '$rootScope', '$location', '$mdDialog', 'showToast', function(Logs, Location, Box, $routeParams, gettextCatalog, pagination_labels, $pusher, $rootScope, $location, $mdDialog, showToast) {

  var link = function(scope,element,attrs,controller) {

    scope.loading  = true;
    var ap_mac = $routeParams.ap_mac;

    scope.pagination_labels = pagination_labels;
    scope.query = {
      // order:   '-timestamp',
      query:   $routeParams.q,
      ap_mac:  $routeParams.ap_mac,
      limit:   $routeParams.per || 25,
      page:    $routeParams.page || 1,
      options: [5,10,25,50,100],
    };

    $routeParams.start || $routeParams.end ? scope.date_range = true : scope.date_range = false;

    var ap_descriptions = {};
    var ap_slugs = {};
    var location;

    var fetchBoxes = function() {
      Box.get({location_id: $routeParams.id}).$promise.then(function(results) {
        for (var i = 0, len = results.boxes.length; i < len; i++) {
          ap_descriptions[results.boxes[i].calledstationid] = results.boxes[i].description;
          ap_slugs[results.boxes[i].calledstationid] = results.boxes[i].slug;
        }
      });
    };

    var setApAttributes = function() {
      for (var i = 0, len = scope.logs.length; i < len; i++) {
        scope.logs[i].ap_name = ap_descriptions[scope.logs[i].ap_mac];
        scope.logs[i].ap_slug = ap_slugs[scope.logs[i].ap_mac];
      }
    };

    // scope.onPaginate = function (page, limit) {
    //   scope.query.page = page;
    //   scope.query.limit = limit;
    //   updatePage();
    // };

    scope.expandRow = function(log) {
      if (log.show_detail && log.show_detail === true) {
        log.show_detail = false;
      } else {
        log.show_detail = true;
      }
    };

    scope.updatePage = function(page) {
      var hash  = {};
      hash.start  = scope.start;
      hash.end    = scope.end;
      // hash.page  = scope.query.page;
      hash.per    = scope.query.limit;
      hash.q      = scope.query.query;
      hash.ap_mac = scope.query.ap_mac;
      $location.search(hash);
    };

    var start_time;
    var end_time;

    if ($routeParams.start && $routeParams.end && $routeParams.end - $routeParams.start <= 3600) {
      start_time = $routeParams.start;
      end_time = $routeParams.end;
    } else {
      if ($routeParams.end - $routeParams.start > 3600) {
        showToast(gettextCatalog.getString('Period should not be longer than an hour'));
      } else if ($routeParams.start || $routeParams.end) {
        showToast(gettextCatalog.getString('Selected range period not valid'));
      }
      start_time = Math.round((new Date().getTime() - 60*60*1000) / 1000);
      end_time = Math.round((new Date().getTime()) / 1000);
    }

    function rangeCtrl($scope, startFull, endFull) {
      $scope.startFull = startFull;
      $scope.endFull = endFull;
      $scope.page = 'show';
      $scope.saveRange = function() {
        if ($scope.startFull && $scope.endFull) {
          // converting the moment picker time format - this could really do with some work:
          var startTimestamp = Math.floor(moment($scope.startFull).utc().toDate().getTime() / 1000);
          var endTimestamp = Math.floor(moment($scope.endFull).utc().toDate().getTime() / 1000);
          if (startTimestamp > endTimestamp) {
            showToast(gettextCatalog.getString('Selected range period not valid'));
          } else if ((endTimestamp - startTimestamp) < 300 || (endTimestamp - startTimestamp) > 3600) {
            // check that the selected range period is between five minutes and thirty days
            showToast(gettextCatalog.getString('Range period should be between five minutes and one hour'));
          } else {
            scope.start = startTimestamp;
            scope.end = endTimestamp;
            scope.date_range = true;
            scope.updatePage();
            $mdDialog.cancel();
          }
        }
      };

      $scope.close = function() {
        $mdDialog.cancel();
      };
    }

    scope.openMomentRange = function() {
      if ($routeParams.start && $routeParams.end) {
        scope.startFull = moment($routeParams.start * 1000).format('MM/DD/YYYY h:mm A');
        scope.endFull = moment($routeParams.end * 1000).format('MM/DD/YYYY h:mm A');
      }
      $mdDialog.show({
        templateUrl: 'components/locations/clients/_client_date_range.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        locals: {
          startFull: scope.startFull,
          endFull:   scope.endFull
        },
        controller: rangeCtrl
      });
    };

    scope.clearRangeFilter = function() {
      scope.start = undefined;
      scope.end = undefined;
      scope.date_range = false;
      scope.updatePage();
    };

    scope.clearQueryFilter = function() {
      scope.query.query = undefined;
      scope.updatePage();
    };

    scope.filterByMac = function(mac) {
      scope.query.ap_mac = mac;
      scope.updatePage();
    };

    scope.clearAPFilter = function() {
      scope.query.ap_mac = undefined;
      scope.updatePage();
    };

    scope.clearAllFilters = function() {
      scope.query.ap_mac = undefined;
      scope.query.query = undefined;
      scope.start = undefined;
      scope.end = undefined;
      scope.date_range = false;
      scope.updatePage();
    };

    var getLogs = function() {
      Logs.query({
        location_id: scope.location.id,
        ap_mac: ap_mac,
        // page: scope.query.page,
        per: scope.query.limit,
        start_time: start_time,
        end_time: end_time,
        q: scope.query.query
      }).$promise.then(function(res) {
        scope.logs = res.data;
        setApAttributes();
        // scope._links = res._links;
        scope.loading = undefined;
      }, function() {
        scope.loading = undefined;
      });
    };

    var init = function() {
      Location.get({id: $routeParams.id}, function(data) {
        scope.location = data;
        fetchBoxes();
        getLogs();
      }, function(err){
        console.log(err);
      });
    };

    init();
  };

  return {
    link: link,
    scope: {
      loading: '='
    },
    templateUrl: 'components/locations/logging/_index.html'
  };

}]);

<commit_msg>onpaginate<commit_after>'use strict';

var app = angular.module('myApp.logs.directives', []);

app.directive('logging', ['Logs', 'Location', 'Box', '$routeParams', 'gettextCatalog', 'pagination_labels', '$pusher', '$rootScope', '$location', '$mdDialog', 'showToast', function(Logs, Location, Box, $routeParams, gettextCatalog, pagination_labels, $pusher, $rootScope, $location, $mdDialog, showToast) {

  var link = function(scope,element,attrs,controller) {

    scope.loading  = true;
    var ap_mac = $routeParams.ap_mac;

    scope.pagination_labels = pagination_labels;
    scope.query = {
      // order:   '-timestamp',
      query:   $routeParams.q,
      ap_mac:  $routeParams.ap_mac,
      limit:   $routeParams.per || 25,
      page:    $routeParams.page || 1,
      options: [5,10,25,50,100],
    };

    $routeParams.start || $routeParams.end ? scope.date_range = true : scope.date_range = false;

    var ap_descriptions = {};
    var ap_slugs = {};
    var location;

    var fetchBoxes = function() {
      Box.get({location_id: $routeParams.id}).$promise.then(function(results) {
        for (var i = 0, len = results.boxes.length; i < len; i++) {
          ap_descriptions[results.boxes[i].calledstationid] = results.boxes[i].description;
          ap_slugs[results.boxes[i].calledstationid] = results.boxes[i].slug;
        }
      });
    };

    var setApAttributes = function() {
      for (var i = 0, len = scope.logs.length; i < len; i++) {
        scope.logs[i].ap_name = ap_descriptions[scope.logs[i].ap_mac];
        scope.logs[i].ap_slug = ap_slugs[scope.logs[i].ap_mac];
      }
    };

    // scope.onPaginate = function (page, limit) {
    //   scope.query.page = page;
    //   scope.query.limit = limit;
    //   updatePage();
    // };

    scope.expandRow = function(log) {
      if (log.show_detail && log.show_detail === true) {
        log.show_detail = false;
      } else {
        log.show_detail = true;
      }
    };

    scope.updatePage = function(page) {
      var hash  = {};
      hash.start  = scope.start;
      hash.end    = scope.end;
      hash.page  = scope.query.page;
      hash.per    = scope.query.limit;
      hash.q      = scope.query.query;
      hash.ap_mac = scope.query.ap_mac;
      $location.search(hash);
    };

    var start_time;
    var end_time;

    if ($routeParams.start && $routeParams.end && $routeParams.end - $routeParams.start <= 3600) {
      start_time = $routeParams.start;
      end_time = $routeParams.end;
    } else {
      if ($routeParams.end - $routeParams.start > 3600) {
        showToast(gettextCatalog.getString('Period should not be longer than an hour'));
      } else if ($routeParams.start || $routeParams.end) {
        showToast(gettextCatalog.getString('Selected range period not valid'));
      }
      start_time = Math.round((new Date().getTime() - 60*60*1000) / 1000);
      end_time = Math.round((new Date().getTime()) / 1000);
    }

    function rangeCtrl($scope, startFull, endFull) {
      $scope.startFull = startFull;
      $scope.endFull = endFull;
      $scope.page = 'show';
      $scope.saveRange = function() {
        if ($scope.startFull && $scope.endFull) {
          // converting the moment picker time format - this could really do with some work:
          var startTimestamp = Math.floor(moment($scope.startFull).utc().toDate().getTime() / 1000);
          var endTimestamp = Math.floor(moment($scope.endFull).utc().toDate().getTime() / 1000);
          if (startTimestamp > endTimestamp) {
            showToast(gettextCatalog.getString('Selected range period not valid'));
          } else if ((endTimestamp - startTimestamp) < 300 || (endTimestamp - startTimestamp) > 3600) {
            // check that the selected range period is between five minutes and thirty days
            showToast(gettextCatalog.getString('Range period should be between five minutes and one hour'));
          } else {
            scope.start = startTimestamp;
            scope.end = endTimestamp;
            scope.date_range = true;
            scope.updatePage();
            $mdDialog.cancel();
          }
        }
      };

      $scope.close = function() {
        $mdDialog.cancel();
      };
    }

    scope.openMomentRange = function() {
      if ($routeParams.start && $routeParams.end) {
        scope.startFull = moment($routeParams.start * 1000).format('MM/DD/YYYY h:mm A');
        scope.endFull = moment($routeParams.end * 1000).format('MM/DD/YYYY h:mm A');
      }
      $mdDialog.show({
        templateUrl: 'components/locations/clients/_client_date_range.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        locals: {
          startFull: scope.startFull,
          endFull:   scope.endFull
        },
        controller: rangeCtrl
      });
    };

    scope.clearRangeFilter = function() {
      scope.start = undefined;
      scope.end = undefined;
      scope.date_range = false;
      scope.updatePage();
    };

    scope.clearQueryFilter = function() {
      scope.query.query = undefined;
      scope.updatePage();
    };

    scope.filterByMac = function(mac) {
      scope.query.ap_mac = mac;
      scope.updatePage();
    };

    scope.clearAPFilter = function() {
      scope.query.ap_mac = undefined;
      scope.updatePage();
    };

    scope.clearAllFilters = function() {
      scope.query.ap_mac = undefined;
      scope.query.query = undefined;
      scope.start = undefined;
      scope.end = undefined;
      scope.date_range = false;
      scope.updatePage();
    };

    scope.onPaginate = function (page, limit) {
      scope.query.page = page;
      scope.query.limit = limit;
      scope.updatePage();
    };

    var getLogs = function() {
      Logs.query({
        location_id: scope.location.id,
        ap_mac: ap_mac,
        page: scope.query.page,
        per: scope.query.limit,
        start_time: start_time,
        end_time: end_time,
        q: scope.query.query
      }).$promise.then(function(res) {
        scope.logs = res.data;
        setApAttributes();
        // scope._links = res._links;
        scope.loading = undefined;
      }, function() {
        scope.loading = undefined;
      });
    };

    var init = function() {
      Location.get({id: $routeParams.id}, function(data) {
        scope.location = data;
        fetchBoxes();
        getLogs();
      }, function(err){
        console.log(err);
      });
    };

    init();
  };

  return {
    link: link,
    scope: {
      loading: '='
    },
    templateUrl: 'components/locations/logging/_index.html'
  };

}]);

<|endoftext|>


<commit_before>/* jshint camelcase:false */
var osx = 'OS X 10.10';
var windows = 'Windows 8.1';
var browsers = [{
    browserName: 'safari',
    platform: osx
}, {
    browserName: 'firefox',
    platform: windows
}, {
    browserName: 'chrome',
    platform: windows
}, {
    browserName: 'microsoftedge',
    platform: 'Windows 10'
}, {
    browserName: 'internet explorer',
    platform: windows,
    version: '11'
}, {
    browserName: 'internet explorer',
    platform: 'Windows 8',
    version: '10'
}, {
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '9'
}];

module.exports = function (grunt) {
    require('load-grunt-tasks')(grunt);

    var otherFiles = [
        'src/app/**/*.html',
        'src/app/**/*.css',
        'src/index.html',
        'src/ChangeLog.html'
    ];
    var jsFiles = [
        'src/app/**/*.js',
        'profiles/*.js',
        'GruntFile.js'
    ];
    var bumpFiles = [
        'package.json',
        'bower.json',
        'src/app/package.json',
        'src/app/config.js'
    ];
    var deployFiles = [
        '**',
        '!**/*.uncompressed.js',
        '!**/*consoleStripped.js',
        '!**/bootstrap/less/**',
        '!**/bootstrap/test-infra/**',
        '!**/tests/**',
        '!build-report.txt',
        '!components-jasmine/**',
        '!favico.js/**',
        '!jasmine-favicon-reporter/**',
        '!jasmine-jsreporter/**',
        '!stubmodule/**',
        '!util/**'
    ];
    var deployDir = 'SGID';
    var secrets;
    var sauceConfig = {
        urls: ['http://127.0.0.1:8000/_SpecRunner.html?catch=false'],
        tunnelTimeout: 120,
        build: process.env.TRAVIS_JOB_ID,
        browsers: browsers,
        testname: 'atlas',
        maxRetries: 10,
        maxPollRetries: 10,
        'public': 'public',
        throttled: 5,
        sauceConfig: {
            'max-duration': 1800
        },
        statusCheckAttempts: 500
    };
    try {
        secrets = grunt.file.readJSON('secrets.json');
        sauceConfig.username = secrets.sauce_name;
        sauceConfig.key = secrets.sauce_key;
    } catch (e) {
        // swallow for build server
        secrets = {
            stage: {
                host: '',
                username: '',
                password: ''
            },
            prod: {
                host: '',
                username: '',
                password: ''
            }
        };
    }

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        bump: {
            options: {
                files: bumpFiles,
                commitFiles: bumpFiles,
                push: false
            }
        },
        clean: {
            build: ['dist'],
            deploy: ['deploy']
        },
        compress: {
            main: {
                options: {
                    archive: 'deploy/deploy.zip'
                },
                files: [{
                    src: deployFiles,
                    dest: './',
                    cwd: 'dist/',
                    expand: true
                }]
            }
        },
        connect: {
            uses_defaults: {}
        },
        copy: {
            main: {
                files: [{expand: true, cwd: 'src/', src: ['*.html'], dest: 'dist/'}]
            }
        },
        dojo: {
            prod: {
                options: {
                    // You can also specify options to be used in all your tasks
                    profiles: ['profiles/prod.build.profile.js', 'profiles/build.profile.js'] // Profile for build
                }
            },
            stage: {
                options: {
                    // You can also specify options to be used in all your tasks
                    profiles: ['profiles/stage.build.profile.js', 'profiles/build.profile.js'] // Profile for build
                }
            },
            options: {
                // You can also specify options to be used in all your tasks
                dojo: 'src/dojo/dojo.js', // Path to dojo.js file in dojo source
                load: 'build', // Optional: Utility to bootstrap (Default: 'build')
                releaseDir: '../dist',
                requires: ['src/app/packages.js', 'src/app/run.js'], // Optional: Module to require for the build (Default: nothing)
                basePath: './src'
            }
        },
        eslint: {
            options: {
                configFile: '.eslintrc'
            },
            main: {
                src: jsFiles
            }
        },
        imagemin: {
            main: {
                options: {
                    optimizationLevel: 3
                },
                files: [{
                    expand: true,
                    cwd: 'src/',
                    // exclude tests because some images in dojox throw errors
                    src: ['**/*.{png,jpg,gif}', '!**/tests/**/*.*'],
                    dest: 'src/'
                }]
            }
        },
        jasmine: {
            main: {
                options: {
                    specs: ['src/app/**/Spec*.js'],
                    vendor: [
                        'src/jasmine-favicon-reporter/vendor/favico.js',
                        'src/jasmine-favicon-reporter/jasmine-favicon-reporter.js',
                        'src/jasmine-jsreporter/jasmine-jsreporter.js',
                        'src/app/tests/jasmineTestBootstrap.js',
                        'src/dojo/dojo.js',
                        'src/app/packages.js',
                        'src/app/tests/jsReporterSanitizer.js',
                        'src/app/tests/jasmineAMDErrorChecking.js'
                    ],
                    host: 'http://localhost:8000'
                }
            }
        },
        processhtml: {
            options: {},
            main: {
                files: {
                    'dist/index.html': ['src/index.html'],
                    'dist/user_admin.html': ['src/user_admin.html']
                }
            }
        },
        'saucelabs-jasmine': {
            all: {
                options: sauceConfig
            }
        },
        secrets: secrets,
        sftp: {
            stage: {
                files: {
                    './': 'deploy/deploy.zip'
                },
                options: {
                    host: '<%= secrets.stage.host %>',
                    username: '<%= secrets.stage.username %>',
                    password: '<%= secrets.stage.password %>'
                }
            },
            prod: {
                files: {
                    './': 'deploy/deploy.zip'
                },
                options: {
                    host: '<%= secrets.prod.host %>',
                    username: '<%= secrets.prod.username %>',
                    password: '<%= secrets.prod.password %>',
                    path: './upload/' + deployDir
                }
            },
            options: {
                createDirectories: true,
                path: './wwwroot' + deployDir + '/',
                srcBasePath: 'deploy/',
                showProgress: true
            }
        },
        sshexec: {
            options: {

            },
            stage: {
                command: ['cd wwwroot/' + deployDir, 'unzip -oq deploy.zip', 'rm deploy.zip'].join(';'),
                options: {
                    host: '<%= secrets.stage.host %>',
                    username: '<%= secrets.stage.username %>',
                    password: '<%= secrets.stage.password %>'
                }
            },
            prod: {
                command: ['cd wwwroot/' + deployDir, 'unzip -oq deploy.zip', 'rm deploy.zip'].join(';'),
                options: {
                    host: '<%= secrets.prod.host %>',
                    username: '<%= secrets.prod.username %>',
                    password: '<%= secrets.prod.password %>'
                }
            }
        },
        stylus: {
            main: {
                options: {
                    compress: false
                },
                files: [{
                    expand: true,
                    cwd: 'src/',
                    src: ['app/**/*.styl'],
                    dest: 'src/',
                    ext: '.css'
                }]
            }
        },
        watch: {
            eslint: {
                files: jsFiles,
                tasks: ['newer:eslint:main', 'jasmine:main:build']
            },
            src: {
                files: jsFiles.concat(otherFiles),
                options: { livereload: true }
            },
            stylus: {
                files: 'src/app/**/*.styl',
                tasks: ['newer:stylus']
            }
        }
    });

    grunt.registerTask('default', [
        'jasmine:main:build',
        'eslint:main',
        'connect',
        'stylus',
        'watch'
    ]);
    grunt.registerTask('build-prod', [
        'eslint:main',
        'clean:build',
        'newer:imagemin:main',
        'stylus',
        'dojo:prod',
        'copy:main',
        'processhtml:main'
    ]);
    grunt.registerTask('deploy-prod', [
        'clean:deploy',
        'compress:main',
        'sftp:prod'
    ]);
    grunt.registerTask('build-stage', [
        'eslint:main',
        'clean:build',
        'newer:imagemin:main',
        'stylus',
        'dojo:stage',
        'copy:main',
        'processhtml:main'
    ]);
    grunt.registerTask('deploy-stage', [
        'clean:deploy',
        'compress:main',
        'sftp:stage',
        'sshexec:stage'
    ]);
    grunt.registerTask('sauce', [
        'jasmine:main:build',
        'connect',
        'saucelabs-jasmine'
    ]);
    grunt.registerTask('travis', [
        'eslint:main',
        'sauce',
        'build-prod'
    ]);
};
<commit_msg>whats up with live reload?<commit_after>/* jshint camelcase:false */
var osx = 'OS X 10.10';
var windows = 'Windows 8.1';
var browsers = [{
    browserName: 'safari',
    platform: osx
}, {
    browserName: 'firefox',
    platform: windows
}, {
    browserName: 'chrome',
    platform: windows
}, {
    browserName: 'microsoftedge',
    platform: 'Windows 10'
}, {
    browserName: 'internet explorer',
    platform: windows,
    version: '11'
}, {
    browserName: 'internet explorer',
    platform: 'Windows 8',
    version: '10'
}, {
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '9'
}];

module.exports = function (grunt) {
    require('load-grunt-tasks')(grunt);

    var otherFiles = [
        'src/app/**/*.html',
        'src/app/**/*.css',
        'src/index.html',
        'src/ChangeLog.html'
    ];
    var jsFiles = [
        'src/app/**/*.js',
        'profiles/*.js',
        'GruntFile.js'
    ];
    var bumpFiles = [
        'package.json',
        'bower.json',
        'src/app/package.json',
        'src/app/config.js'
    ];
    var deployFiles = [
        '**',
        '!**/*.uncompressed.js',
        '!**/*consoleStripped.js',
        '!**/bootstrap/less/**',
        '!**/bootstrap/test-infra/**',
        '!**/tests/**',
        '!build-report.txt',
        '!components-jasmine/**',
        '!favico.js/**',
        '!jasmine-favicon-reporter/**',
        '!jasmine-jsreporter/**',
        '!stubmodule/**',
        '!util/**'
    ];
    var deployDir = 'Parels';
    var secrets;
    var sauceConfig = {
        urls: ['http://127.0.0.1:8000/_SpecRunner.html'],
        tunnelTimeout: 120,
        build: process.env.TRAVIS_JOB_ID,
        browsers: browsers,
        testname: 'parcels',
        maxRetries: 10,
        maxPollRetries: 10,
        'public': 'public',
        throttled: 5,
        sauceConfig: {
            'max-duration': 1800
        },
        statusCheckAttempts: 500
    };
    try {
        secrets = grunt.file.readJSON('secrets.json');
        sauceConfig.username = secrets.sauce_name;
        sauceConfig.key = secrets.sauce_key;
    } catch (e) {
        // swallow for build server
        secrets = {
            stage: {
                host: '',
                username: '',
                password: ''
            },
            prod: {
                host: '',
                username: '',
                password: ''
            }
        };
    }

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        bump: {
            options: {
                files: bumpFiles,
                commitFiles: bumpFiles,
                push: false
            }
        },
        clean: {
            build: ['dist'],
            deploy: ['deploy']
        },
        compress: {
            main: {
                options: {
                    archive: 'deploy/deploy.zip'
                },
                files: [{
                    src: deployFiles,
                    dest: './',
                    cwd: 'dist/',
                    expand: true
                }]
            }
        },
        connect: {
            options: {
                livereload: true,
                base: '.',
                logger: 'dev',
                middleware: function (connect, options, defaultMiddleware) {
                    var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
                    return [proxy].concat(defaultMiddleware);
                },
                proxies: [
                    {
                        context: '/arcgis',
                        host: 'localhost'
                    }
                ]
            },
            app: {
                options: {
                    port: 8000,
                    base: {
                        path: './src'
                    }
                }
            },
            jasmine: {
                options: {
                    port: 8001,
                    base: {
                        path: '.',
                        options: {
                            index: '_SpecRunner.html'
                        }
                    }
                }
            },
            openApp: {
                options: {
                    open: true,
                    port: 8000,
                    base: {
                        path: './src'
                    }
                }
            },
            openJasmine: {
                options: {
                    open: true,
                    port: 8001,
                    base: {
                        path: '.',
                        options: {
                            index: '_SpecRunner.html'
                        }
                    }
                }
            }
        },
        copy: {
            main: {
                files: [{expand: true, cwd: 'src/', src: ['*.html'], dest: 'dist/'}]
            }
        },
        dojo: {
            prod: {
                options: {
                    // You can also specify options to be used in all your tasks
                    profiles: ['profiles/prod.build.profile.js', 'profiles/build.profile.js'] // Profile for build
                }
            },
            stage: {
                options: {
                    // You can also specify options to be used in all your tasks
                    profiles: ['profiles/stage.build.profile.js', 'profiles/build.profile.js'] // Profile for build
                }
            },
            options: {
                // You can also specify options to be used in all your tasks
                dojo: 'src/dojo/dojo.js', // Path to dojo.js file in dojo source
                load: 'build', // Optional: Utility to bootstrap (Default: 'build')
                releaseDir: '../dist',
                requires: ['src/app/packages.js', 'src/app/run.js'], // Optional: Module to require for the build (Default: nothing)
                basePath: './src'
            }
        },
        eslint: {
            options: {
                configFile: '.eslintrc'
            },
            main: {
                src: jsFiles
            }
        },
        imagemin: {
            main: {
                options: {
                    optimizationLevel: 3
                },
                files: [{
                    expand: true,
                    cwd: 'src/',
                    // exclude tests because some images in dojox throw errors
                    src: ['**/*.{png,jpg,gif}', '!**/tests/**/*.*'],
                    dest: 'src/'
                }]
            }
        },
        jasmine: {
            main: {
                options: {
                    specs: ['src/app/**/Spec*.js'],
                    vendor: [
                        'src/jasmine-favicon-reporter/vendor/favico.js',
                        'src/jasmine-favicon-reporter/jasmine-favicon-reporter.js',
                        'src/jasmine-jsreporter/jasmine-jsreporter.js',
                        'src/app/tests/jasmineTestBootstrap.js',
                        'src/dojo/dojo.js',
                        'src/app/packages.js',
                        'src/app/tests/jsReporterSanitizer.js',
                        'src/app/tests/jasmineAMDErrorChecking.js'
                    ],
                    host: 'http://localhost:8001'
                }
            }
        },
        processhtml: {
            options: {},
            main: {
                files: {
                    'dist/index.html': ['src/index.html'],
                    'dist/user_admin.html': ['src/user_admin.html']
                }
            }
        },
        'saucelabs-jasmine': {
            all: {
                options: sauceConfig
            }
        },
        secrets: secrets,
        sftp: {
            stage: {
                files: {
                    './': 'deploy/deploy.zip'
                },
                options: {
                    host: '<%= secrets.stage.host %>',
                    username: '<%= secrets.stage.username %>',
                    password: '<%= secrets.stage.password %>'
                }
            },
            prod: {
                files: {
                    './': 'deploy/deploy.zip'
                },
                options: {
                    host: '<%= secrets.prod.host %>',
                    username: '<%= secrets.prod.username %>',
                    password: '<%= secrets.prod.password %>',
                    path: './upload/' + deployDir
                }
            },
            options: {
                createDirectories: true,
                path: './wwwroot' + deployDir + '/',
                srcBasePath: 'deploy/',
                showProgress: true
            }
        },
        sshexec: {
            options: {

            },
            stage: {
                command: ['cd wwwroot/' + deployDir, 'unzip -oq deploy.zip', 'rm deploy.zip'].join(';'),
                options: {
                    host: '<%= secrets.stage.host %>',
                    username: '<%= secrets.stage.username %>',
                    password: '<%= secrets.stage.password %>'
                }
            },
            prod: {
                command: ['cd wwwroot/' + deployDir, 'unzip -oq deploy.zip', 'rm deploy.zip'].join(';'),
                options: {
                    host: '<%= secrets.prod.host %>',
                    username: '<%= secrets.prod.username %>',
                    password: '<%= secrets.prod.password %>'
                }
            }
        },
        stylus: {
            main: {
                options: {
                    compress: false
                },
                files: [{
                    expand: true,
                    cwd: 'src/',
                    src: ['app/**/*.styl'],
                    dest: 'src/',
                    ext: '.css'
                }]
            }
        },
        watch: {
            options: {
                livereload: true
            },
            eslint: {
                files: jsFiles,
                tasks: ['newer:eslint:main', 'jasmine:main:build']
            },
            src: {
                files: jsFiles.concat(otherFiles),
                options: {
                    livereload: true
                }
            },
            stylus: {
                files: 'src/app/**/*.styl',
                tasks: ['stylus']
            }
        }
    });

    grunt.registerTask('default', [
        'jasmine:main:build',
        'eslint:main',
        'connect:app',
        'connect:jasmine',
        'stylus',
        'watch'
    ]);
    grunt.registerTask('launch', [
        'jasmine:main:build',
        'eslint:main',
        'connect:openApp',
        'connect:openJasmine',
        'stylus',
        'watch'
    ]);
    grunt.registerTask('build-prod', [
        'eslint:main',
        'clean:build',
        'newer:imagemin:main',
        'stylus',
        'dojo:prod',
        'copy:main',
        'processhtml:main'
    ]);
    grunt.registerTask('deploy-prod', [
        'clean:deploy',
        'compress:main',
        'sftp:prod'
    ]);
    grunt.registerTask('build-stage', [
        'eslint:main',
        'clean:build',
        'newer:imagemin:main',
        'stylus',
        'dojo:stage',
        'copy:main',
        'processhtml:main'
    ]);
    grunt.registerTask('deploy-stage', [
        'clean:deploy',
        'compress:main',
        'sftp:stage',
        'sshexec:stage'
    ]);
    grunt.registerTask('sauce', [
        'jasmine:main:build',
        'connect',
        'saucelabs-jasmine'
    ]);
    grunt.registerTask('travis', [
        'eslint:main',
        'sauce',
        'build-prod'
    ]);
};
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var multer  = require('multer');
var fs = require('fs');
var NCMB = require("ncmb"),
    ncmb = new NCMB("655099e79b56b4ca5a1429d184acd69f480738197c9ad755b5658a6f8db0571a","071d9fc038d795a9895b96545df65f43fe4b32781181d45649b1f6d39c717555");

var app = express();

var upload = multer({ dest: 'uploads/' });
app.use(express.static(path.join(__dirname, 'public_html')));

app.get('/hoge', function (req, res) {

    var Coupon = ncmb.DataStore("coupon");
    Coupon.fetchAll()
        .then(function(results){
	    console.dir(results);

	    for (var i = 0; i < results.length; i++) {
		var object = results[i];
		console.log(object.score + " - " + object.get("playerName"));
	    }

	    res.send('Hello World!');
	})
        .catch(function(err){
	    console.log(err);
	});

});

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});
<commit_msg>画像アップロード機能実装<commit_after>var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var express = require('express');
var multer  = require('multer');

var NCMB = require("ncmb"),
    ncmb = new NCMB("655099e79b56b4ca5a1429d184acd69f480738197c9ad755b5658a6f8db0571a","071d9fc038d795a9895b96545df65f43fe4b32781181d45649b1f6d39c717555");

var app = express();

app.use(express.static(path.join(__dirname, 'public_html')));

var storage = multer.diskStorage({
    destination: './uploads/',
    filename: function (req, file, cb) {
	crypto.pseudoRandomBytes(16, function (err, raw) {
	    if (err) return cb(err);

	    cb(null, raw.toString('hex') + path.extname(file.originalname));
	});
    }
});
var upload = multer({ storage: storage });

app.post('/upload', upload.single('avatar'), function (req, res, next) {
    console.log(req.body);
    console.log(req.file.path);

    ncmb.File.upload(req.file.filename, req.file.path)
        .then(function(data){
	    // アップロード後処理
	    fs.unlink(req.file.path);
	    res.send("hoge");
	})
        .catch(function(err){
	    // エラー処理
	    fs.unlink(req.file.path);
	    res.send("failed");
	});
});

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});

//app.use(express.static(path.join(__dirname, 'public_html')));

//console.dir(multer);

//app.use(multer({ dest: 'uploads/' }));
// var limits = { fileSize: 10 * 1024 * 1024 };
// var storage = multer.diskStorage({});
// var upload = multer({ limits: limits, storage: storage });

// app.get('/hoge', function (req, res) {
//     res.send('Hello World!');
// });

// app.post('/upload', upload.single('photo'), function(req, res){
//     console.log(req.body);
//     console.log(req.files);

//     res.status(204).end();
// });

// app.post('/upload',  [ multer({ dest: './uploads/'}), function(req, res){
//     console.log(req.body); // form fields
//     console.log(req.files); // form files

//     res.send("hoge");
//     res.status(204).end();
// }]);

// var server = app.listen(3000, function () {
//     var host = server.address().address;
//     var port = server.address().port;

//     console.log('Example app listening at http://%s:%s', host, port);
// });
<|endoftext|>


<commit_before>module.exports = function(){
    var _ = require('underscore');
    var schemaValidator = require('jsonschema');
    var userSchema = require('bonsens-models').user;
    var dao = require('daoi');

    this.init = function(config) {
        var self = this;
        var daoImpl = dao.use(dao.MEMORY);
        this.params = _.defaults(config||{}, defaults)
        process.on('user:update', function(user){
console.log('user:update', user);
        });
        process.on('user:find', function(criteria){
console.log('user:find', criteria);
            // fake search result
            process.emit('user:find.by.email.'+criteria.email+'.response', {fake: 'user'});//todo
            // daoImpl.user.find(pin)
            // .then(function(user){
            // })
            // .catch(function(err){
            // })
        });
        process.on('user:register', function(pin){
            console.log('clonq/revo-user: user:register: ', pin);
            var pout = {};
            var errors = validate(pin);
            if(errors.length == 0) {
                dao.register('user');
                daoImpl.user.create(pin)
                .then(function(user){
                    if(!!user.inviteCode) {
                        var invitationPayload = {
                            code: user.inviteCode,
                            email: user.email
                        };
                        process.emit('invitation:process', invitationPayload);
                    }
                    // pout = {
                    //     user: user,
                    //     success: {
                    //         message: "user has been registered successfully"
                    //     }
                    // }
                    // process.emit('user:register.response', pout);
                })
                .catch(function(err){
                    pout.error = { message: err.message };
                    process.emit('user:register.response', pout);
                })
            } else {
                pout.error = { message: errors[0].message };
                process.emit('user:register.response', pout);
            }
        })
    }

    function validate(payload) {
        // userSchema.required = ['name', 'email', 'password'];
        var schemaErrors = schemaValidator.validate(payload, userSchema).errors;
        if(schemaErrors.length > 0) return schemaErrors;
        var dataErrors = [];
        if(payload.name.length == 0) dataErrors.push({message:'name is mandatory'});
        if(payload.email.length == 0) dataErrors.push({message:'email is mandatory'});
        if(payload.password.length == 0) dataErrors.push({message:'password is mandatory'});
        return dataErrors
    }

}

var defaults = module.exports.defaults = {
    listen: 'user:register',
    models: {
        user: {
            supportedMethods: ['register', 'find']
        }
    }
}
<commit_msg>remove explicit listen declaration<commit_after>module.exports = function(){
    var _ = require('underscore');
    var schemaValidator = require('jsonschema');
    var userSchema = require('bonsens-models').user;
    var dao = require('daoi');

    this.init = function(config) {
        var self = this;
        var daoImpl = dao.use(dao.MEMORY);
        this.params = _.defaults(config||{}, defaults)
        process.on('user:update', function(user){
console.log('user:update', user);
        });
        process.on('user:find', function(criteria){
console.log('user:find', criteria);
            // fake search result
            process.emit('user:find.by.email.'+criteria.email+'.response', {fake: 'user'});//todo
            // daoImpl.user.find(pin)
            // .then(function(user){
            // })
            // .catch(function(err){
            // })
        });
        process.on('user:register', function(pin){
            console.log('clonq/revo-user: user:register: ', pin);
            var pout = {};
            var errors = validate(pin);
            if(errors.length == 0) {
                dao.register('user');
                daoImpl.user.create(pin)
                .then(function(user){
                    if(!!user.inviteCode) {
                        var invitationPayload = {
                            code: user.inviteCode,
                            email: user.email
                        };
                        process.emit('invitation:process', invitationPayload);
                    }
                    // pout = {
                    //     user: user,
                    //     success: {
                    //         message: "user has been registered successfully"
                    //     }
                    // }
                    // process.emit('user:register.response', pout);
                })
                .catch(function(err){
                    pout.error = { message: err.message };
                    process.emit('user:register.response', pout);
                })
            } else {
                pout.error = { message: errors[0].message };
                process.emit('user:register.response', pout);
            }
        })
    }

    function validate(payload) {
        // userSchema.required = ['name', 'email', 'password'];
        var schemaErrors = schemaValidator.validate(payload, userSchema).errors;
        if(schemaErrors.length > 0) return schemaErrors;
        var dataErrors = [];
        if(payload.name.length == 0) dataErrors.push({message:'name is mandatory'});
        if(payload.email.length == 0) dataErrors.push({message:'email is mandatory'});
        if(payload.password.length == 0) dataErrors.push({message:'password is mandatory'});
        return dataErrors
    }

}

var defaults = module.exports.defaults = {
    models: {
        user: {
            supportedMethods: ['register', 'find']
        }
    }
}
<|endoftext|>


<commit_before>var diffmode=true;    // true for manual check, false for production
var debug=true;
var trimpage=true;

var jsonfn=process.argv[2]||"ketaka84.json";  //default json filename
if (jsonfn.indexOf(".json")==-1)jsonfn+=".json";
var json=require("./"+jsonfn);

var source_xml_folder="before_xml/";
var merged_xml_folder="merged_xml/";

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

var fs=require("fs");
var mkdirp=require("./mkdirp");
var path=require("path");
var lastfile="",pages={},currentfile="",currentpage="";
var unmerged=[],lasterror="",mergecount=0;

var errormerge=function(item){
	item.err=lasterror;
	lasterror="";
	if (debug) inserterror(item.offset,unmerged.length+1);
	unmerged.push(JSON.stringify(item));
}

var loadPage=function(filecontent) {
	var pages={},lastidx=0,lastid="_";
	filecontent.replace(/<pb id="(.+?)"\/>\n?/g,function(m,m1,idx){
		if (lastidx===0) {
			pages[lastid]=filecontent.substr(0,idx);
		}
		pages[lastid]=filecontent.substring(lastidx,idx);
		lastidx=idx+m.length;
		lastid=m1;
	});
	pages[lastid]=filecontent.substring(lastidx).trim();

	if (trimpage) for (var i in pages) pages[i]=pages[i].trim();

	return pages;
}
var fetchText=function(pagecontent,offset,len) {
	var realoff=getOffsetOmitTag(pagecontent,offset);
	if (typeof realoff !=="number" || realoff<0) return null;
	return pagecontent.substr(realoff,len);
}

var getOffsetOmitTag=function(pagecontent,offset){
	var intag=false;
	var remain=offset;
	for (var i=0;i<pagecontent.length;i++) {
		var c=pagecontent[i];
		if (c==='<') intag=true;
		if (remain==0) {
			if (intag) {
				lasterror="offset inside tag";
				return -i;
			} else {
				return i;
			}
		}
		if (!intag) remain--;
		if (c==='>') intag=false;
	}
	lasterror="invalid offset";
	return null;
}

var merge=function(item) {
	var page=pages[currentpage];
	var realoff=getOffsetOmitTag(page,item.offset);
	var newtext=diffmode?("["+item.from+"|"+item.to+"]"):item.to;
	pages[currentpage]=page.substr(0,realoff)+newtext+page.substr(realoff+item.from.length);
}
var inserterror=function(offset,err) {
	var page=pages[currentpage];
	var realoff=Math.abs(getOffsetOmitTag(page,offset));
	pages[currentpage]=page.substr(0,realoff)+"!"+err+page.substr(realoff);
}
var createnewfilecontent=function() {
	var s="";
	for (var i in pages) {
		if (i!=="_") s+='<pb id="'+i+'"/>\n';
		s+=pages[i];
	}
	return s;
}

var savemergefile=function() {
	if (!lastfile)return;
	var outfn=merged_xml_folder+lastfile;
	var dir=path.dirname(outfn);
	mkdirp.sync(dir);	//create folder if not exist
	fs.writeFileSync(outfn,createnewfilecontent(),"utf8");
}

var trymerge=function(item){
	if (item.file!==lastfile) {
		savemergefile();
		currentfile=item.file;
		pages=loadPage(fs.readFileSync(source_xml_folder+item.file,"utf8"));
	}
	currentpage=item.page;
	var t=fetchText(pages[item.page],item.offset,item.from.length);

	if (!t) {
		if (!lasterror) lasterror="invalid offset";
		errormerge(item);
	} else if (t!==item.from) {
		if (!lasterror) lasterror="xml mismatch:"+t;
		errormerge(item);
	} else {
		if (t===item.to){
		 	lasterror="sametext";
			errormerge(item);
		} else {
			mergecount++;
			merge(item);
		}
	}
	lastfile=item.file;
}

json.map(trymerge);
savemergefile(); //last file content
var unmergefn=jsonfn.replace(".json","")+"_unmerged.json";
console.log("success merged",mergecount,"unmerged",unmerged.length,"check",unmergefn);
fs.writeFileSync(unmergefn,unmerged.join("\n"),"utf8")<commit_msg>pb in single line<commit_after>var diffmode=true;    // true for manual check, false for production
var debug=true;
var trimpage=true;

var jsonfn=process.argv[2]||"ketaka84.json";  //default json filename
if (jsonfn.indexOf(".json")==-1)jsonfn+=".json";
var json=require("./"+jsonfn);

var source_xml_folder="before_xml/";
var merged_xml_folder="merged_xml/";

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

var fs=require("fs");
var mkdirp=require("./mkdirp");
var path=require("path");
var lastfile="",pages={},currentfile="",currentpage="";
var unmerged=[],lasterror="",mergecount=0;

var errormerge=function(item){
	item.err=lasterror;
	lasterror="";
	if (debug) inserterror(item.offset,unmerged.length+1);
	unmerged.push(JSON.stringify(item));
}

var loadPage=function(filecontent) {
	var pages={},lastidx=0,lastid="_";
	filecontent.replace(/<pb id="(.+?)"\/>\n?/g,function(m,m1,idx){
		if (lastidx===0) {
			pages[lastid]=filecontent.substr(0,idx);
		}
		pages[lastid]=filecontent.substring(lastidx,idx);
		lastidx=idx+m.length;
		lastid=m1;
	});
	pages[lastid]=filecontent.substring(lastidx).trim();

	if (trimpage) for (var i in pages) pages[i]=pages[i].trim();

	return pages;
}
var fetchText=function(pagecontent,offset,len) {
	var realoff=getOffsetOmitTag(pagecontent,offset);
	if (typeof realoff !=="number" || realoff<0) return null;
	return pagecontent.substr(realoff,len);
}

var getOffsetOmitTag=function(pagecontent,offset){
	var intag=false;
	var remain=offset;
	for (var i=0;i<pagecontent.length;i++) {
		var c=pagecontent[i];
		if (c==='<') intag=true;
		if (remain==0) {
			if (intag) {
				lasterror="offset inside tag";
				return -i;
			} else {
				return i;
			}
		}
		if (!intag) remain--;
		if (c==='>') intag=false;
	}
	lasterror="invalid offset";
	return null;
}

var merge=function(item) {
	var page=pages[currentpage];
	var realoff=getOffsetOmitTag(page,item.offset);
	var newtext=diffmode?("["+item.from+"|"+item.to+"]"):item.to;
	pages[currentpage]=page.substr(0,realoff)+newtext+page.substr(realoff+item.from.length);
}
var inserterror=function(offset,err) {
	var page=pages[currentpage];
	var realoff=Math.abs(getOffsetOmitTag(page,offset));
	pages[currentpage]=page.substr(0,realoff)+"!"+err+page.substr(realoff);
}
var createnewfilecontent=function() {
	var s="";
	for (var i in pages) {
		if (i!=="_") s+='\n<pb id="'+i+'"/>\n';
		s+=pages[i];
	}
	return s;
}

var savemergefile=function() {
	if (!lastfile)return;
	var outfn=merged_xml_folder+lastfile;
	var dir=path.dirname(outfn);
	mkdirp.sync(dir);	//create folder if not exist
	fs.writeFileSync(outfn,createnewfilecontent(),"utf8");
}

var trymerge=function(item){
	if (item.file!==lastfile) {
		savemergefile();
		currentfile=item.file;
		pages=loadPage(fs.readFileSync(source_xml_folder+item.file,"utf8"));
	}
	currentpage=item.page;
	var t=fetchText(pages[item.page],item.offset,item.from.length);

	if (!t) {
		if (!lasterror) lasterror="invalid offset";
		errormerge(item);
	} else if (t!==item.from) {
		if (!lasterror) lasterror="xml mismatch:"+t;
		errormerge(item);
	} else {
		if (t===item.to){
		 	lasterror="sametext";
			errormerge(item);
		} else {
			mergecount++;
			merge(item);
		}
	}
	lastfile=item.file;
}

json.map(trymerge);
savemergefile(); //last file content
var unmergefn=jsonfn.replace(".json","")+"_unmerged.json";
console.log("success merged",mergecount,"unmerged",unmerged.length,"check",unmergefn);
fs.writeFileSync(unmergefn,unmerged.join("\n"),"utf8")<|endoftext|>


<commit_before>(function() {
  var selectOption = function(selector, value) {
    var options = $('option', selector);
    options.filter(function() {
      return ($(this).text() == value);
    }).prop('selected', true);
  };

  var highlight = function(selector) {
    $(selector).effect('highlight', 1500);
  };

  var setVAT = function(value) {
    var selector = '#purchase_sales_tax_rate';
    selectOption(selector, value);
    highlight(selector);
  };

  var setCategory = function(value) {
    var selector = $('#other_payment_type');
    selectOption(selector, value);
    highlight(selector);
  };

  var setDescription = function(value) {
    var selector = '#bank_account_entry_description';
    var descriptionField = $(selector);
    descriptionField.val(value);
    highlight(selector);
  };

  var promptForAnAttachment = function() {
    var selector = '#attachment_form h2';
    $(selector).text('Now upload an attachment!');
    $(selector).css('color', '#f00');
    highlight(selector);
  }

  var rules = [
    ['CAMPFIRE', '37 Signals - Campfire', '0', 'Computer Software', true],
    ['GITHUB.COM', 'GitHub - Monthly subscription', '0', 'Computer Software', true],
    ['LINODE.COM', 'Linode - Monthly subscription - Linode 2048', '0', 'Web Hosting', true],
    ['Non-Sterling Transaction Fee', 'Non Sterling Transaction Fee', '0', 'Bank/Finance Charges', false],
    ['PACT COFFEE', 'Pact Coffee London', '0', 'Sundries', false],
    ['TOTAL CHARGES TO', 'HSBC - Monthly account maintenance fee', '0', 'Bank/Finance Charges', false],
    ['SVCSAPPS_G', 'Google Apps for Business', '0', 'Computer Software', true]
  ]

  var tryToExplainTransaction = function() {
    var unexplainedTransactionText = $('.transaction.unexplained').text();

    if (unexplainedTransactionText) {
      $(rules).each(function(index, rule) {
        var textToMatch = rule[0];
        var description = rule[1];
        var vat = rule[2];
        var category = rule[3];
        var shouldHaveAttachment = rule[4];

        console.log('Testing: ' + textToMatch);
        if (unexplainedTransactionText.match(textToMatch)) {
          console.log('Found: ' + description);

          setVAT(vat);
          setCategory(category);
          setDescription(description);
          if (shouldHaveAttachment) {
            promptForAnAttachment();
          };

          return false; // We don't need to continue having found a match
        };
      });
    } else {
      console.log('Ignoring previously explained transactions');
    };
  }

  tryToExplainTransaction();
})();
<commit_msg>Add EC Status to rules<commit_after>(function() {
  var selectOption = function(selector, value) {
    var options = $('option', selector);
    options.filter(function() {
      return ($(this).text() == value);
    }).prop('selected', true);
  };

  var highlight = function(selector) {
    $(selector).effect('highlight', 1500);
  };

  var setVAT = function(value) {
    var selector = '#purchase_sales_tax_rate';
    selectOption(selector, value);
    highlight(selector);
  };

  var setEcStatus = function(value) {
    var ecStatusOptions = {
      'Non-EC': '#bank_account_entry_ec_status_',
      'EC Goods': '#bank_account_entry_ec_status_2',
      'EC Services': '#bank_account_entry_ec_status_1'
    };

    var ecStatusSelector = ecStatusOptions[value];
    $(ecStatusSelector).prop('checked', true);
    highlight('#ec_status_options');
  };

  var setCategory = function(value) {
    var selector = $('#other_payment_type');
    selectOption(selector, value);
    highlight(selector);
  };

  var setDescription = function(value) {
    var selector = '#bank_account_entry_description';
    var descriptionField = $(selector);
    descriptionField.val(value);
    highlight(selector);
  };

  var promptForAnAttachment = function() {
    var selector = '#attachment_form h2';
    $(selector).text('Now upload an attachment!');
    $(selector).css('color', '#f00');
    highlight(selector);
  }

  var rules = [
    ['CAMPFIRE', '37 Signals - Campfire', '0', 'Computer Software', true, 'Non-EC'],
    ['GITHUB.COM', 'GitHub - Monthly subscription', '0', 'Computer Software', true, 'Non-EC'],
    ['LINODE.COM', 'Linode - Monthly subscription - Linode 2048', '0', 'Web Hosting', true, 'Non-EC'],
    ['Non-Sterling Transaction Fee', 'Non Sterling Transaction Fee', '0', 'Bank/Finance Charges', false, 'Non-EC'],
    ['PACT COFFEE', 'Pact Coffee London', '0', 'Sundries', false, 'Non-EC'],
    ['TOTAL CHARGES TO', 'HSBC - Monthly account maintenance fee', '0', 'Bank/Finance Charges', false, 'Non-EC'],
    ['SVCSAPPS_G', 'Google Apps for Business', '0', 'Computer Software', true, 'EC Services']
  ]

  var tryToExplainTransaction = function() {
    var unexplainedTransactionText = $('.transaction.unexplained').text();

    if (unexplainedTransactionText) {
      $(rules).each(function(index, rule) {
        var textToMatch = rule[0];
        var description = rule[1];
        var vat = rule[2];
        var category = rule[3];
        var shouldHaveAttachment = rule[4];
        var ecStatus = rule[5];

        console.log('Testing: ' + textToMatch);
        if (unexplainedTransactionText.match(textToMatch)) {
          console.log('Found: ' + description);

          setVAT(vat);
          setEcStatus(ecStatus);
          setCategory(category);
          setDescription(description);
          if (shouldHaveAttachment) {
            promptForAnAttachment();
          };

          return false; // We don't need to continue having found a match
        };
      });
    } else {
      console.log('Ignoring previously explained transactions');
    };
  }

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


<commit_before>var GameAI = function(player1name, player2name){
	Game.call(this, player1name, player2name);
}

GameAI.prototype = Object.create(Game.prototype);
GameAI.prototype.buildNewProbs = function() {

	if (gamePiano[1] == this.getNextTurnPlayerSlug() || gamePiano[2] == this.getNextTurnPlayerSlug() || gamePiano[3] == this.getNextTurnPlayerSlug())
		lines[1] = 0;
	if (gamePiano[4] == this.getNextTurnPlayerSlug() || gamePiano[5] == this.getNextTurnPlayerSlug() || gamePiano[6] == this.getNextTurnPlayerSlug())
		lines[2] = 0;
	if (gamePiano[7] == this.getNextTurnPlayerSlug() || gamePiano[8] == this.getNextTurnPlayerSlug() || gamePiano[9] == this.getNextTurnPlayerSlug())
		lines[3] = 0;
	if (gamePiano[1] == this.getNextTurnPlayerSlug() || gamePiano[4] == this.getNextTurnPlayerSlug() || gamePiano[7] == this.getNextTurnPlayerSlug())
		cols[1] = 0;
	if (gamePiano[2] == this.getNextTurnPlayerSlug() || gamePiano[5] == this.getNextTurnPlayerSlug() || gamePiano[8] == this.getNextTurnPlayerSlug())
		cols[2] = 0;
	if (gamePiano[3] == this.getNextTurnPlayerSlug() || gamePiano[6] == this.getNextTurnPlayerSlug() || gamePiano[9] == this.getNextTurnPlayerSlug())
		cols[3] = 0;
	if (gamePiano[1] == this.getNextTurnPlayerSlug() || gamePiano[5] == this.getNextTurnPlayerSlug() || gamePiano[9] == this.getNextTurnPlayerSlug())
		diag[1] = 0;
	if (gamePiano[3] == this.getNextTurnPlayerSlug() || gamePiano[5] == this.getNextTurnPlayerSlug() || gamePiano[7] == this.getNextTurnPlayerSlug())
		diag[2] = 0;

	gameMap[1].prob = lines[1] + cols[1] + diag[1];
	gameMap[2].prob = lines[1] + cols[2];
	gameMap[3].prob = lines[1] + cols[3] + diag[2];
	gameMap[4].prob = lines[2] + cols[1];
	gameMap[5].prob = lines[2] + cols[2] + diag[1] + diag[2];
	gameMap[6].prob = lines[2] + cols[3];
	gameMap[7].prob = lines[3] + cols[1] + diag[2];
	gameMap[8].prob = lines[3] + cols[2];
	gameMap[9].prob = lines[3] + cols[3] + diag[1];

	return true;
};

GameAI.prototype.AIChoice = function() {
	var bestProb = [];
	$.each(gameMap,function(index,square){
		bestProb[index] = parseInt(square.prob);
	});

	var maxValue = 0;
	bestProb.forEach(function(value, index){
		if (value > maxValue)
			maxValue = value;
	});

	bestProb.forEach(function(value, index){
		if (value < maxValue)
			delete bestProb[index];
	});

	var squares = [];
	bestProb.forEach(function(value, index){
		if ($('.square[data-id=' + index + ']').attr('data-belong') == "false")
			squares.push(index);
	});

	this.AIClick(squares[Math.floor(Math.random() * squares.length)]);
};

GameAI.prototype.onValidateTour = function(){
	Game.prototype.onValidateTour.call(this);
	this.buildNewProbs();

	if (this.getCurrentTurn().slug == "player2")
		this.AIChoice();
}

GameAI.prototype.AIClick = function(square) {
	$('.square[data-id=' + square + ']').click();
    Materialize.toast("L'IA a choisit sa case (" + square + ')', 5000);
	setTimeout(function(){
		$('#validateTourButton').trigger("click");
	},800);
};<commit_msg>add defensive choices<commit_after>var GameAI = function(player1name, player2name){
	Game.call(this, player1name, player2name);
}

GameAI.prototype = Object.create(Game.prototype);
GameAI.prototype.buildNewProbs = function() {

	console.log("[AI] - AI is building probabilities");

	var nextTurnPlayerSlug = this.getNextTurnPlayerSlug();

	if (gamePiano[1] == nextTurnPlayerSlug || gamePiano[2] == nextTurnPlayerSlug || gamePiano[3] == nextTurnPlayerSlug)
		lines[1] = 0;
	if (gamePiano[4] == nextTurnPlayerSlug || gamePiano[5] == nextTurnPlayerSlug || gamePiano[6] == nextTurnPlayerSlug)
		lines[2] = 0;
	if (gamePiano[7] == nextTurnPlayerSlug || gamePiano[8] == nextTurnPlayerSlug || gamePiano[9] == nextTurnPlayerSlug)
		lines[3] = 0;
	if (gamePiano[1] == nextTurnPlayerSlug || gamePiano[4] == nextTurnPlayerSlug || gamePiano[7] == nextTurnPlayerSlug)
		cols[1] = 0;
	if (gamePiano[2] == nextTurnPlayerSlug || gamePiano[5] == nextTurnPlayerSlug || gamePiano[8] == nextTurnPlayerSlug)
		cols[2] = 0;
	if (gamePiano[3] == nextTurnPlayerSlug || gamePiano[6] == nextTurnPlayerSlug || gamePiano[9] == nextTurnPlayerSlug)
		cols[3] = 0;
	if (gamePiano[1] == nextTurnPlayerSlug || gamePiano[5] == nextTurnPlayerSlug || gamePiano[9] == nextTurnPlayerSlug)
		diag[1] = 0;
	if (gamePiano[3] == nextTurnPlayerSlug || gamePiano[5] == nextTurnPlayerSlug || gamePiano[7] == nextTurnPlayerSlug)
		diag[2] = 0;

	gameMap[1].prob = lines[1] + cols[1] + diag[1];
	gameMap[2].prob = lines[1] + cols[2];
	gameMap[3].prob = lines[1] + cols[3] + diag[2];
	gameMap[4].prob = lines[2] + cols[1];
	gameMap[5].prob = lines[2] + cols[2] + diag[1] + diag[2];
	gameMap[6].prob = lines[2] + cols[3];
	gameMap[7].prob = lines[3] + cols[1] + diag[2];
	gameMap[8].prob = lines[3] + cols[2];
	gameMap[9].prob = lines[3] + cols[3] + diag[1];

	console.log("[AI] - AI has build new probs");

	return true;
};

// Code le plus indigeste de cette planète.
GameAI.prototype.willBeWinner = function() {

	console.log("[AI] - Checking if AI have to block");

	var isPlayerWin = this.overrideProbs(this.player1);
	var isIAWin = this.overrideProbs(this.player2);

	console.log(typeof isPlayerWin + "," + isPlayerWin);
	console.log(typeof isIAWin + "," + isIAWin);

	if (isIAWin) {
		//gameMap[isIAWin].prob = 1000;
		console.log("[AI] - AI do not have to block because she will win");
		return isIAWin;
	} else if(isPlayerWin) {
		//gameMap[isPlayerWin].prob = 1000;
		console.log("[AI] - AI have to block in square : " + isPlayerWin);
		return isPlayerWin;
	} else {
		console.log("[AI] - AI do not have to block");
	}

	return false;
};

GameAI.prototype.overrideProbs = function(player) {

	var challenger = player.slug == "player1" ? this.player2 : this.player1;

	if (gamePiano[1] == player.slug && gamePiano[4] == player.slug && gamePiano[7] == null) {
		return 7;
	}

	if (gamePiano[7] == player.slug && gamePiano[1] == player.slug && gamePiano[4] == null) {
		return 4;
	}

	if (gamePiano[4] == player.slug && gamePiano[7] == player.slug && gamePiano[1] == null) {
		return 1;
	}

	if (gamePiano[2] == player.slug && gamePiano[5] == player.slug && gamePiano[8] == null) {
		return 8;
	}

	if (gamePiano[8] == player.slug && gamePiano[2] == player.slug && gamePiano[5] == null) {
		return 5;
	}

	if (gamePiano[5] == player.slug && gamePiano[8] == player.slug && gamePiano[2] == null) {
		return 2;
	}

	if (gamePiano[3] == player.slug && gamePiano[6] == player.slug && gamePiano[9] == null) {
		return 9;
	}

	if (gamePiano[9] == player.slug && gamePiano[3] == player.slug && gamePiano[6] == null) {
		return 6;
	}

	if (gamePiano[6] == player.slug && gamePiano[9] == player.slug && gamePiano[3] == null) {
		return 3;
	}

	if (gamePiano[1] == player.slug && gamePiano[2] == player.slug && gamePiano[3] == null) {
		return 3;
	}

	if (gamePiano[3] == player.slug && gamePiano[1] == player.slug && gamePiano[2] == null) {
		return 2;
	}

	if (gamePiano[3] == player.slug && gamePiano[2] == player.slug && gamePiano[1] == null) {
		return 1;
	}

	if (gamePiano[4] == player.slug && gamePiano[5] == player.slug && gamePiano[6] == null) {
		return 6;
	}

	if (gamePiano[6] == player.slug && gamePiano[4] == player.slug && gamePiano[5] == null) {
		return 5;
	}

	if (gamePiano[6] == player.slug && gamePiano[5] == player.slug && gamePiano[4] == null) {
		return 4;
	}

	if (gamePiano[7] == player.slug && gamePiano[8] == player.slug && gamePiano[9] == null) {
		return 9;
	}

	if (gamePiano[9] == player.slug && gamePiano[7] == player.slug && gamePiano[8] == null) {
		return 8;
	}

	if (gamePiano[9] == player.slug && gamePiano[8] == player.slug && gamePiano[7] == null) {
		return 7;
	}

	if (gamePiano[1] == player.slug && gamePiano[5] == player.slug && gamePiano[9] == null) {
		return 9;
	}

	if (gamePiano[9] == player.slug && gamePiano[1] == player.slug && gamePiano[5] == null) {
		return 5;
	}

	if (gamePiano[5] == player.slug && gamePiano[9] == player.slug && gamePiano[1] == null) {
		return 1;
	}

	if (gamePiano[3] == player.slug && gamePiano[5] == player.slug && gamePiano[7] == null) {
		return 7;
	}

	if (gamePiano[7] == player.slug && gamePiano[3] == player.slug && gamePiano[5] == null) {
		return 5;
	}

	if (gamePiano[5] == player.slug && gamePiano[7] == player.slug && gamePiano[3] == null) {
		return 3;
	}

	return false;
};

GameAI.prototype.AIChoice = function(forcedChoice) {

	console.log(forcedChoice);

	forcedChoice = forcedChoice || null;
	console.log(forcedChoice);

	if (!forcedChoice) {

		console.log("[AI] - AI is making a choice");
		console.log("[AI] - Probs are this one : ");

		var bestProb = [];
		console.log(bestProb);
		$.each(gameMap,function(index,square){
			bestProb[index] = parseInt(square.prob);
		});
		console.log(bestProb);

		var maxValue = 0;
		bestProb.forEach(function(value, index){
			if (value > maxValue)
				maxValue = value;
		});

		bestProb.forEach(function(value, index){
			if (value < maxValue)
				delete bestProb[index];
		});

		var squares = [];
		bestProb.forEach(function(value, index){
			console.log("[BESTPROB] index -> " + index);
			console.log("[BESTPROB] value -> " + value);
			if ($('.square[data-id=' + index + ']').attr('data-belong') == "false")
				squares.push(index);
		});

		console.log("[AI] - AI has possible choices : " );
		console.log(squares);

		var choosenSquare = squares[Math.floor(Math.random() * squares.length)];

		gameMap[choosenSquare].prob = parseInt(0);
	} else {
		var choosenSquare = forcedChoice;
		console.log("[AI] - The choice is forced to : " + choosenSquare );
	}

	this.AIClick(choosenSquare);
};

GameAI.prototype.onValidateTour = function(){
	Game.prototype.onValidateTour.call(this);

	if (this.getCurrentTurn().slug == "player2") {
		var winner = this.willBeWinner();
		if (winner) {
			this.AIChoice(winner);
		} else {
			this.buildNewProbs();
			this.AIChoice();
		}
	}
}

GameAI.prototype.AIClick = function(square) {
	$('.square[data-id=' + square + ']').click();
    Materialize.toast("L'IA a choisit sa case (" + square + ')', 5000);
	setTimeout(function(){
		$('#validateTourButton').trigger("click");
	},800);
};<|endoftext|>


<commit_before>var http = require('http'),
  _ = require('../underscore_ext');

/**
 * Class responsible for tunnelling requests
 */
class Proxy {
  constructor(config) {
    _.bindAll(this, '_handleRequest');

    this._configure.call(this, config);
  }

  /**
   * Listen to port
   */
  listen() {
    this._createServer();
    this.server.listen(this.config.port);
  }

  /**
   * Stops listening
   */
 stop() {
   this.server.close();
  }

  /**
   * Configure redirecter
   */
  _configure(config) {
    let redirecter = this;

    redirecter.config = _.extend({
      port:3330,
      proxy: {
        host: 'localhost',
        port: 80
      },
      before:[]
    }, config);

    redirecter.before = _.asArray(config.before);
  }

  /**
   * Initiate server
   */
  _createServer() {
    let redirecter = this;

    redirecter.server = http.createServer(this._handleRequest);
  }

  /**
   * Handles each request piping it to the proxied server
   */
  _handleRequest(request, response){
    if (this._applyBefore(request, response)) {
      this._pipeRequest(request, response);
    }
  }

  _pipeRequest(request, response) {
    request.pipe(this._proxyRequest(request, response));
  }

  _proxyRequest(request, response) {
    var options = {
      headers:  request.headers,
      hostname: this.config.proxy.host,
      port:     this.config.proxy.port,
      method:   request.method,
      path:     request.url
    };

    return http.request(options, function (res) {
      response.writeHead(res.statusCode, res.headers);
      res.pipe(response, {
        end: true
      });
    });
  }

  /**
   * Run before scripts on request
   */
  _applyBefore(request, response){
    let redirecter = this;

    for (var i = 0; i < redirecter.before.length; i++){
      if (! redirecter.before[i].call(redirecter, request, response))
        return false;
    }
    return true;
  }
}

module.exports = function(config){
  redirecter = new Proxy(config);
  return redirecter;
};

module.exports.fn = Proxy.prototype;
<commit_msg>Correct identation<commit_after>var http = require('http'),
  _ = require('../underscore_ext');

/**
 * Class responsible for tunnelling requests
 */
class Proxy {
  constructor(config) {
    _.bindAll(this, '_handleRequest');

    this._configure.call(this, config);
  }

  /**
   * Listen to port
   */
  listen() {
    this._createServer();
    this.server.listen(this.config.port);
  }

  /**
   * Stops listening
   */
  stop() {
    this.server.close();
  }

  /**
   * Configure redirecter
   */
  _configure(config) {
    let redirecter = this;

    redirecter.config = _.extend({
      port:3330,
      proxy: {
        host: 'localhost',
        port: 80
      },
      before:[]
    }, config);

    redirecter.before = _.asArray(config.before);
  }

  /**
   * Initiate server
   */
  _createServer() {
    let redirecter = this;

    redirecter.server = http.createServer(this._handleRequest);
  }

  /**
   * Handles each request piping it to the proxied server
   */
  _handleRequest(request, response){
    if (this._applyBefore(request, response)) {
      this._pipeRequest(request, response);
    }
  }

  _pipeRequest(request, response) {
    request.pipe(this._proxyRequest(request, response));
  }

  _proxyRequest(request, response) {
    var options = {
      headers:  request.headers,
      hostname: this.config.proxy.host,
      port:     this.config.proxy.port,
      method:   request.method,
      path:     request.url
    };

    return http.request(options, function (res) {
      response.writeHead(res.statusCode, res.headers);
      res.pipe(response, {
        end: true
      });
    });
  }

  /**
   * Run before scripts on request
   */
  _applyBefore(request, response){
    let redirecter = this;

    for (var i = 0; i < redirecter.before.length; i++){
      if (! redirecter.before[i].call(redirecter, request, response))
        return false;
    }
    return true;
  }
}

module.exports = function(config){
  redirecter = new Proxy(config);
  return redirecter;
};

module.exports.fn = Proxy.prototype;
<|endoftext|>


<commit_before>/*
 * Copyright 2019 Immersive Web Community Group. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
Example Gamepad mapping. Any of the values may be omitted for the original
gamepad values to pass through unchanged.

"Gamepad ID String": { // The Gamepad.id that this entry maps to.
  mapping: 'xr-standard', // Overrides the Gamepad.mapping that is reported
  profiles: ['gamepad-id-string'], // The profiles array that should be reported
  displayProfiles: {
    // Alternative profiles arrays to report if the VRDevice.displayName matches
    "WebVR Display Name": ['gamepad-id-string']
  },
  axes: { // Remaps the reported axes
    length: 2, // Overrides the length of the reported axes array
    invert: [0] // List of mapped axes who's value should be inverted
    0: 2, // Remaps axes[0] to report axis[2] from the original gamepad object
    1: null, // Remaps axes[1] to a placeholder axis (always reports 0)
  },
  buttons: { // Remaps the reported buttons
    length: 2, // Overrides the length of the reported buttons array
    0: 2, // Remaps buttons[0] to report buttons[2] from the original gamepad object
    1: null // Remaps buttons[1] to a placeholder button (always reports 0/false)
  },
  gripTransform: { // An additional transform to apply to the gripSpace's pose
    position: [0, 0, 0.5], // Additional translation vector to apply
    orientation: [0, 0, 0, 1] // Additional rotation quaternion to apply
  },
  targetRayTransform: { // An additional transform to apply to the targetRaySpace's pose
    position: [0, 0, 0.5], // Additional translation vector to apply
    orientation: [0, 0, 0, 1] // Additional rotation quaternion to apply
  }
}
*/

let daydream = {
  mapping: '',
  profiles: ['daydream', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: null,
    1: null,
    2: 0
  },
};

let viveFocus = {
  mapping: 'xr-standard',
  profiles: ['htc-vive-focus', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: 1,
    1: null,
    2: 0
  },
};

let oculusGo = {
  mapping: 'xr-standard',
  profiles: ['oculus-go', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: 1,
    1: null,
    2: 0
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

// Applies to both left and right Oculus Touch controllers.
let oculusTouch = {
  mapping: 'xr-standard',
  displayProfiles: {
    'Oculus Quest': ['oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick']
  },
  profiles: ['oculus-touch', 'generic-trigger-squeeze-thumbstick'],
  axes: {
    length: 4,
    0: null,
    1: null,
    2: 0,
    3: 1
  },
  buttons: {
    length: 7,
    0: 1,
    1: 2,
    2: null,
    3: 0,
    4: 3,
    5: 4,
    6: null
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    position: [0, -0.02, 0.04, 1],
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let openVr = {
  mapping: 'xr-standard',
  profiles: ['openvr-controller', 'generic-trigger-squeeze-touchpad'],
  displayProfiles: {
    'HTC Vive': ['htc-vive', 'generic-trigger-squeeze-touchpad'],
    'HTC Vive DVT': ['htc-vive', 'generic-trigger-squeeze-touchpad'],
    'Valve Index': ['valve-index', 'generic-trigger-squeeze-touchpad-thumbstick']
  },
  buttons: {
    length: 3,
    0: 1,
    1: 2,
    2: 0
  },
  // Transform adjustments determined experimentally.
  gripTransform: {
    position: [0, 0, 0.05, 1],
  },
  targetRayTransform: {
    orientation: [Math.PI * -0.08, 0, 0, 1]
  },
  userAgentOverrides: {
    "Firefox": {
      axes: {
        invert: [1, 3]
      }
    }
  }
};

let samsungGearVR = {
  mapping: 'xr-standard',
  profiles: ['samsung-gearvr', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: 1,
    1: null,
    2: 0
  },
  gripTransform: {
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let samsungOdyssey = {
  mapping: 'xr-standard',
  profiles: ['samsung-odyssey', 'microsoft-mixed-reality', 'generic-trigger-squeeze-touchpad-thumbstick'],
  buttons: {
    length: 4,
    0: 1, // index finger trigger
    1: 0, // pressable joystick
    2: 2, // grip trigger
    3: 4, // pressable touchpad
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    position: [0, -0.02, 0.04, 1],
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let windowsMixedReality = {
  mapping: 'xr-standard',
  profiles: ['microsoft-mixed-reality', 'generic-trigger-squeeze-touchpad-thumbstick'],
  buttons: {
    length: 4,
    0: 1, // index finger trigger
    1: 0, // pressable joystick
    2: 2, // grip trigger
    3: 4, // pressable touchpad
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    position: [0, -0.02, 0.04, 1],
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let GamepadMappings = {
  'Daydream Controller': daydream,
  'Gear VR Controller': samsungGearVR,
  'HTC Vive Focus Controller': viveFocus,
  'Oculus Go Controller': oculusGo,
  'Oculus Touch (Right)': oculusTouch,
  'Oculus Touch (Left)': oculusTouch,
  'OpenVR Gamepad': openVr,
  'Spatial Controller (Spatial Interaction Source) 045E-065A': windowsMixedReality,
  'Spatial Controller (Spatial Interaction Source) 045E-065D': samsungOdyssey,
  'Windows Mixed Reality (Right)': windowsMixedReality,
  'Windows Mixed Reality (Left)': windowsMixedReality,
};

export default GamepadMappings;<commit_msg>Correct Daydream and OpenVR profile ids<commit_after>/*
 * Copyright 2019 Immersive Web Community Group. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
Example Gamepad mapping. Any of the values may be omitted for the original
gamepad values to pass through unchanged.

"Gamepad ID String": { // The Gamepad.id that this entry maps to.
  mapping: 'xr-standard', // Overrides the Gamepad.mapping that is reported
  profiles: ['gamepad-id-string'], // The profiles array that should be reported
  displayProfiles: {
    // Alternative profiles arrays to report if the VRDevice.displayName matches
    "WebVR Display Name": ['gamepad-id-string']
  },
  axes: { // Remaps the reported axes
    length: 2, // Overrides the length of the reported axes array
    invert: [0] // List of mapped axes who's value should be inverted
    0: 2, // Remaps axes[0] to report axis[2] from the original gamepad object
    1: null, // Remaps axes[1] to a placeholder axis (always reports 0)
  },
  buttons: { // Remaps the reported buttons
    length: 2, // Overrides the length of the reported buttons array
    0: 2, // Remaps buttons[0] to report buttons[2] from the original gamepad object
    1: null // Remaps buttons[1] to a placeholder button (always reports 0/false)
  },
  gripTransform: { // An additional transform to apply to the gripSpace's pose
    position: [0, 0, 0.5], // Additional translation vector to apply
    orientation: [0, 0, 0, 1] // Additional rotation quaternion to apply
  },
  targetRayTransform: { // An additional transform to apply to the targetRaySpace's pose
    position: [0, 0, 0.5], // Additional translation vector to apply
    orientation: [0, 0, 0, 1] // Additional rotation quaternion to apply
  }
}
*/

let daydream = {
  mapping: '',
  profiles: ['google-daydream', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: null,
    1: null,
    2: 0
  },
};

let viveFocus = {
  mapping: 'xr-standard',
  profiles: ['htc-vive-focus', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: 1,
    1: null,
    2: 0
  },
};

let oculusGo = {
  mapping: 'xr-standard',
  profiles: ['oculus-go', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: 1,
    1: null,
    2: 0
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

// Applies to both left and right Oculus Touch controllers.
let oculusTouch = {
  mapping: 'xr-standard',
  displayProfiles: {
    'Oculus Quest': ['oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick']
  },
  profiles: ['oculus-touch', 'generic-trigger-squeeze-thumbstick'],
  axes: {
    length: 4,
    0: null,
    1: null,
    2: 0,
    3: 1
  },
  buttons: {
    length: 7,
    0: 1,
    1: 2,
    2: null,
    3: 0,
    4: 3,
    5: 4,
    6: null
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    position: [0, -0.02, 0.04, 1],
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let openVr = {
  mapping: 'xr-standard',
  profiles: ['htc-vive', 'generic-trigger-squeeze-touchpad'],
  displayProfiles: {
    'HTC Vive': ['htc-vive', 'generic-trigger-squeeze-touchpad'],
    'HTC Vive DVT': ['htc-vive', 'generic-trigger-squeeze-touchpad'],
    'Valve Index': ['valve-index', 'generic-trigger-squeeze-touchpad-thumbstick']
  },
  buttons: {
    length: 3,
    0: 1,
    1: 2,
    2: 0
  },
  // Transform adjustments determined experimentally.
  gripTransform: {
    position: [0, 0, 0.05, 1],
  },
  targetRayTransform: {
    orientation: [Math.PI * -0.08, 0, 0, 1]
  },
  userAgentOverrides: {
    "Firefox": {
      axes: {
        invert: [1, 3]
      }
    }
  }
};

let samsungGearVR = {
  mapping: 'xr-standard',
  profiles: ['samsung-gearvr', 'generic-trigger-touchpad'],
  buttons: {
    length: 3,
    0: 1,
    1: null,
    2: 0
  },
  gripTransform: {
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let samsungOdyssey = {
  mapping: 'xr-standard',
  profiles: ['samsung-odyssey', 'microsoft-mixed-reality', 'generic-trigger-squeeze-touchpad-thumbstick'],
  buttons: {
    length: 4,
    0: 1, // index finger trigger
    1: 0, // pressable joystick
    2: 2, // grip trigger
    3: 4, // pressable touchpad
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    position: [0, -0.02, 0.04, 1],
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let windowsMixedReality = {
  mapping: 'xr-standard',
  profiles: ['microsoft-mixed-reality', 'generic-trigger-squeeze-touchpad-thumbstick'],
  buttons: {
    length: 4,
    0: 1, // index finger trigger
    1: 0, // pressable joystick
    2: 2, // grip trigger
    3: 4, // pressable touchpad
  },
  // Grip adjustments determined experimentally.
  gripTransform: {
    position: [0, -0.02, 0.04, 1],
    orientation: [Math.PI * 0.11, 0, 0, 1]
  }
};

let GamepadMappings = {
  'Daydream Controller': daydream,
  'Gear VR Controller': samsungGearVR,
  'HTC Vive Focus Controller': viveFocus,
  'Oculus Go Controller': oculusGo,
  'Oculus Touch (Right)': oculusTouch,
  'Oculus Touch (Left)': oculusTouch,
  'OpenVR Gamepad': openVr,
  'Spatial Controller (Spatial Interaction Source) 045E-065A': windowsMixedReality,
  'Spatial Controller (Spatial Interaction Source) 045E-065D': samsungOdyssey,
  'Windows Mixed Reality (Right)': windowsMixedReality,
  'Windows Mixed Reality (Left)': windowsMixedReality,
};

export default GamepadMappings;
<|endoftext|>


<commit_before>(function(){

angular.module('crowdy')
 .controller("tagTaskController", ['$http', '$sce', '$httpParamSerializerJQLike', '$log', '$modal', '$scope', '$rootScope', '$routeParams',
         function($http, $sce, $httpParamSerializerJQLike, $log, $modal, $scope, $rootScope, $routeParams) {

    var BACKEND_SERVER = "."; // e.g. http://localhost:3000

    $scope.preview = ($routeParams.assignmentId === 'ASSIGNMENT_ID_NOT_AVAILABLE' );
    $scope.formSubmitTo = $sce.trustAsResourceUrl($routeParams.turkSubmitTo + "/mturk/externalSubmit");
    $scope.assignmentId = $routeParams.assignmentId;

    $scope.type = "tagging";
    $scope.taskset = {};
    $scope.taskset.tasks = []; // Initialize empty, set when it's available

    //Modal
    $scope.openModal = function (opts) {
      var modalInstance = $modal.open({
        animation: true,
        templateUrl: 'templates/modal.html',
        controller: 'ModalInstanceCtrl',
        backdrop: 'static',
        size: 'lg',
        resolve: {
          opts: function () {
          return opts
          }
        }
      });
    };

    $scope.toggleAnimation = function () {
      $scope.animationsEnabled = !$scope.animationsEnabled;
    };

    $scope.submitForm = function($event) {
        if ($scope.turkForm.$valid) {
          // Submit form toServer
          $http.post(BACKEND_SERVER+"/save/hit", $scope.taskset)
            .success(function(res){
                $log.log(res);
                PostResultsToAmazon(res, null);
            })
            .error(function(err){
                // Still send results to amazon in case of error
                $log.error(err);
                PostResultsToAmazon($scope.taskset, res);
            });
          // Submit form back to Amazon
        } else {
          // Reload masonry, in case any errors pop up
          $rootScope.$broadcast("masonry.reload");
        }

    };

    PostResultsToAmazon = function(results, errors){
        $scope.hiddenErrors = errors;
        // Add an action to the main form.
        // It couldn't be there before because of interference with our submit method.
        // MTurk requires a post from the client, though.
        angular.element("#turkHiddenForm").submit();
        return;
    };

    // Construct JSON callback
    params = {
      callback: "JSON_CALLBACK",
      user: $scope.preview ? "PREVIEWUSER" : $routeParams.workerId,
      taskset_id:$scope.preview ? "TEST" : $routeParams.hitId,
      hit_id: $routeParams.hit_id,
      assignment_id: $routeParams.assignment_id,
      lock: !($scope.preview)
    };

    $http.jsonp(BACKEND_SERVER + "/hit", {params:params}).success(function(data){
        $scope.taskset = data.taskset;
        if ($scope.taskset.tasks.length === 0) {
          $rootScope.error = "No tasks";
          $scope.openModal({
            show: { ok: false},
            title: "Out of tasks :(",
            message: "Sorry, we ran out of tasks that are available at the moment.
We're really sorry about that, we know it sucks."
          });
        }
    }).error(function(err){
        $scope.error = "Unknown error";
    });

  }])

 .controller("tagTaskItemController", ['$http', '$log', '$scope', '$rootScope', '$routeParams',
         function($http, $log, $scope, $rootScope, $routeParams) {
        // Individual Item Controller

        $scope.$watch('tags', function(newValue, oldValue){
          // Only refresh masonry is the value actually changed
          // This also keeps from running on page load
          if (newValue !== oldValue) {
            $rootScope.$broadcast("masonry.reload");
          }
        });

         $scope.tooltip = function(item){
           return "Title: "+item.meta.title+"
Description: "+item.meta.description
         }

        // Individual item timer
        $scope.timeStart = function(item){
          if (!item.timing) {
          item.timing = new Date();
          }
        }

        $scope.timeStop = function(item){
          if (item.timing) {
            timeInFocus = (new Date()-item.timing)/1000;
            item.timeSpent += timeInFocus;
            delete item.timing;
          }
        }

  }])

  .controller("feedbackCtrl", ['$scope', function($scope) {
    $scope.message1 = "";

    $scope.getMsg = function(n, cond){
        responses = {
        satisfy: ["I hated it.", "I didn't like it", "It was OK", "It was great", "I loved it"],
        pay: ["Way too low.", "Lower than I'd like", "It was OK", "Better than usual", "Much better than usual"]
        };
        return responses[cond][n-1];
      };

  }]);

// END
})();
<commit_msg>Logging and debug improvements<commit_after>(function(){

angular.module('crowdy')
 .controller("tagTaskController", ['$http', '$sce', '$httpParamSerializerJQLike', '$log', '$modal', '$scope', '$rootScope', '$routeParams',
         function($http, $sce, $httpParamSerializerJQLike, $log, $modal, $scope, $rootScope, $routeParams) {

    var BACKEND_SERVER = "."; // e.g. http://localhost:3000

    $scope.preview = ($routeParams.assignmentId === 'ASSIGNMENT_ID_NOT_AVAILABLE' );
    $scope.formSubmitTo = $sce.trustAsResourceUrl($routeParams.turkSubmitTo + "/mturk/externalSubmit");
    $scope.assignmentId = $routeParams.assignmentId;

    $rootScope.debug = $routeParams.debug;

    $scope.type = "tagging";
    $scope.taskset = {};
    $scope.taskset.tasks = []; // Initialize empty, set when it's available

    //Modal
    $scope.openModal = function (opts) {
      var modalInstance = $modal.open({
        animation: true,
        templateUrl: 'templates/modal.html',
        controller: 'ModalInstanceCtrl',
        backdrop: 'static',
        size: 'lg',
        resolve: {
          opts: function () {
          return opts
          }
        }
      });
    };

    $scope.toggleAnimation = function () {
      $scope.animationsEnabled = !$scope.animationsEnabled;
    };

    $scope.submitForm = function($event) {
        if ($scope.turkForm.$valid) {
          // Submit form toServer
          $http.post(BACKEND_SERVER+"/save/hit", $scope.taskset)
            .success(function(res){
                $log.log(res);
                PostResultsToAmazon(res, null);
            })
            .error(function(err){
                // Still send results to amazon in case of error
                $log.error(err);
                PostResultsToAmazon($scope.taskset, res);
            });
          // Submit form back to Amazon
        } else {
          // Reload masonry, in case any errors pop up
          $rootScope.$broadcast("masonry.reload");
        }

    };

    PostResultsToAmazon = function(results, errors){
        $scope.hiddenErrors = errors;
        // Add an action to the main form.
        // It couldn't be there before because of interference with our submit method.
        // MTurk requires a post from the client, though.
        angular.element("#turkHiddenForm").submit();
        return;
    };

    // Construct JSON callback
    params = {
      callback: "JSON_CALLBACK",
      user: $scope.preview ? "PREVIEWUSER" : $routeParams.workerId,
      taskset_id:$scope.preview ? "TEST" : $routeParams.hitId,
      hit_id: $routeParams.hit_id,
      assignment_id: $routeParams.assignment_id,
      lock: !($scope.preview)
    };

    var endpoint;
    if ($rootScope.debug) {
        endpoint = 'data/debug-image-hit.json';
       } else {
        endpoint = BACKEND_SERVER + "/hit";
       }

    $http.jsonp(endpoint, {params:params})
     .success(function(data){
        if (data.status && data.status===500){
            $rootScope.error = true;
            $scope.openModal({
                show: { ok: false},
                title: "Error",
                message: data.message
              });
            return;
        }
        $scope.taskset = data.taskset;
        if ($scope.taskset.tasks.length === 0) {
          $rootScope.error = "No tasks";
          $scope.openModal({
            show: { ok: false},
            title: "Out of tasks :(",
            message: "Sorry, we ran out of tasks that are available at the moment.
We're really sorry about that, we know it sucks."
          });
        }
    }).error(function(err){
        $rootScope.error = true;
        console.log(err);
        var msg, title;
        if (data.message){
            title = "Error";
            msg = data.message;
        } else {
            title = "Unknown error.";
            msg = "Sorry, an unknown error occurred. We don't know what happened";
        }
        $scope.openModal({
            show: {ok:false},
            title: title,
            message: msg
        });
    });

  }])

 .controller("tagTaskItemController", ['$http', '$log', '$scope', '$rootScope', '$routeParams',
         function($http, $log, $scope, $rootScope, $routeParams) {
        // Individual Item Controller

        $scope.$watch('tags', function(newValue, oldValue){
          // Only refresh masonry is the value actually changed
          // This also keeps from running on page load
          if (newValue !== oldValue) {
            $rootScope.$broadcast("masonry.reload");
          }
        });

         $scope.tooltip = function(item){
           return "Title: "+item.meta.title+"
Description: "+item.meta.description
         }

        // Individual item timer
        $scope.timeStart = function(item){
          if (!item.timing) {
          item.timing = new Date();
          }
        }

        $scope.timeStop = function(item){
          if (item.timing) {
            timeInFocus = (new Date()-item.timing)/1000;
            item.timeSpent += timeInFocus;
            delete item.timing;
          }
        }

  }])

  .controller("feedbackCtrl", ['$scope', function($scope) {
    $scope.message1 = "";

    $scope.getMsg = function(n, cond){
        responses = {
        satisfy: ["I hated it.", "I didn't like it", "It was OK", "It was great", "I loved it"],
        pay: ["Way too low.", "Lower than I'd like", "It was OK", "Better than usual", "Much better than usual"]
        };
        return responses[cond][n-1];
      };

  }]);

// END
})();
<|endoftext|>


<commit_before>'use strict'

const testWorker = require('./fixtures/worker-tid')
const testWorkerEmitter = testWorker.emitter

// Ponos Tooling
const ponos = require('../../src')
const RabbitMQ = require('../../src/rabbitmq')

const Promise = require('bluebird')

describe('Basic Example', () => {
  let server
  let rabbitmq

  before(() => {
    rabbitmq = new RabbitMQ({})
    const tasks = {
      'ponos-test:one': testWorker
    }
    server = new ponos.Server({ tasks: tasks })
    return server.start()
      .then(() => {
        return rabbitmq.connect()
      })
  })

  after(() => {
    return server.stop()
      .then(() => {
        return rabbitmq.disconnect()
      })
  })

  it('should queue a task that triggers an event', (done) => {
    const job = {
      eventName: 'task',
      message: 'hello world'
    }
    testWorkerEmitter.on('failed', function (err) {
      done(new Error(err.message))
    })
    testWorkerEmitter.on('passed', function () {
      done()
    })
    rabbitmq.publishTask('ponos-test:one', job)
  })
})
<commit_msg>fix lint<commit_after>'use strict'

const testWorker = require('./fixtures/worker-tid')
const testWorkerEmitter = testWorker.emitter

// Ponos Tooling
const ponos = require('../../src')
const RabbitMQ = require('../../src/rabbitmq')

describe('Basic Example', () => {
  let server
  let rabbitmq

  before(() => {
    rabbitmq = new RabbitMQ({})
    const tasks = {
      'ponos-test:one': testWorker
    }
    server = new ponos.Server({ tasks: tasks })
    return server.start()
      .then(() => {
        return rabbitmq.connect()
      })
  })

  after(() => {
    return server.stop()
      .then(() => {
        return rabbitmq.disconnect()
      })
  })

  it('should queue a task that triggers an event', (done) => {
    const job = {
      eventName: 'task',
      message: 'hello world'
    }
    testWorkerEmitter.on('failed', function (err) {
      done(new Error(err.message))
    })
    testWorkerEmitter.on('passed', function () {
      done()
    })
    rabbitmq.publishTask('ponos-test:one', job)
  })
})
<|endoftext|>