<commit_before>define(
    [ "preemptive-task" ],
    function( PreemptiveTask ) {
      return function() {

        module( "PreemptiveTask", {
          setup: function() {},
          teardown: function() {}
        });

        var schedulerApi = {
            insert: function() {},
            remove: function() {}
        };

        var invalidSchedulerApi = {
            foo: function() {},
            bar: function() {}
        };

        test( "start a task", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          schedulerMock.expects( "insert" ).once();

          function taskFunction() {};
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();

          ok( schedulerMock.verify(), "scheduler invocations verified" );
        });

        test( "create a task with invalid scheduler", function() {
          expect( 1 );

          var invalidSchedulerMock = sinon.mock( invalidSchedulerApi );

          function taskFunction() {};

          raises( function() {
            var task = new PreemptiveTask( invalidSchedulerApi, taskFunction );
          }, Error, "exception thrown for invalid scheduler" );
        });

        test( "start a task that's already started", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {};
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();
          raises( function() {
            task.start();
          }, Error, "exception thrown for task already started" );
        });

        test( "task run context is correct", function() {
          expect( 4 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {
            equal( this, task, "this value is correct" );
            ok( this.isRunning, "task is running" );
          };
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          ok( !task.isStarted(), "task is not started" );
          task.start();
          ok( task.isStarted(), "task is started" );
          task.run(); // Bypass the scheduler
        });

        test( "pause a running task", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {
            this.pause();
          };
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();
          task.run(); // Bypass the scheduler

          ok( task.result instanceof Error,
              "exception thrown for task not in blocked state" );
        });

        test( "cancel a running task", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {
            task.cancel();
          };
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();
          task.run(); // Bypass the scheduler

          ok( task.result instanceof Error,
          "exception thrown for task not in blocked state" );
        });

      };
    }
);<commit_msg>More tests.<commit_after>define(
    [ "preemptive-task" ],
    function( PreemptiveTask ) {
      return function() {

        module( "PreemptiveTask", {
          setup: function() {},
          teardown: function() {}
        });

        var schedulerApi = {
            insert: function() {},
            remove: function() {}
        };

        var invalidSchedulerApi = {
            foo: function() {},
            bar: function() {}
        };

        test( "start a task", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          schedulerMock.expects( "insert" ).once();

          function taskFunction() {};
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();

          ok( schedulerMock.verify(), "scheduler invocations verified" );
        });

        test( "create a task with invalid scheduler", function() {
          expect( 1 );

          var invalidSchedulerMock = sinon.mock( invalidSchedulerApi );

          function taskFunction() {};

          raises( function() {
            var task = new PreemptiveTask( invalidSchedulerApi, taskFunction );
          }, Error, "exception thrown for invalid scheduler" );
        });

        test( "start a task that's already started", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {};
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();
          raises( function() {
            task.start();
          }, Error, "exception thrown for task already started" );
        });

        test( "task run context is correct", function() {
          expect( 7 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {
            equal( this, task, "this value is correct" );
            ok( this.isRunning, "task is running" );
          };
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          ok( !task.isRunning(), "task is not running" );
          ok( !task.isStarted(), "task is not started" );
          task.start();
          ok( task.isStarted(), "task is started" );
          task.run(); // Bypass the scheduler
          ok( !task.isRunning(), "task is not running" );
          ok( task.isStarted(), "task is started" );
        });

        test( "pause a running task", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {
            this.pause();
          };
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();
          task.run(); // Bypass the scheduler

          ok( task.result instanceof Error,
              "exception thrown for task not in blocked state" );
        });

        test( "cancel a running task", function() {
          expect( 1 );

          var schedulerMock = sinon.mock( schedulerApi );
          function taskFunction() {
            task.cancel();
          };
          var task = new PreemptiveTask( schedulerApi, taskFunction );

          task.start();
          task.run(); // Bypass the scheduler

          ok( task.result instanceof Error,
          "exception thrown for task not in blocked state" );
        });

      };
    }
);<|endoftext|>


<commit_before>var POLLING_INTERVAL = 3500, // Milliseconds
    VICINITY_STRENGTH = -8, // B/T RSSI
    BUTTON_HOLD_TIME = 2000, // Milliseconds
    DISCONNECTION_DURATION = 24500, // Milliseconds
    CONF_FILE = 'BLUETOOTH-HW.CONF';

var execSync = require('child_process').execSync,
    fs = require("fs"),
    GPIO = require('rpi').GPIO;

var mac = fs.readFileSync(CONF_FILE);

var unlockPin = new GPIO(0, 'out'),
    lockPin = new GPIO(7, 'out');

var changeButton = new GPIO(8, 'in');

var inRange = false,
    lastConnectionTime = 0;

var disconnectionCount = 0;

/*changeButton.on('change', function(value) {
    if (value == 1) {
        console.log("Request to Change Bluetooth Device Received.");
        exec("hcitool scan", function(error, stdout, stderr) {
            console.log(" - Scanning...");
            var mac_addr_line = stdout.split("\n")

            if(mac_addr_line[1] != ""){
                var temp_mac = mac_addr_line[1].split("\t")[1];

                if(temp_mac.length = 17){
                    console.log("   - Device found: " + mac);
                    mac = temp_mac;
                    fs.writeFileSync(CONF_FILE, mac);
                } else {
                    console.log("   - No Device was Found.");
                }
            }
        });
    }
});*/

function switchPower(pin) {
    pin.high();
    setTimeout(function() {
        pin.low();
    }, BUTTON_HOLD_TIME);
}

function cmd() {
    return "hcitool cc " + mac + " && hcitool rssi " + mac;
}

function parseConnectionStrength(resp) {
    var rawRSSI = resp.split(": ")[1];
    console.log("    - raw RSSI: " + rawRSSI);

    if (rawRSSI != "") {
        console.log(Math.round(rawRSSI));
        return Math.round(rawRSSI); // Math.round is applied to convert string to number, returns RSSI from command
    } else {
        console.log(-2056);
        return -2056;               // Device is not is range, return number that is guaranteed to far out of the RSSI range
    }
}

// Probe for Device Presence
setInterval(function() {
    try {
    console.log("Probing for Connection...");
    console.log(" - " + Date.now());
    if (mac.length == 17) {
        console.log(" - Valid MAC Address was found in Config, detecting signal strength.");
        var stdout = execSync(cmd());
        console.log("Stdout: "+stdout);
        var connectionStrength = parseConnectionStrength(stdout);
        console.log(connectionStrength);
        console.log(inRange);
        console.log(VICINITY_STRENGTH);
        // Check if phone is in valid range
        if ((inRange == false) && (connectionStrength > VICINITY_STRENGTH)) {
            console.log(" - Phone is in the disconnected state and device is within preconfigured vicinity.");
            console.log("    - Unlocking Car");
            switchPower(unlockPin);
            console.log("    - Reconfiguring Variables");
            inRange = true;
            lastConnectionTime = Date.now();
            disconnectionCount = 0;
            console.log("       - Connection Time: " + lastConnectionTime);
        }
        // If the signal is weaker than that, treat it as though the phone is not in valid range
        else if ((inRange == true) && (connectionStrength < VICINITY_STRENGTH)) {
            console.log(" - Phone is in the connected state and device is not within preconfigured vicinity.");
            disconnectionCount++;
            console.log("    - Increment Disconnection Count: " + disconnectionCount);
            // Calculate approx. how many times hardware should be probed before disconnect is acknowledged
            if (disconnectionCount >= Math.ceil(DISCONNECTION_DURATION / POLLING_INTERVAL)) {
                console.log("    - Locking Car");
                switchPower(lockPin);
                inRange = false;
            }
        }
    }
    catch(e){
        console.log(e);
    }
    console.log("--------------");
}, POLLING_INTERVAL);<commit_msg>Cleanup<commit_after>var POLLING_INTERVAL = 3500, // Milliseconds
    VICINITY_STRENGTH = -8, // B/T RSSI
    BUTTON_HOLD_TIME = 2000, // Milliseconds
    DISCONNECTION_DURATION = 24500, // Milliseconds
    CONF_FILE = 'BLUETOOTH-HW.CONF';

var execSync = require('child_process').execSync,
    fs = require("fs"),
    GPIO = require('rpi').GPIO;

var mac = fs.readFileSync(CONF_FILE);

var unlockPin = new GPIO(0, 'out'),
    lockPin = new GPIO(7, 'out');

var changeButton = new GPIO(8, 'in');

var inRange = false,
    lastConnectionTime = 0;

var disconnectionCount = 0;

/*changeButton.on('change', function(value) {
    if (value == 1) {
        console.log("Request to Change Bluetooth Device Received.");
        exec("hcitool scan", function(error, stdout, stderr) {
            console.log(" - Scanning...");
            var mac_addr_line = stdout.split("\n")

            if(mac_addr_line[1] != ""){
                var temp_mac = mac_addr_line[1].split("\t")[1];

                if(temp_mac.length = 17){
                    console.log("   - Device found: " + mac);
                    mac = temp_mac;
                    fs.writeFileSync(CONF_FILE, mac);
                } else {
                    console.log("   - No Device was Found.");
                }
            }
        });
    }
});*/

function switchPower(pin) {
    pin.high();
    setTimeout(function() {
        pin.low();
    }, BUTTON_HOLD_TIME);
}

function cmd() {
    return "hcitool cc " + mac + " && hcitool rssi " + mac;
}

function parseConnectionStrength(resp) {
    var rawRSSI = resp.split(": ")[1];
    console.log("    - raw RSSI: " + rawRSSI);

    if (rawRSSI != "") {
        console.log(Math.round(rawRSSI));
        return Math.round(rawRSSI); // Math.round is applied to convert string to number, returns RSSI from command
    } else {
        console.log(-2056);
        return -2056;               // Device is not is range, return number that is guaranteed to far out of the RSSI range
    }
}

// Probe for Device Presence
setInterval(function() {
    try {
        console.log("Probing for Connection...");
        console.log(" - " + Date.now());
        if (mac.length == 17) {
            console.log(" - Valid MAC Address was found in Config, detecting signal strength.");
            var stdout = execSync(cmd());
            console.log("Stdout: "+stdout);
            var connectionStrength = parseConnectionStrength(stdout);
            console.log(connectionStrength);
            console.log(inRange);
            console.log(VICINITY_STRENGTH);
            // Check if phone is in valid range
            if ((inRange == false) && (connectionStrength > VICINITY_STRENGTH)) {
                console.log(" - Phone is in the disconnected state and device is within preconfigured vicinity.");
                console.log("    - Unlocking Car");
                switchPower(unlockPin);
                console.log("    - Reconfiguring Variables");
                inRange = true;
                lastConnectionTime = Date.now();
                disconnectionCount = 0;
                console.log("       - Connection Time: " + lastConnectionTime);
            }
            // If the signal is weaker than that, treat it as though the phone is not in valid range
            else if ((inRange == true) && (connectionStrength < VICINITY_STRENGTH)) {
                console.log(" - Phone is in the connected state and device is not within preconfigured vicinity.");
                disconnectionCount++;
                console.log("    - Increment Disconnection Count: " + disconnectionCount);
                // Calculate approx. how many times hardware should be probed before disconnect is acknowledged
                if (disconnectionCount >= Math.ceil(DISCONNECTION_DURATION / POLLING_INTERVAL)) {
                    console.log("    - Locking Car");
                    switchPower(lockPin);
                    inRange = false;
                }
            }
        }
    }
    catch(e){
        console.log(e);
    }
    console.log("--------------");
}, POLLING_INTERVAL);<|endoftext|>


<commit_before>//optimze modules using https://github.com/gulpjs/plugins/blob/master/src/blackList.json
'use strict';

var LIVERELOAD_PORT = 35729;
var SERVER_PORT = 9001;
var Proxy = require('gulp-connect-proxy');
var pngquant = require('imagemin-pngquant');
var lrSnippet = require('connect-livereload')({
  port: LIVERELOAD_PORT
});
var mountFolder = function(connect, dir) {
  return connect.static(require('path').resolve(dir));
};

var gulp = require('gulp',{
  base: 'Gulpfile.js'
});

var del = require('del');

var gulpLoadPlugins = require('gulp-load-plugins');
var plugins = gulpLoadPlugins({
  pattern: ['gulp-*'],
  lazy: true,
  camelize: true
});

var files = [
  'app/*.html',
  'app/scripts/**/*.js'
];

gulp.task('less', function() {
  return gulp.src('app/styles/main.less')
  .pipe(plugins.less())
  .pipe(gulp.dest('.tmp/styles'))
  .pipe(plugins.connect.reload());
});

gulp.task('karma', function() {
  gulp.src('test.js')
  .pipe(plugins.karma({
    configFile: 'karma.conf.js',
    action: 'run',
    browsers: ['PhantomJS'],
    singleRun: true,
    coverageReporter: {
      dir: 'coverage',
      reporters: [
      {type: 'html', subdir: 'report-html'},
      {type: 'cobertura', subdir: '.', file: 'cobertura.txt'},
      {type: 'text', subdir: '.', file: 'text.txt'},
      {type: 'text-summary', subdir: '.', file: 'text-summary.txt'}
      ]
    }
  }))
  .pipe(plugins.exit())
  .on('error', function(err) {
    throw err;
  });
});

gulp.task('karma:browser', function() {
  gulp.src('test.js')
  .pipe(plugins.karma({
    configFile: 'karma.conf.js',
    action: 'run',
    browsers: ['PhantomJS', 'Chrome', 'Firefox'],
    singleRun: true,
    coverageReporter: {
      dir: 'coverage',
      reporters: [
      {type: 'html', subdir: 'report-html'},
      {type: 'cobertura', subdir: '.', file: 'cobertura.txt'},
      {type: 'text', subdir: '.', file: 'text.txt'},
      {type: 'text-summary', subdir: '.', file: 'text-summary.txt'}
      ]
    }
  }))
  .pipe(plugins.exit())
  .on('error', function(err) {
    throw err;
  });
});

gulp.task('jshint', function() {
  gulp.src(['app/scripts/**/*.js', 'test/spec/**/*.js', 'Gulpfile.js'])
  .pipe(plugins.jshint())
  .pipe(plugins.jshint.reporter('jshint-stylish'));
});

gulp.task('jscs', function() {
  gulp.src([
    'Gulpfile.js',
    'app/scripts/*',
    'test/spec/{,*/}*.js'
  ])
  .pipe(plugins.jscs({configPath: '.jscsrc'}))
  .pipe(plugins.jscsStylish());
});

gulp.task('watch', ['templates', 'less'], function() {
  gulp.watch('app/scripts/**/*.hbs', ['templates']);
  gulp.watch('app/styles/{,*/}*.less', ['less']);
  gulp.watch(files, ['clean-reload']);
});

gulp.task('clean-reload', function() {
  gulp.src(files)
  .pipe(plugins.connect.reload());
});

gulp.task('connect', function() {
  plugins.connect.server({
    root: 'app',
    livereload: true,
    port: SERVER_PORT,
    hostname: '0.0.0.0',
    proxies: [{
      context: ['/api'],
      host: 'localhost',
      port: 8081
    }, {
      context: ['/socket.io'],
      host: 'localhost',
      port: 8081,
      ws: true
    }],
    middleware: function(connect, opt) {
      var proxy = new Proxy(opt);
      return [
      proxy,
      lrSnippet,
      mountFolder(connect, '.tmp'),
      mountFolder(connect, 'app')
      ];
    }
  });
});

gulp.task('open', function() {
  gulp.src('').pipe(plugins.open({
    uri: 'http://localhost:9001'
  }));
});

gulp.task('clean', function() {
  return del(['.tmp/', 'dist']);
});

gulp.task('jsbeautifier', function() {
  gulp.src(['Gulpfile.js', 'app/scripts/{*/}*.js'])
  .pipe(plugins.prettify({config: '.jsbeautifyrc'}))
  .pipe(plugins.exit());
});

gulp.task('usemin', function() {
  gulp.src('app/scripts/{*/}*.html')
  .pipe(plugins.usemin({
    css: [plugins.minifyCss(), 'concat'],
    html: [plugins.minifyHtml()],
    js: [plugins.uglify(), plugins.rev()]
  }))
  .pipe(gulp.dest('dist'));
});

gulp.task('imagemin', function() {
  gulp.src('app/images/*')
  .pipe(plugins.imagemin({
    progressive: true,
    svgoPlugins: [{removeViewBox: false}],
    use: [pngquant()]
  }))
  .pipe(gulp.dest('dist/images'));
});

gulp.task('minify-css', ['copy'], function() {
  gulp.src('.tmp/styles/*.css')
  .pipe(plugins.minifyCss())
  .pipe(gulp.dest('dist/styles'));
});

gulp.task('minify-html', function() {
  gulp.src('app/scripts/{*/}*.html')
  .pipe(plugins.minifyHtml({collapseWhitespace: true}))
  .pipe(gulp.dest('dist'));
});

gulp.task('copy', ['requirejs'], function() {
  gulp.src([
    'app/*.{ico,txt}',
    'app/.htaccess',
    'app/jsondata/*.*',
    'app/images/*.*',
    'app/bower_components/font-awesome/fonts/{,*/}*.*',
    'app/bower_components/modernizr/modernizr.js',
    'app/bower_components/requirejs/*.js',
    'app/index.html'
  ], {base: 'app'})
  .pipe(gulp.dest('dist'));
});

gulp.task('bower', function() {
  plugins.bower()
  .pipe(gulp.dest('app/bower_components'));
});

gulp.task('templates', function() {
  return gulp.src('app/scripts/**/*.hbs')
    .pipe(plugins.handlebars())
    .pipe(plugins.wrap('Handlebars.template(<%= contents %>)'))
    .pipe(plugins.declare({
      namespace: 'JST',
      noRedeclare: true, // Avoid duplicate declarations
      //make handlebars namespace compliant with grunt version
      processName: function(filePath) {
        filePath = 'app/scripts/apps' + filePath.replace(/\\/g, '/').split(/app\/scripts\/apps/)[1];
        filePath = filePath.substring(0, filePath.length - 3) + '_hbs';

        return filePath;
      }
    }))
    .pipe(plugins.concat('templates.js'))
    //make handlebars file names compliant with grunt version
    .pipe(plugins.replace(/_hbs/g, '.hbs'))
      //make templates amd compatible
    .pipe(plugins.wrap('define([\'handlebars\'], function(Handlebars) { <%= contents %> return this["JST"]; });'))

    .pipe(gulp.dest('.tmp/scripts/'))
    .pipe(plugins.connect.reload());
});

gulp.task('requirejs', ['templates'], function() {
  gulp.src(['app/scripts/main.js'])
    .pipe(plugins.requirejsOptimize({
      baseUrl: 'app/scripts',
      out: 'main.js',
      name: 'main',
      mainConfigFile: 'app/scripts/main.js',
      optimize: 'uglify',
      paths: {
        'templates': '../../.tmp/scripts/templates'
      }
    }))
    .pipe(gulp.dest('dist/scripts'));
});

gulp.task('serve', [
  'clean',
  'analyze',
  'connect',
  'open',
  'watch'
]);

gulp.task('test', ['test:karma']);

gulp.task('test:browser', [
  'templates',
  'karma:browser'
]);

gulp.task('test:karma', [
  'templates',
  'karma'
]);

gulp.task('build', [
  'clean',
  'analyze',
  'less',
  'requirejs',
  'imagemin',
  'copy',
  'usemin',
  'minify-css'
]);

gulp.task('default', [
  'analyze',
  'test',
  'build'
]);

gulp.task('beautify', [
  'jsbeautifier:modify',
  'analyze'
]);

gulp.task('serve:alias', [
  'serve'
]);

gulp.task('analyze', [
  'jshint',
  'jscs'
]);
<commit_msg>Fixed gulp style minification<commit_after>//optimze modules using https://github.com/gulpjs/plugins/blob/master/src/blackList.json
'use strict';

var LIVERELOAD_PORT = 35729;
var SERVER_PORT = 9001;
var Proxy = require('gulp-connect-proxy');
var pngquant = require('imagemin-pngquant');
var lrSnippet = require('connect-livereload')({
  port: LIVERELOAD_PORT
});
var mountFolder = function(connect, dir) {
  return connect.static(require('path').resolve(dir));
};

var gulp = require('gulp',{
  base: 'Gulpfile.js'
});

var del = require('del');

var gulpLoadPlugins = require('gulp-load-plugins');
var plugins = gulpLoadPlugins({
  pattern: ['gulp-*'],
  lazy: true,
  camelize: true
});

var files = [
  'app/*.html',
  'app/scripts/**/*.js'
];

gulp.task('less', function() {
  return gulp.src('app/styles/main.less')
  .pipe(plugins.less())
  .pipe(gulp.dest('.tmp/styles'))
  .pipe(plugins.connect.reload());
});

gulp.task('karma', function() {
  gulp.src('test.js')
  .pipe(plugins.karma({
    configFile: 'karma.conf.js',
    action: 'run',
    browsers: ['PhantomJS'],
    singleRun: true,
    coverageReporter: {
      dir: 'coverage',
      reporters: [
      {type: 'html', subdir: 'report-html'},
      {type: 'cobertura', subdir: '.', file: 'cobertura.txt'},
      {type: 'text', subdir: '.', file: 'text.txt'},
      {type: 'text-summary', subdir: '.', file: 'text-summary.txt'}
      ]
    }
  }))
  .pipe(plugins.exit())
  .on('error', function(err) {
    throw err;
  });
});

gulp.task('karma:browser', function() {
  gulp.src('test.js')
  .pipe(plugins.karma({
    configFile: 'karma.conf.js',
    action: 'run',
    browsers: ['PhantomJS', 'Chrome', 'Firefox'],
    singleRun: true,
    coverageReporter: {
      dir: 'coverage',
      reporters: [
      {type: 'html', subdir: 'report-html'},
      {type: 'cobertura', subdir: '.', file: 'cobertura.txt'},
      {type: 'text', subdir: '.', file: 'text.txt'},
      {type: 'text-summary', subdir: '.', file: 'text-summary.txt'}
      ]
    }
  }))
  .pipe(plugins.exit())
  .on('error', function(err) {
    throw err;
  });
});

gulp.task('jshint', function() {
  gulp.src(['app/scripts/**/*.js', 'test/spec/**/*.js', 'Gulpfile.js'])
  .pipe(plugins.jshint())
  .pipe(plugins.jshint.reporter('jshint-stylish'));
});

gulp.task('jscs', function() {
  gulp.src([
    'Gulpfile.js',
    'app/scripts/*',
    'test/spec/{,*/}*.js'
  ])
  .pipe(plugins.jscs({configPath: '.jscsrc'}))
  .pipe(plugins.jscsStylish());
});

gulp.task('watch', ['templates', 'less'], function() {
  gulp.watch('app/scripts/**/*.hbs', ['templates']);
  gulp.watch('app/styles/{,*/}*.less', ['less']);
  gulp.watch(files, ['clean-reload']);
});

gulp.task('clean-reload', function() {
  gulp.src(files)
  .pipe(plugins.connect.reload());
});

gulp.task('connect', function() {
  plugins.connect.server({
    root: 'app',
    livereload: true,
    port: SERVER_PORT,
    hostname: '0.0.0.0',
    proxies: [{
      context: ['/api'],
      host: 'localhost',
      port: 8081
    }, {
      context: ['/socket.io'],
      host: 'localhost',
      port: 8081,
      ws: true
    }],
    middleware: function(connect, opt) {
      var proxy = new Proxy(opt);
      return [
      proxy,
      lrSnippet,
      mountFolder(connect, '.tmp'),
      mountFolder(connect, 'app')
      ];
    }
  });
});

gulp.task('open', function() {
  gulp.src('').pipe(plugins.open({
    uri: 'http://localhost:9001'
  }));
});

gulp.task('clean', function() {
  return del(['.tmp/', 'dist']);
});

gulp.task('jsbeautifier', function() {
  gulp.src(['Gulpfile.js', 'app/scripts/{*/}*.js'])
  .pipe(plugins.prettify({config: '.jsbeautifyrc'}))
  .pipe(plugins.exit());
});

gulp.task('usemin', function() {
  gulp.src('app/scripts/{*/}*.html')
  .pipe(plugins.usemin({
    css: [plugins.minifyCss(), 'concat'],
    html: [plugins.minifyHtml()],
    js: [plugins.uglify(), plugins.rev()]
  }))
  .pipe(gulp.dest('dist'));
});

gulp.task('imagemin', function() {
  gulp.src('app/images/*')
  .pipe(plugins.imagemin({
    progressive: true,
    svgoPlugins: [{removeViewBox: false}],
    use: [pngquant()]
  }))
  .pipe(gulp.dest('dist/images'));
});

gulp.task('minify-css', ['copy'], function() {
  gulp.src('.tmp/styles/*.css')
  .pipe(plugins.minifyCss({advanced: false}))
  .pipe(gulp.dest('dist/styles'));
});

gulp.task('minify-html', function() {
  gulp.src('app/scripts/{*/}*.html')
  .pipe(plugins.minifyHtml({collapseWhitespace: true}))
  .pipe(gulp.dest('dist'));
});

gulp.task('copy', ['requirejs'], function() {
  gulp.src([
    'app/*.{ico,txt}',
    'app/.htaccess',
    'app/jsondata/*.*',
    'app/images/*.*',
    'app/bower_components/font-awesome/fonts/{,*/}*.*',
    'app/bower_components/modernizr/modernizr.js',
    'app/bower_components/requirejs/*.js',
    'app/index.html'
  ], {base: 'app'})
  .pipe(gulp.dest('dist'));
});

gulp.task('bower', function() {
  plugins.bower()
  .pipe(gulp.dest('app/bower_components'));
});

gulp.task('templates', function() {
  return gulp.src('app/scripts/**/*.hbs')
    .pipe(plugins.handlebars())
    .pipe(plugins.wrap('Handlebars.template(<%= contents %>)'))
    .pipe(plugins.declare({
      namespace: 'JST',
      noRedeclare: true, // Avoid duplicate declarations
      //make handlebars namespace compliant with grunt version
      processName: function(filePath) {
        filePath = 'app/scripts/apps' + filePath.replace(/\\/g, '/').split(/app\/scripts\/apps/)[1];
        filePath = filePath.substring(0, filePath.length - 3) + '_hbs';

        return filePath;
      }
    }))
    .pipe(plugins.concat('templates.js'))
    //make handlebars file names compliant with grunt version
    .pipe(plugins.replace(/_hbs/g, '.hbs'))
      //make templates amd compatible
    .pipe(plugins.wrap('define([\'handlebars\'], function(Handlebars) { <%= contents %> return this["JST"]; });'))

    .pipe(gulp.dest('.tmp/scripts/'))
    .pipe(plugins.connect.reload());
});

gulp.task('requirejs', ['templates'], function() {
  gulp.src(['app/scripts/main.js'])
    .pipe(plugins.requirejsOptimize({
      baseUrl: 'app/scripts',
      out: 'main.js',
      name: 'main',
      mainConfigFile: 'app/scripts/main.js',
      optimize: 'uglify',
      paths: {
        'templates': '../../.tmp/scripts/templates'
      }
    }))
    .pipe(gulp.dest('dist/scripts'));
});

gulp.task('serve', [
  'clean',
  'analyze',
  'connect',
  'open',
  'watch'
]);

gulp.task('test', ['test:karma']);

gulp.task('test:browser', [
  'templates',
  'karma:browser'
]);

gulp.task('test:karma', [
  'templates',
  'karma'
]);

gulp.task('build', [
  'clean',
  'analyze',
  'less',
  'requirejs',
  'imagemin',
  'copy',
  'usemin',
  'minify-css'
]);

gulp.task('default', [
  'analyze',
  'test',
  'build'
]);

gulp.task('beautify', [
  'jsbeautifier:modify',
  'analyze'
]);

gulp.task('serve:alias', [
  'serve'
]);

gulp.task('analyze', [
  'jshint',
  'jscs'
]);
<|endoftext|>


<commit_before>

var net = require('net');
var sock;
var tcpcon;
var client;
var connected = false;
var buffer;
server = net.createServer(function(c) {
//server.on('connection', function (socket) {
	sock = c;
	console.log('connections');
	client = 	net.createConnection('5901','96.31.76.142',
	function() { //'connect' listener
		console.log('client connected');
		connected = true;
		client.on('data', function(data) {
	//		console.log('data received:'+data);
		//	sock.send(new Buffer(data,'binary').toString('base64'));
			sock.write(data);
		});
		client.on('end', function() {
		sock.end();
		console.log('client disconnected');
		});

	});

	sock.on('data', function (message) {
//	console.log(message);
//	buffer= new Buffer(message,'base64');
	if(connected == true)
	{
		//client.write(new Buffer(message,'base64'));
		client.write(message);
	}
	else
	{
		setTimeout('sendLater()',500);
	}
	});
	sock.on('end', function () {
	if(connected)
	{
		client.end();
	}
	});
});

function sendLater()
{

if(connected)
{
	client.write(buffer);
}
else
{
	setTimeout('sendLater()',500);
}
}
server.listen('3381','127.0.0.1');
<commit_msg>wrong repo for this file<commit_after><|endoftext|>


<commit_before>'use strict';

const CONSTANTS = require('./../constants');

const assignWant = (data, message) => {
	let reply = '';
	let wantedMon = message.content.split(' ').slice(-1)[0].toLowerCase();

	wantedMon = CONSTANTS.standardizePokemonName(wantedMon);

	if (CONSTANTS.MONS.indexOf(wantedMon) === -1 && CONSTANTS.RAIDMONS.indexOf(wantedMon) === -1 && CONSTANTS.LEGENDARYMONS.indexOf(wantedMon) === -1 &&
		CONSTANTS.SPECIALMONS.indexOf(wantedMon) === -1 && CONSTANTS.SPECIALRAIDS.indexOf(wantedMon) === -1 &&
		CONSTANTS.EGGTIERS.indexOf(wantedMon) === -1 && CONSTANTS.QUESTREWARDS.indexOf(wantedMon) === -1) {
		reply = 'I\'m sorry, I can\'t find ' + wantedMon + '. Remember you can only type one pokemon\'s name at a time. Type **!want pokemonName** where pokemonName is one item in any of the lists below:' +
				'\n**Legendary Pokemon**: ' + CONSTANTS.LEGENDARYMONS.join('|') +
				'\n**Egg Tiers**: ' + CONSTANTS.EGGTIERS.join('|') +
				'\n**Quest Rewards**: ' + CONSTANTS.QUESTREWARDS.join('|') +
				'\n**Raid Boss Pokemon**: ' + CONSTANTS.RAIDMONS.join('|') +
				'\n**Wild Pokemon**: ' + CONSTANTS.MONS.join('|') +
				'\n**Special Case**: ' + CONSTANTS.SPECIALMONS.join('|') +
				'\n**Special Raids**: ' + CONSTANTS.SPECIALRAIDS.join('|') +
				'\nWhere *legendary* is any legendary pokemon' +
				'\nWhere *exgym* is a raid at an EX-raid eligible gym' +
				'\nWhere *highiv* is a wild rare spawn that a user finds that is *amazing*, a *wonder*, or *can battle with the best of them*' +
				'\nWhere *finalevo* is a wild spawn of a final evolution';
		message.channel.send(reply);
		return reply;
	}

	var currWantsMon = false;
	if (message.member.roles) {
		message.member.roles.forEach( (role) => {
			if (!currWantsMon && role.name === wantedMon) {
				currWantsMon = true;
			}
		});
	}

	if (!currWantsMon) {
		message.member.addRole(data.rolesByName[wantedMon]);
		reply = 'OK ' + message.member.displayName + '! I will let you know when someone reports a ' + wantedMon;
		if (CONSTANTS.SPECIALRAIDS.indexOf(wantedMon) !== -1 ||  CONSTANTS.EGGTIERS.indexOf(wantedMon) !== -1) {
			reply += ' raid.';
		} else if (CONSTANTS.QUESTREWARDS.indexOf(wantedMon) !== -1) {
			reply += ' quest.';
		} else {
			reply += ' in the wild or as a raid boss.';
		}
		reply += '\nRemember you can **run this command again to stop alerts** for ' + wantedMon + '.';

	} else {
		message.member.removeRole(data.rolesByName[wantedMon]);
		reply = 'Oh? I will ignore ' + wantedMon + ' for you, ' + message.member.displayName;
	}

	message.channel.send(reply);
	return reply;
};

module.exports = (data) => ( (message) => {
	return assignWant(data, message);
});
<commit_msg>Added description of shinycheck and pvp to want.js<commit_after>'use strict';

const CONSTANTS = require('./../constants');

const assignWant = (data, message) => {
	let reply = '';
	let wantedMon = message.content.split(' ').slice(-1)[0].toLowerCase();

	wantedMon = CONSTANTS.standardizePokemonName(wantedMon);

	if (CONSTANTS.MONS.indexOf(wantedMon) === -1 && CONSTANTS.RAIDMONS.indexOf(wantedMon) === -1 && CONSTANTS.LEGENDARYMONS.indexOf(wantedMon) === -1 &&
		CONSTANTS.SPECIALMONS.indexOf(wantedMon) === -1 && CONSTANTS.SPECIALRAIDS.indexOf(wantedMon) === -1 &&
		CONSTANTS.EGGTIERS.indexOf(wantedMon) === -1 && CONSTANTS.QUESTREWARDS.indexOf(wantedMon) === -1 && CONSTANTS.PVP.indexOf(wantedMon) === -1) {
		reply = 'I\'m sorry, I can\'t find ' + wantedMon + '. Remember you can only type one pokemon\'s name at a time. Type **!want pokemonName** where pokemonName is one item in any of the lists below:' +
				'\n**Legendary Pokemon**: ' + CONSTANTS.LEGENDARYMONS.join('|') +
				'\n**Egg Tiers**: ' + CONSTANTS.EGGTIERS.join('|') +
				'\n**Quest Rewards**: ' + CONSTANTS.QUESTREWARDS.join('|') +
				'\n**Raid Boss Pokemon**: ' + CONSTANTS.RAIDMONS.join('|') +
				'\n**Wild Pokemon**: ' + CONSTANTS.MONS.join('|') +
				'\n**Special Case**: ' + CONSTANTS.SPECIALMONS.join('|') +
				'\n**Special Raids**: ' + CONSTANTS.SPECIALRAIDS.join('|') +
				'\n**PVP**: ' + CONSTANTS.PVP.join('|') +
				'\nWhere *legendary* is any legendary pokemon' +
				'\nWhere *exgym* is a raid at an EX-raid eligible gym' +
				'\nWhere *highiv* is a wild rare spawn that a user finds that is *amazing*, a *wonder*, or *can battle with the best of them*' +
				'\nWhere *finalevo* is a wild spawn of a final evolution' +
				'\nWhere *shinycheck* is a Pokemon can *potentially* be shiny upon the encounter.' ;
		message.channel.send(reply);
		return reply;
	}

	var currWantsMon = false;
	if (message.member.roles) {
		message.member.roles.forEach( (role) => {
			if (!currWantsMon && role.name === wantedMon) {
				currWantsMon = true;
			}
		});
	}

	if (!currWantsMon) {
		message.member.addRole(data.rolesByName[wantedMon]);
		reply = 'OK ' + message.member.displayName + '! I will let you know when someone reports a ' + wantedMon;
		if (CONSTANTS.SPECIALRAIDS.indexOf(wantedMon) !== -1 ||  CONSTANTS.EGGTIERS.indexOf(wantedMon) !== -1) {
			reply += ' raid.';
		} else if (CONSTANTS.QUESTREWARDS.indexOf(wantedMon) !== -1) {
			reply += ' quest.';
		} else {
			reply += ' in the wild or as a raid boss.';
		}
		reply += '\nRemember you can **run this command again to stop alerts** for ' + wantedMon + '.';

	} else {
		message.member.removeRole(data.rolesByName[wantedMon]);
		reply = 'Oh? I will ignore ' + wantedMon + ' for you, ' + message.member.displayName;
	}

	message.channel.send(reply);
	return reply;
};

module.exports = (data) => ( (message) => {
	return assignWant(data, message);
});
<|endoftext|>


<commit_before>var $ui = $ui || {};

/**
Create a new checkbox control

HTML:

	<input type='checkbox' id='checkbox' />

Javascript:

	$ui.checkbox({
		element: document.getElementById('checkbox'),
		label: 'Checked',
		value: true
	});

@class $ui.checkbox
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to control
@param [options.value=0] {String} Value of initially selected option, defaults to the attribute value set on the passed element, or `0`
@param [options.name=ui-checkbox-RandInt] {String} Name of underlying input control, defaults to the attribute value set on the passed element, or `ui-checkbox-RandInt`
@param [options.label=label] {String} String to use for the control label, defaults to the attribute value set on the passed element, or its `innerHTML`
@param [options.tabindex=0] {Number} Tabindex of control, defaults to the attribute value set on the passed element, or `0`
@param [options.disabled=false] {Boolean} Disabled state of control, defaults to the attribute value set on the passed element, or `false`
@param [options.listeners] {Object} Object array of event listeners to bind to underlying input(s)
@return Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function($ui) {
    $ui.checkbox = function(opt) {
        var el = opt.element,
            //    listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputValue = opt.value || el.getAttribute('value') || 0,
            inputLabel = opt.label || el.getAttribute('label') || el.innerHTML,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputName = opt.name || el.getAttribute('name') || 'ui-checkbox-' + $ui.getRand(1, 999),
            listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        /*jshint multistr:true */
        var str = "<label class='ui-checkbox' for='" + inputName + "'>\
		<input type = 'checkbox'  id = '" + inputName + "'  name = '" + inputName + "'  value = '" + inputValue + "'  tabindex = '" + inputTabIndex + "' / >\
            <span class = 'ui-label' > " + inputLabel + " </span>\
		</label>";
        el.innerHTML = '';
        el = $ui.replaceEl(el, str);
        /**
        Gets or sets control value
        @method val
        @param [value] {String} Value to set
        @return {String} Returns current value
        */

        /**
        Gets or sets control disabled state
        @method disabled
        @param [boolean] {Boolean} Disabled state
        @return {Boolean} Returns disabled state
        */
        var obj = {
            0: el,
            val: function(val) {
                if (val === undefined) {
                    return inputValue;
                }
                $ui.attribute(el.children[0], 'checked', Boolean(val));
            },
            disabled: function(val) {
                if (val !== undefined) {
                    $ui.toggleClass(el, 'ui-disabled', Boolean(val));
                    $ui.attribute(el.children[0], 'disabled', Boolean(val));
                }
                return $ui.attribute(el.children[0], 'disabled');
            }
        };
        obj.val(inputValue);
        if (inputDisabled) {
            obj.disabled(true);
        }
        $ui.bindListeners(listeners, el.children[0]);
        return obj;
    };
    return $ui;
})($ui);
<commit_msg>Update checkbox.js<commit_after>var $ui = $ui || {};

/**
Create a new checkbox control

HTML:

	<input type='checkbox' id='checkbox' />

Javascript:

	$ui.checkbox({
		element: document.getElementById('checkbox'),
		label: 'Checked',
		value: true
	});

@class $ui.checkbox
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to control
@param [options.value=0] {String} Value of initially selected option, defaults to the attribute value set on the passed element, or `0`
@param [options.name=ui-checkbox-RandInt] {String} Name of underlying input control, defaults to the attribute value set on the passed element, or `ui-checkbox-RandInt`
@param [options.label=label] {String} String to use for the control label, defaults to the attribute value set on the passed element, or its `innerHTML`
@param [options.tabindex=0] {Number} Tabindex of control, defaults to the attribute value set on the passed element, or `0`
@param [options.disabled=false] {Boolean} Disabled state of control, defaults to the attribute value set on the passed element, or `false`
@param [options.listeners] {Object} Object array of event listeners to bind to underlying input(s)
@return Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function($ui) {
    $ui.checkbox = function(opt) {

        var el = opt.element;
		opt=$ui.inputCtrlMeta(opt, 'checkbox');

		str=($ui.compile('checkbox', opt));

        el.innerHTML = '';
        el = $ui.replaceEl(el, str);
        /**
        Gets or sets control value
        @method val
        @param [value] {String} Value to set
        @return {String} Returns current value
        */

        /**
        Gets or sets control disabled state
        @method disabled
        @param [boolean] {Boolean} Disabled state
        @return {Boolean} Returns disabled state
        */
        var obj = {
            0: el,
            val: function(val) {
                if (val === undefined) {
                    return opt.value;
                }
                $ui.attribute(el.children[0], 'checked', Boolean(val));
            },
            disabled: function(val) {
                if (val !== undefined) {
                    $ui.toggleClass(el, 'ui-disabled', Boolean(val));
                    $ui.attribute(el.children[0], 'disabled', Boolean(val));
                }
                return $ui.attribute(el.children[0], 'disabled');
            }
        };
        obj.val(opt.value);
        if (opt.disabled) {
            obj.disabled(true);
        }
        if(opt.listeners){$ui.bindListeners(listeners, el.children[0]);}
        return obj;
    };
    return $ui;
})($ui);
<|endoftext|>


<commit_before>const Mailjet = require('./mailjet-client')

const client = new Mailjet(
  process.env.MJ_APIKEY_PUBLIC,
  process.env.MJ_APIKEY_PRIVATE
)

client.delete('contact').id('23539759').request()
  .then(e => console.log(e.body))
  .catch(e => console.log(e))
<commit_msg>delete send.js<commit_after><|endoftext|>


<commit_before>var hasOwnProperty = Object.prototype.hasOwnProperty;

var Namespace = function(name, owner) {
    this.name = name;
    this.owner = owner;
    this.methods = Object.create(null);
};

Namespace.prototype = {
    isMethodProvided: function(methodName) {
        return hasOwnProperty.call(this.methods, methodName);
    },
    provide: function(methodName, fn) {
        if (typeof methodName === 'string') {
            if (typeof fn === 'function') {
                this.methods[methodName] = fn;
            }
        } else {
            var methods = methodName;
            for (methodName in methods) {
                if (hasOwnProperty.call(methods, methodName) &&
                    typeof methods[methodName] === 'function') {
                    this.methods[methodName] = methods[methodName];
                }
            }
        }
    },
    revoke: function(methodName) {
        if (Array.isArray(methodName)) {
            methodName.forEach(this.revoke, this);
        } else {
            if (hasOwnProperty.call(this.methods, methodName)) {
                delete this.methods[methodName];
            }
        }
    },
    callRemote: function(method/*, ...args, callback*/) {
        var args = Array.prototype.slice.call(arguments, 1);
        var callback = null;

        if (args.length && typeof args[args.length - 1] === 'function') {
            callback = args.pop();
        }

        Namespace.send(this.owner, [{
            type: 'call',
            ns: this.name,
            method: method,
            args: args
        }, callback]);
    }
};

Namespace.invoke = function invoke(namespace, method, args, callback) {
    if (typeof callback === 'function') {
        args = args.concat(callback);
    }

    namespace.methods[method].apply(null, args);
};

Namespace.send = function send(owner, args) {
    for (var channel in owner.channels) {
        if (typeof owner.channels[channel] === 'function') {
            owner.channels[channel].apply(null, args);
        }
    }
};

module.exports = Namespace;
<commit_msg>make callback call safe when callback is not pass to remote method<commit_after>var hasOwnProperty = Object.prototype.hasOwnProperty;

var Namespace = function(name, owner) {
    this.name = name;
    this.owner = owner;
    this.methods = Object.create(null);
};

Namespace.prototype = {
    isMethodProvided: function(methodName) {
        return hasOwnProperty.call(this.methods, methodName);
    },
    provide: function(methodName, fn) {
        if (typeof methodName === 'string') {
            if (typeof fn === 'function') {
                this.methods[methodName] = fn;
            }
        } else {
            var methods = methodName;
            for (methodName in methods) {
                if (hasOwnProperty.call(methods, methodName) &&
                    typeof methods[methodName] === 'function') {
                    this.methods[methodName] = methods[methodName];
                }
            }
        }
    },
    revoke: function(methodName) {
        if (Array.isArray(methodName)) {
            methodName.forEach(this.revoke, this);
        } else {
            if (hasOwnProperty.call(this.methods, methodName)) {
                delete this.methods[methodName];
            }
        }
    },
    callRemote: function(method/*, ...args, callback*/) {
        var args = Array.prototype.slice.call(arguments, 1);
        var callback = null;

        if (args.length && typeof args[args.length - 1] === 'function') {
            callback = args.pop();
        }

        Namespace.send(this.owner, [{
            type: 'call',
            ns: this.name,
            method: method,
            args: args
        }, callback]);
    }
};

Namespace.invoke = function invoke(namespace, method, args, callback) {
    // add a callback to args even if no callback, to avoid extra checking
    // that callback is passed by remote side
    args = args.concat(callback === 'function' ? callback : function() {});

    // invoke the provided remote method
    namespace.methods[method].apply(null, args);
};

Namespace.send = function send(owner, args) {
    for (var channel in owner.channels) {
        if (typeof owner.channels[channel] === 'function') {
            owner.channels[channel].apply(null, args);
        }
    }
};

module.exports = Namespace;
<|endoftext|>


<commit_before>/**
 * Paginator class module
 * @module classes/Paginator
 */

'use strict';

// var _ = require('lodash');
var Display = require('./Display');
var Page = require('./Page');
var parser = require('./paginator/parser');

var errors = require('./paginator/errors'),
  InvalidPageRankError = errors.InvalidPageRankError;

/**
 * Paginator is the page manager
 * @constructor
 * @param {string} pageFormatLabel The label of the paper format for all pages. For example, 'A4'
 * @param {string} pageOrientation The label of the orientation for all pages. May be 'portait' or 'landscape'
 * @param {DOMDocument} doc The document given by editor.getDoc() of the tinymce API
 *
 * @example
 paginator = new Paginator('A4','portait', editor.getDoc());
 *
 * @see utils/page-formats
 */
function Paginator(pageFormatLabel, pageOrientation, ed){

  editor = ed;
  /**
   * The DOMDocument given in the constructor
   * @property {DOMDocument}
   * @private
   */
  this._document = ed.getDoc();
  /**
   * The Display to manage screen and dimensions
   * @property {Display}
   * @private
   */
  this._display = new Display(this._document);
  /**
   * The default abstract page from all real pages inherits
   * @property {Page}
   * @private
   */
  this._defaultPage = new Page(pageFormatLabel, pageOrientation);
  /**
   * The body element of the full document
   * @property {Element}
   * @private
   */
  this._body = this._document.getElementsByTagName('body');

}

/**
 * The current page
 * @property {Page}
 * @private
 */
var currentPage;

/**
 * The list of pages
 * @property {Array}
 * @private
 */
var pages = [];

/**
 * Current editor
 * @property {Editor}
 * @private
 */
var editor;

/**
 * Get the current page
 * @method
 * @return {Page} the current page loaded in editor
 */
Paginator.prototype.getCurrentPage = function(){
  return currentPage;
};

/**
 * Get the page with the given rank
 * @method
 * @param {Number} rank The requested page rank
 * @return {Page} The requested page
 */
Paginator.prototype.getPage = function(rank){
  if (!pages.length)
    throw new Error('Paginator pages length in null. Can\'t iterate on it.');

  var isLower = rank-1 < 0;
  var isGreater = rank-1 > pages.length;

  if (isLower || isGreater) throw new InvalidPageRankError(rank);
  else return pages[rank-1];
};

/**
 * Get all pages in paginator
 * @method
 * @return {Array<Page>} all paginator pages
 */
Paginator.prototype.getPages = function(){
  return pages;
};

/**
 * Return the previous page
 * @method
 * @return {Page} The previous page
 */
Paginator.prototype.getPrevious = function(){
  try {
    console.log('this.getCurrentPage()',currentPage);
    return this.getPage(this.getCurrentPage().rank-1);
  } catch(err) {
    console.error(err.stck);
    return null;
  }
};

/**
 * Get the next page
 * @method
 * @return {Page} The next page
 */
Paginator.prototype.getNext = function(){
  try {
    return this.getPage(this.getCurrentPage().rank+1);
  } catch(err) {
    return null;
  }
};

/**
 * Navigate to the given page
 * @method
 * @param {Page} the page to navigate to
 * @return void
 */
Paginator.prototype.gotoPage = function(toPage){

  // Show the destination page
  $(toPage._content).css({ 'display': 'block' });

  // Hide all other pages
  $.each(pages,function(i, loopPage){
    if (toPage.rank !== loopPage.rank) {
      $(loopPage._content).css({ 'display': 'none' });
    }
  });

  currentPage = toPage;

};

/**
 * Get the currently focused page div
 * @method
 * @return {Element} The parent div element having an attribute data-paginator
 */
Paginator.prototype.getFocusedPageDiv = function(){
  var selectedElement = editor.selection.getRng().startContainer;
  var parents = editor.dom.getParents(selectedElement,'div',editor.getDoc().body);
  var ret;
  $.each(parents,function(i,parent){
    if ($(parent).attr('data-paginator')) {
      ret = parent;
    }
  });
  if (!ret) throw new Error('No parent page found ! You are out of a page.');
  else return ret;
};

/**
 * Go to the page having the focus
 * @method
 * @return void
 */
Paginator.prototype.gotoFocusedPage = function(){
  var focusedDiv = this.getFocusedPageDiv();
  var pageRank = $(focusedDiv).attr('data-paginator-page-rank');
  var focusedPage = this.getPage(pageRank);
  currentPage = focusedPage;
  this.gotoPage(focusedPage);
};

/**
 * Navigate to the previous page
 * @method
 * @return {Page} The previous page after navigation is done
 */
Paginator.prototype.gotoPrevious = function(){
  console.info('goto previous page');
  return this.gotoPage(this.getPrevious());
};

/**
 * Navigate to the next page
 * @method
 * @return {Page} The next page after navigation is done
 */
Paginator.prototype.gotoNext = function(){
  console.info('goto next page');
  return this.gotoPage(this.getNext());
};

/**
 * Watch the current page, to check if content overflows the page's max-height.
 * @method
 * @return void
 */
Paginator.prototype.watchPage = function(){

  // console.log('body clientHeight', this._body.clientHeight,'body scrollHeight', this._body.scrollHeight);

  // console.log('padding',padding);

  // console.log('default height:', this._defaultPage.height);
  // console.log('page (Display) height (px): ', this._display.height('px') + ' px');
  // console.log('page (Display) height (mm): ', this._display.height('mm') + ' mm');
  // console.log('page content', page.content());
};

/**
 * Get the current computed padding
 * @method
 * @return {object}
 */
Paginator.prototype._getDocPadding = function(){
  var that = this;
  return {
    top: $(that._body).css('padding-top'),
    right: $(that._body).css('padding-right'),
    bottom: $(that._body).css('padding-bottom'),
    left: $(that._body).css('padding-left')
  };
}

/**
 * Compute the page inner height in pixels
 * @method
 * @return {Number} The resulted height in pixels
 */
Paginator.prototype._getPageInnerHeight = function(){

  var outerHeight = Number(this._display.mm2px(this._defaultPage.height)*10); // @TODO (*10) is a bug fix
  var docPadding = this._getDocPadding();
  var paddingTop = Number(docPadding.top.split('px').join(''));
  var paddingBottom = Number(docPadding.bottom.split('px').join(''));

  var innerHeight = outerHeight - paddingTop - paddingBottom;

  return innerHeight-1 // -1 because of a bug in border-bottom pdf rendering
};

/**
 * Initialize the paginator
 * @method
 * @return void
 */
Paginator.prototype.init = function(){
  function findPageWrappers(){
    return $('div[data-paginator-page-rank]',that._body);
  }
  var that = this;

  // search the paginator page wrappers
  var wrappedPages = findPageWrappers();
  var wrapper = $('<div>');
  wrapper.attr({
    'data-paginator': true,
    'data-paginator-page-rank': 1
  }).css({
    'page-break-after': 'always',
    'height': that._getPageInnerHeight(),
    // 'border': 'solid red 1px',
    // 'background': 'yellow',
    'overflow': 'hidden'
  });

  // wrap unwrapped content
  if (!wrappedPages.length){
    $(this._body).wrapInner(wrapper);
    wrappedPages = findPageWrappers();
  }

  pages = [];
  $.each(wrappedPages,function(i,el){
    pages.push(new Page(that._defaultPage.format().label, that._defaultPage.orientation, i+1, el));
  });

  console.log(pages);

};

/**
 * Paginator class
 */
module.exports = Paginator;
<commit_msg>implement Paginator.watchPage()<commit_after>/**
 * Paginator class module
 * @module classes/Paginator
 */

'use strict';

// var _ = require('lodash');
var Display = require('./Display');
var Page = require('./Page');
var parser = require('./paginator/parser');

var errors = require('./paginator/errors'),
  InvalidPageRankError = errors.InvalidPageRankError;

/**
 * Paginator is the page manager
 * @constructor
 * @param {string} pageFormatLabel The label of the paper format for all pages. For example, 'A4'
 * @param {string} pageOrientation The label of the orientation for all pages. May be 'portait' or 'landscape'
 * @param {DOMDocument} doc The document given by editor.getDoc() of the tinymce API
 *
 * @example
 paginator = new Paginator('A4','portait', editor.getDoc());
 *
 * @see utils/page-formats
 */
function Paginator(pageFormatLabel, pageOrientation, ed){

  editor = ed;
  /**
   * The DOMDocument given in the constructor
   * @property {DOMDocument}
   * @private
   */
  this._document = ed.getDoc();
  /**
   * The Display to manage screen and dimensions
   * @property {Display}
   * @private
   */
  this._display = new Display(this._document);
  /**
   * The default abstract page from all real pages inherits
   * @property {Page}
   * @private
   */
  this._defaultPage = new Page(pageFormatLabel, pageOrientation);
  /**
   * The body element of the full document
   * @property {Element}
   * @private
   */
  this._body = this._document.getElementsByTagName('body');

}

/**
 * The current page
 * @property {Page}
 * @private
 */
var currentPage;

/**
 * The list of pages
 * @property {Array}
 * @private
 */
var pages = [];

/**
 * Current editor
 * @property {Editor}
 * @private
 */
var editor;

/**
 * Get the current page
 * @method
 * @return {Page} the current page loaded in editor
 */
Paginator.prototype.getCurrentPage = function(){
  return currentPage;
};

/**
 * Get the page with the given rank
 * @method
 * @param {Number} rank The requested page rank
 * @return {Page} The requested page
 */
Paginator.prototype.getPage = function(rank){
  if (!pages.length)
    throw new Error('Paginator pages length in null. Can\'t iterate on it.');

  var isLower = rank-1 < 0;
  var isGreater = rank-1 > pages.length;

  if (isLower || isGreater) throw new InvalidPageRankError(rank);
  else return pages[rank-1];
};

/**
 * Get all pages in paginator
 * @method
 * @return {Array<Page>} all paginator pages
 */
Paginator.prototype.getPages = function(){
  return pages;
};

/**
 * Return the previous page
 * @method
 * @return {Page} The previous page
 */
Paginator.prototype.getPrevious = function(){
  try {
    console.log('this.getCurrentPage()',currentPage);
    return this.getPage(this.getCurrentPage().rank-1);
  } catch(err) {
    console.error(err.stck);
    return null;
  }
};

/**
 * Get the next page
 * @method
 * @return {Page} The next page
 */
Paginator.prototype.getNext = function(){
  try {
    return this.getPage(this.getCurrentPage().rank+1);
  } catch(err) {
    return null;
  }
};

/**
 * Navigate to the given page
 * @method
 * @param {Page} the page to navigate to
 * @return void
 */
Paginator.prototype.gotoPage = function(toPage){

  // Show the destination page
  $(toPage._content).css({ 'display': 'block' });

  // Hide all other pages
  $.each(pages,function(i, loopPage){
    if (toPage.rank !== loopPage.rank) {
      $(loopPage._content).css({ 'display': 'none' });
    }
  });

  currentPage = toPage;

};

/**
 * Get the currently focused page div
 * @method
 * @return {Element} The parent div element having an attribute data-paginator
 */
Paginator.prototype.getFocusedPageDiv = function(){
  var selectedElement = editor.selection.getRng().startContainer;
  var parents = editor.dom.getParents(selectedElement,'div',editor.getDoc().body);
  var ret;
  $.each(parents,function(i,parent){
    if ($(parent).attr('data-paginator')) {
      ret = parent;
    }
  });
  if (!ret) throw new Error('No parent page found ! You are out of a page.');
  else return ret;
};

/**
 * Go to the page having the focus
 * @method
 * @return void
 */
Paginator.prototype.gotoFocusedPage = function(){
  var focusedDiv = this.getFocusedPageDiv();
  var pageRank = $(focusedDiv).attr('data-paginator-page-rank');
  var focusedPage = this.getPage(pageRank);
  currentPage = focusedPage;
  this.gotoPage(focusedPage);
};

/**
 * Navigate to the previous page
 * @method
 * @return {Page} The previous page after navigation is done
 */
Paginator.prototype.gotoPrevious = function(){
  console.info('goto previous page');
  return this.gotoPage(this.getPrevious());
};

/**
 * Navigate to the next page
 * @method
 * @return {Page} The next page after navigation is done
 */
Paginator.prototype.gotoNext = function(){
  console.info('goto next page');
  return this.gotoPage(this.getNext());
};

/**
 * Watch the current page, to check if content overflows the page's max-height.
 * @method
 * @return void
 */
Paginator.prototype.watchPage = function(){

  var maxHeight = Math.ceil(this._getPageInnerHeight());
  var currentHeight = Number($(currentPage.content()).css('height').split('px').join(''));
  console.info('normal inner page height',maxHeight);
  console.info('currentPage inner height',currentHeight);

  if (currentHeight > maxHeight) {
    alert('Dépassement de page !');
    this._repage();
  }

  // console.log('padding',padding);

  // console.log('default height:', this._defaultPage.height);
  // console.log('page (Display) height (px): ', this._display.height('px') + ' px');
  // console.log('page (Display) height (mm): ', this._display.height('mm') + ' mm');
  // console.log('page content', page.content());
};

/**
 * Get the current computed padding
 * @method
 * @return {object}
 */
Paginator.prototype._getDocPadding = function(){
  var that = this;
  return {
    top: $(that._body).css('padding-top'),
    right: $(that._body).css('padding-right'),
    bottom: $(that._body).css('padding-bottom'),
    left: $(that._body).css('padding-left')
  };
}

/**
 * Compute the page inner height in pixels
 * @method
 * @return {Number} The resulted height in pixels
 */
Paginator.prototype._getPageInnerHeight = function(){

  var outerHeight = Number(this._display.mm2px(this._defaultPage.height)*10); // @TODO (*10) is a bug fix
  var docPadding = this._getDocPadding();
  var paddingTop = Number(docPadding.top.split('px').join(''));
  var paddingBottom = Number(docPadding.bottom.split('px').join(''));

  var innerHeight = outerHeight - paddingTop - paddingBottom;

  return innerHeight-1 // -1 because of a bug in border-bottom pdf rendering
};

/**
 * Initialize the paginator
 * @method
 * @return void
 */
Paginator.prototype.init = function(){
  function findPageWrappers(){
    return $('div[data-paginator-page-rank]',that._body);
  }
  var that = this;

  // search the paginator page wrappers
  var wrappedPages = findPageWrappers();
  var wrapper = $('<div>');
  wrapper.attr({
    'data-paginator': true,
    'data-paginator-page-rank': 1
  }).css({
    'page-break-after': 'always',
    'height': that._getPageInnerHeight(),
    // 'border': 'solid red 1px',
    // 'background': 'yellow',
    'overflow': 'hidden'
  });

  // wrap unwrapped content
  if (!wrappedPages.length){
    $(this._body).wrapInner(wrapper);
    wrappedPages = findPageWrappers();
  }

  pages = [];
  $.each(wrappedPages,function(i,el){
    pages.push(new Page(that._defaultPage.format().label, that._defaultPage.orientation, i+1, el));
  });

  console.log(pages);

};

/**
 * Paginator class
 */
module.exports = Paginator;
<|endoftext|>


<commit_before>import Serializable from './Serializable';

export default class CustomDimensions extends Serializable {
  constructor(category, action, label, value, experiment) {
    super('event', {
      ec: category,
      ea: action,
      el: label,
      ev: value
    }, experiment);
  }

  addDimension(index, name) {
    this.properties = {
      [`cd${index}`]: name
    };
  }

  removeDimension(index) {
    delete this.properties[`cd${index}`];
  }
}
<commit_msg>Removed bad code<commit_after>import Serializable from './Serializable';

export default class CustomDimensions extends Serializable {

  addDimension(index, name) {
    this.properties = {
      [`cd${index}`]: name
    };
  }

  removeDimension(index) {
    delete this.properties[`cd${index}`];
  }
}
<|endoftext|>


<commit_before>ENS.sqlPlanView = wgp.AbstractView
		.extend({
			tableColNamesList : {
				"sqlStatement" : [ "Query" ],
				"sqlExecutePlan" : [ "Get Time", "Query Plan" ],
				"stackTrace" : [ "Stack Trace" ]
			},
			initialize : function(argument, treeSettings) {

				var appView = new ENS.AppView();
				this.treeSettings = treeSettings;
				var treeId = treeSettings.id;
				appView.addView(this, treeId);

				this.tableMargin = 20;
				this.tableWidth = $("#" + this.id).width() - this.tableMargin
						* 3;

				this.createTableColModelsList();

				// 空のテーブルを作成
				this.render();

				this.getSqlPlan(treeId);
			},
			render : function() {
				var divId = "sqlPlanDiv";
				$("#" + this.id).append('

');
				$("#" + divId).css({
					"margin-top" : 20,
					"margin-left" : 15
				});

				// 各テーブルを作成する
				this.createSqlStatementTabel(divId);
				this.createSqlExecutePlanTable(divId);
				this.createStackTraceTable(divId);

				$(".ui-jqgrid-sortable").css("font-size", "13px");
			},
			onAdd : function(element) {
				// Do nothing
			},
			onChange : function(element) {
				// Do nothing
			},
			onRemove : function(element) {
				// Do nothing
			},
			onComplete : function(element) {
				// Do nothing
			},
			createTableColModelsList : function() {

				this.tableColModelsList = {
					"sqlStatement" : [ {
						name : "sqlStatement",
						width : this.tableWidth - 5
					} ],
					"sqlExecutePlan" : [ {
						name : "gettingPlanTime",
						width : 70
					}, {
						name : "executePlan",
						width : this.tableWidth - 110
					} ],
					"stackTrace" : [ {
						name : "stackTrace",
						width : this.tableWidth - 35
					} ]
				};
			},
			createSqlStatementTabel : function(divId) {
				$("#" + divId).append('

');

				$("#sqlStatementTable").jqGrid({
					datatype : "local",
					data : "",
					colModel : this.tableColModelsList["sqlStatement"],
					colNames : this.tableColNamesList["sqlStatement"],
					caption : "Query",
					height : "auto",
					width : this.tableWidth,
					shrinkToFit : false,
					cellEdit : true,
					cmTemplate: { title: false }
				});

				$("#gbox_sqlStatementTable").css({
					"margin-bottom" : this.tableMargin,
				});

				$("#sqlStatementTable").css('font-size', '13px');
				$("#sqlStatementTable").css('word-break', 'break-all');
			},
			createSqlExecutePlanTable : function(divId) {
				$("#" + divId).append(
						'

');
				$("#" + divId).append('

');

				$("#sqlExecutePlanTable").jqGrid({
					datatype : "local",
					data : "",
					colModel : this.tableColModelsList["sqlExecutePlan"],
					colNames : this.tableColNamesList["sqlExecutePlan"],
					caption : "Query Plan",
					pager : "sqlExecutePlanPager",
					rowList : [ 1, 3, 5 ],
					pgbuttons : true,
					pginput : true,
					height : "auto",
					width : this.tableWidth,
					sortname : "stackTrace",
					sortorder : "desc",
					viewrecords : true,
					rownumbers : true,
					shrinkToFit : false,
					cellEdit : true,
					cmTemplate: { title: false }
				});

				$("#gbox_sqlExecutePlanTable").css({
					"margin-bottom" : this.tableMargin
				});

				$("#sqlExecutePlanTable").css('font-size', '13px');
				$("#sqlExecutePlanTable").css('word-break', 'break-all');
				$("#sqlExecutePlanPager").css('font-size', '13px');
			},
			createStackTraceTable : function(divId) {
				$("#" + divId).append('

');
				$("#" + divId).append('

');

				$("#stackTraceTable").jqGrid({
					datatype : "local",
					data : "",
					colModel : this.tableColModelsList["stackTrace"],
					colNames : this.tableColNamesList["stackTrace"],
					caption : "Stack Trace",
					pager : "stackTracePager",
					rowList : [ 1, 3, 5 ],
					pgbuttons : true,
					pginput : true,
					height : "auto",
					width : this.tableWidth,
					sortname : "gettingPlanTime",
					sortorder : "desc",
					viewrecords : true,
					rownumbers : true,
					shrinkToFit : false,
					cellEdit : true,
					cmTemplate: { title: false }
				});

				$("#gbox_stackTraceTable").css({
					"margin-bottom" : this.tableMargin
				});

				$("#stackTraceTable").css('font-size', '13px');
				$("#stackTraceTable").css('word-break', 'break-all');
				$("#stackTracePager").css('font-size', '13px');
			},
			getSqlPlan : function(itemName) {
				// SQL文、SQL実行計画、スタックトレースを取得する
				// Ajax通信用の設定
				var settings = {
					data : {
						itemName : itemName
					},
					url : ENS.tree.GET_SQL_PLAN
				};

				// 非同期通信でデータを送信する
				var ajaxHandler = new wgp.AjaxHandler();
				settings[wgp.ConnectionConstants.SUCCESS_CALL_OBJECT_KEY] = this;
				settings[wgp.ConnectionConstants.SUCCESS_CALL_FUNCTION_KEY] = "callbackGetSqlPlan";
				ajaxHandler.requestServerAsync(settings);
			},
			callbackGetSqlPlan : function(sqlPlan) {
				var sqlStatement = sqlPlan.sqlStatement;
				var executionPlanList = sqlPlan.executionPlanList;
				var gettingPlanTimeList = sqlPlan.gettingPlanTimeList;
				var stackTraceList = sqlPlan.stackTraceList;

				if (sqlStatement) {
					// 各テーブル用データを作成し、テーブルごとにリロードする
					var sqlStatementTableData = [ {
						"sqlStatement" : sqlStatement
					} ];

					$("#sqlStatementTable").clearGridData().setGridParam({
						data : sqlStatementTableData
					}).trigger("reloadGrid");
				}

				if (executionPlanList && gettingPlanTimeList) {
					var executionPlanTableData = [];
					_
							.each(
									executionPlanList,
									function(executionPlan, index) {

										if (executionPlan) {
											executionPlan = executionPlan
													.replace(/\n/g, "
");
											executionPlan = executionPlan
													.replace(/\s\s/g, "　");
										}

										var data = {
											"gettingPlanTime" : gettingPlanTimeList[index],
											"executePlan" : executionPlan
										};
										executionPlanTableData.push(data);
									});

					$("#sqlExecutePlanTable").clearGridData().setGridParam({
						data : executionPlanTableData
					}).trigger("reloadGrid");
				}

				if (stackTraceList) {
					var stackTraceTableData = [];

					_
							.each(
									stackTraceList,
									function(stackTrace, index) {
										var data = {
											"stackTrace" : stackTrace
										};
										stackTraceTableData.push(data);
									});

					$("#stackTraceTable").clearGridData().setGridParam({
						data : stackTraceTableData
					}).trigger("reloadGrid");
				}
			}
		});<commit_msg>issues #176 実行計画テーブル、スタックトレーステーブルのデフォルトのページ内最大表示行数に制限がなかったため、5に設定した。<commit_after>ENS.sqlPlanView = wgp.AbstractView
		.extend({
			tableColNamesList : {
				"sqlStatement" : [ "Query" ],
				"sqlExecutePlan" : [ "Get Time", "Query Plan" ],
				"stackTrace" : [ "Stack Trace" ]
			},
			initialize : function(argument, treeSettings) {

				var appView = new ENS.AppView();
				this.treeSettings = treeSettings;
				var treeId = treeSettings.id;
				appView.addView(this, treeId);

				this.tableMargin = 20;
				this.tableWidth = $("#" + this.id).width() - this.tableMargin
						* 3;

				this.createTableColModelsList();

				// 空のテーブルを作成
				this.render();

				this.getSqlPlan(treeId);
			},
			render : function() {
				var divId = "sqlPlanDiv";
				$("#" + this.id).append('

');
				$("#" + divId).css({
					"margin-top" : 20,
					"margin-left" : 15
				});

				// 各テーブルを作成する
				this.createSqlStatementTabel(divId);
				this.createSqlExecutePlanTable(divId);
				this.createStackTraceTable(divId);

				$(".ui-jqgrid-sortable").css("font-size", "13px");
			},
			onAdd : function(element) {
				// Do nothing
			},
			onChange : function(element) {
				// Do nothing
			},
			onRemove : function(element) {
				// Do nothing
			},
			onComplete : function(element) {
				// Do nothing
			},
			createTableColModelsList : function() {

				this.tableColModelsList = {
					"sqlStatement" : [ {
						name : "sqlStatement",
						width : this.tableWidth - 5
					} ],
					"sqlExecutePlan" : [ {
						name : "gettingPlanTime",
						width : 70
					}, {
						name : "executePlan",
						width : this.tableWidth - 110
					} ],
					"stackTrace" : [ {
						name : "stackTrace",
						width : this.tableWidth - 35
					} ]
				};
			},
			createSqlStatementTabel : function(divId) {
				$("#" + divId).append('

');

				$("#sqlStatementTable").jqGrid({
					datatype : "local",
					data : "",
					colModel : this.tableColModelsList["sqlStatement"],
					colNames : this.tableColNamesList["sqlStatement"],
					caption : "Query",
					height : "auto",
					width : this.tableWidth,
					shrinkToFit : false,
					cellEdit : true,
					cmTemplate: { title: false }
				});

				$("#gbox_sqlStatementTable").css({
					"margin-bottom" : this.tableMargin,
				});

				$("#sqlStatementTable").css('font-size', '13px');
				$("#sqlStatementTable").css('word-break', 'break-all');
			},
			createSqlExecutePlanTable : function(divId) {
				$("#" + divId).append(
						'

');
				$("#" + divId).append('

');

				$("#sqlExecutePlanTable").jqGrid({
					datatype : "local",
					data : "",
					colModel : this.tableColModelsList["sqlExecutePlan"],
					colNames : this.tableColNamesList["sqlExecutePlan"],
					caption : "Query Plan",
					pager : "sqlExecutePlanPager",
					rowNum : 5,
					rowList : [ 5, 3, 1 ],
					pgbuttons : true,
					pginput : true,
					height : "auto",
					width : this.tableWidth,
					sortname : "stackTrace",
					sortorder : "desc",
					viewrecords : true,
					rownumbers : true,
					shrinkToFit : false,
					cellEdit : true,
					cmTemplate: { title: false }
				});

				$("#gbox_sqlExecutePlanTable").css({
					"margin-bottom" : this.tableMargin
				});

				$("#sqlExecutePlanTable").css('font-size', '13px');
				$("#sqlExecutePlanTable").css('word-break', 'break-all');
				$("#sqlExecutePlanPager").css('font-size', '13px');
			},
			createStackTraceTable : function(divId) {
				$("#" + divId).append('

');
				$("#" + divId).append('

');

				$("#stackTraceTable").jqGrid({
					datatype : "local",
					data : "",
					colModel : this.tableColModelsList["stackTrace"],
					colNames : this.tableColNamesList["stackTrace"],
					caption : "Stack Trace",
					pager : "stackTracePager",
					rowNum : 5,
					rowList : [ 5, 3, 1 ],
					pgbuttons : true,
					pginput : true,
					height : "auto",
					width : this.tableWidth,
					sortname : "gettingPlanTime",
					sortorder : "desc",
					viewrecords : true,
					rownumbers : true,
					shrinkToFit : false,
					cellEdit : true,
					cmTemplate: { title: false }
				});

				$("#gbox_stackTraceTable").css({
					"margin-bottom" : this.tableMargin
				});

				$("#stackTraceTable").css('font-size', '13px');
				$("#stackTraceTable").css('word-break', 'break-all');
				$("#stackTracePager").css('font-size', '13px');
			},
			getSqlPlan : function(itemName) {
				// SQL文、SQL実行計画、スタックトレースを取得する
				// Ajax通信用の設定
				var settings = {
					data : {
						itemName : itemName
					},
					url : ENS.tree.GET_SQL_PLAN
				};

				// 非同期通信でデータを送信する
				var ajaxHandler = new wgp.AjaxHandler();
				settings[wgp.ConnectionConstants.SUCCESS_CALL_OBJECT_KEY] = this;
				settings[wgp.ConnectionConstants.SUCCESS_CALL_FUNCTION_KEY] = "callbackGetSqlPlan";
				ajaxHandler.requestServerAsync(settings);
			},
			callbackGetSqlPlan : function(sqlPlan) {
				var sqlStatement = sqlPlan.sqlStatement;
				var executionPlanList = sqlPlan.executionPlanList;
				var gettingPlanTimeList = sqlPlan.gettingPlanTimeList;
				var stackTraceList = sqlPlan.stackTraceList;

				if (sqlStatement) {
					// 各テーブル用データを作成し、テーブルごとにリロードする
					var sqlStatementTableData = [ {
						"sqlStatement" : sqlStatement
					} ];

					$("#sqlStatementTable").clearGridData().setGridParam({
						data : sqlStatementTableData
					}).trigger("reloadGrid");
				}

				if (executionPlanList && gettingPlanTimeList) {
					var executionPlanTableData = [];
					_
							.each(
									executionPlanList,
									function(executionPlan, index) {

										if (executionPlan) {
											executionPlan = executionPlan
													.replace(/\n/g, "
");
											executionPlan = executionPlan
													.replace(/\s\s/g, "　");
										}

										var data = {
											"gettingPlanTime" : gettingPlanTimeList[index],
											"executePlan" : executionPlan
										};
										executionPlanTableData.push(data);
									});

					$("#sqlExecutePlanTable").clearGridData().setGridParam({
						data : executionPlanTableData
					}).trigger("reloadGrid");
				}

				if (stackTraceList) {
					var stackTraceTableData = [];

					_
							.each(
									stackTraceList,
									function(stackTrace, index) {
										var data = {
											"stackTrace" : stackTrace
										};
										stackTraceTableData.push(data);
									});

					$("#stackTraceTable").clearGridData().setGridParam({
						data : stackTraceTableData
					}).trigger("reloadGrid");
				}
			}
		});<|endoftext|>


<commit_before>Walrus.init({
    ajaxNavigation: true
});

SyntaxHighlighter.all();

$(document).on('pageLoaded', function () {
    console.log('test');
    SyntaxHighlighter.highlight();
});<commit_msg>remove console.log<commit_after>Walrus.init({
    ajaxNavigation: true
});

SyntaxHighlighter.all();

$(document).on('pageLoaded', function () {
    SyntaxHighlighter.highlight();
});<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('weatherHistory.common')
    .factory('forecastFactory', forecastFactory);

  forecastFactory.$inject = [
    '$http',
    '$q',
    'CacheFactory',
    'FORECASTIO_API_KEY'
  ];

  function forecastFactory($http, $q, CacheFactory, FORECASTIO_API_KEY) {
    var service = {};
    service.clearCache = clearCache;
    service.getForecast = getForecast;

    var baseUrl = 'https://api.darksky.net/forecast/'+FORECASTIO_API_KEY+'/';
    var MIN = 1000 * 60;
    var forecastCache = CacheFactory.createCache('forecastCache', {
      maxAge: 15 * MIN,
      deleteOnExpire: 'aggressive'
    });

    return service;

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

    /**
     * Get forecast for a location at a certain time.
     *
     * @param {Number} latitude - Latitude
     * @param {Number} longitude - Longitude
     * @param {Number} time - Unix timestamp in seconds
     * @param {Object} params - Options to pass as query parameters
     * @return {Object} promise - Promise with resolved forecast data
     */
    function getForecast(latitude, longitude, time, params) {
      var deferred = $q.defer();
      var url = baseUrl+latitude+','+longitude+','+time;
      params.callback = 'JSON_CALLBACK';

      $http
        .jsonp(url, {
          cache: forecastCache,
          params: params
        })
        .then(function(res) {
          var forecast = processData(res.data, params.timezone.timezoneId);
          deferred.resolve(forecast);
        });
      return deferred.promise;
    }

    /**
     * Clear forecast cache so fresh data can be available.
     */
    function clearCache() {
      forecastCache.removeAll();
    }

    /**
     * Process forecast data into human readable format
     *
     * @param {Object} forecast - Forecast data to process
     * @param {String} timezone - Timezone of forecast
     * @return {Object} forecast - Forecast data formatted for user
     */
    function processData(forecast, timezone) {
      forecast.year = parseInt(moment.unix(forecast.currently.time).format('YYYY'), 10);
      forecast.daily.data[0].temperatureMaxTime = formatDate(forecast.daily.data[0].temperatureMaxTime, timezone);
      forecast.daily.data[0].temperatureMinTime = formatDate(forecast.daily.data[0].temperatureMinTime, timezone);
      forecast.daily.data[0].sunriseTime = formatDate(forecast.daily.data[0].sunriseTime, timezone);
      forecast.daily.data[0].sunsetTime = formatDate(forecast.daily.data[0].sunsetTime, timezone);
      forecast.currently.icon = renameIcons(forecast.currently.icon);
      return forecast;
    }

    /**
     * Format date in forecast if it needs or ignore if formatted date cached
     *
     * @param {String} date - Date of forecast
     * @param {String} timezone - Timezone of forecast
     * @return {String} date - Formatted date
     */
    function formatDate(date, timezone) {
      var dateIsFormatted = date.toString().indexOf('m') > -1;
      if (dateIsFormatted) {
        return date;
      } else {
        return moment.tz(date * 1000, timezone).format('h:mma');
      }
    }

    /**
     * Rename icon strings from forecast.io to fit weather icons set.
     *
     * @param {String} iconStr - String representing what icon to display. From forecast.io
     * @return {String} iconStr - String representing what icon to display. Modified for icon set
     */
    function renameIcons(iconStr) {
      iconStr = iconStr.replace('partly-', '');
      iconStr = iconStr.replace('wind', 'windy');
      iconStr = iconStr.replace('clear-day', 'day-sunny');
      iconStr = iconStr.replace('clear-night', 'night-clear');
      iconStr = iconStr.replace('cloudy-night', 'night-cloudy');
      iconStr = iconStr.replace('-day', '');
      return iconStr;
    }
  }
})();
<commit_msg>Move processData to transformResponse<commit_after>(function() {
  'use strict';

  angular
    .module('weatherHistory.common')
    .factory('forecastFactory', forecastFactory);

  forecastFactory.$inject = [
    '$http',
    '$q',
    'CacheFactory',
    'FORECASTIO_API_KEY'
  ];

  function forecastFactory($http, $q, CacheFactory, FORECASTIO_API_KEY) {
    var service = {};
    service.clearCache = clearCache;
    service.getForecast = getForecast;

    var baseUrl = 'https://api.darksky.net/forecast/'+FORECASTIO_API_KEY+'/';
    var MIN = 1000 * 60;
    var forecastCache = CacheFactory.createCache('forecastCache', {
      maxAge: 15 * MIN,
      deleteOnExpire: 'aggressive'
    });

    return service;

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

    /**
     * Get forecast for a location at a certain time.
     *
     * @param {Number} latitude - Latitude
     * @param {Number} longitude - Longitude
     * @param {Number} time - Unix timestamp in seconds
     * @param {Object} params - Options to pass as query parameters
     * @return {Object} promise - Promise with resolved forecast data
     */
    function getForecast(latitude, longitude, time, params) {
      var deferred = $q.defer();
      var url = baseUrl+latitude+','+longitude+','+time;
      params.callback = 'JSON_CALLBACK';

      $http
        .jsonp(url, {
          cache: forecastCache,
          params: params,
          transformResponse: transformResponse
        })
        .then(function(res) {
          deferred.resolve(res.data);
        });
      return deferred.promise;
    }

    /**
     * Clear forecast cache so fresh data can be available.
     */
    function clearCache() {
      forecastCache.removeAll();
    }

    /**
     * Process forecast data into human readable format
     *
     * @param {Object} forecast - Forecast data to process
     * @return {Object} forecast - Forecast data formatted for user
     */
    function transformResponse(forecast) {
      forecast.year = parseInt(moment.unix(forecast.currently.time).format('YYYY'), 10);
      forecast.daily.data[0].temperatureMaxTime = formatDate(forecast.daily.data[0].temperatureMaxTime, forecast.timezone);
      forecast.daily.data[0].temperatureMinTime = formatDate(forecast.daily.data[0].temperatureMinTime, forecast.timezone);
      forecast.daily.data[0].sunriseTime = formatDate(forecast.daily.data[0].sunriseTime, forecast.timezone);
      forecast.daily.data[0].sunsetTime = formatDate(forecast.daily.data[0].sunsetTime, forecast.timezone);
      forecast.currently.icon = renameIcons(forecast.currently.icon);
      return forecast;
    }

    /**
     * Format date in forecast if it needs or ignore if formatted date cached
     *
     * @param {String} date - Date of forecast
     * @param {String} timezone - Timezone of forecast
     * @return {String} date - Formatted date
     */
    function formatDate(date, timezone) {
      var dateIsFormatted = date.toString().indexOf('m') > -1;
      if (dateIsFormatted) {
        return date;
      } else {
        return moment.tz(date * 1000, timezone).format('h:mma');
      }
    }

    /**
     * Rename icon strings from forecast.io to fit weather icons set.
     *
     * @param {String} iconStr - String representing what icon to display. From forecast.io
     * @return {String} iconStr - String representing what icon to display. Modified for icon set
     */
    function renameIcons(iconStr) {
      iconStr = iconStr.replace('partly-', '');
      iconStr = iconStr.replace('wind', 'windy');
      iconStr = iconStr.replace('clear-day', 'day-sunny');
      iconStr = iconStr.replace('clear-night', 'night-clear');
      iconStr = iconStr.replace('cloudy-night', 'night-cloudy');
      iconStr = iconStr.replace('-day', '');
      return iconStr;
    }
  }
})();
<|endoftext|>


<commit_before>module.exports = {
  /**
   * Application configuration section
   * http://pm2.keymetrics.io/docs/usage/application-declaration/
   */
  apps : [

    // First application
    {
      name      : 'msTourism2',
      script    : 'index.js',
      env: {
        COMMON_VARIABLE: 'true'
      },
      env_production : {
        NODE_ENV: 'production'
      }
    }
  ],

  /**
   * Deployment section
   * http://pm2.keymetrics.io/docs/usage/deployment/
   */
  deploy : {
    production : {
        key: '~/.ssh/id_rsa',
        user: 'dworkz',
        host: '185.216.32.138',
        ref: 'origin/deployment',
        repo: 'git@github.com:D-Dawg/msTourismGrp3.git',
        path: '/home/dworkz/home/msTourism2',
      'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
    }
  }
};
<commit_msg>ecosystem bugfix git<commit_after>module.exports = {
  /**
   * Application configuration section
   * http://pm2.keymetrics.io/docs/usage/application-declaration/
   */
  apps : [

    // First application
    {
      name      : 'msTourism2',
      script    : 'index.js',
      env: {
        COMMON_VARIABLE: 'true'
      },
      env_production : {
        NODE_ENV: 'production'
      }
    }
  ],

  /**
   * Deployment section
   * http://pm2.keymetrics.io/docs/usage/deployment/
   */
  deploy : {
    production : {
        key: '~/.ssh/id_rsa',
        user: 'dworkz',
        host: '185.216.32.138',
        ref: 'origin/deployment',
        repo: 'git@github.com:D-Dawg/msTourism2.git',
        path: '/home/dworkz/home/msTourism2',
      'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
    }
  }
};
<|endoftext|>


<commit_before>const path = require('path');
const interpreter = path.resolve(process.env.HOME, 'n/n/versions/node/8.1.0/bin/node');

module.exports = {
  /**
   * Application configuration section
   * http://pm2.keymetrics.io/docs/usage/application-declaration/
   */
  apps : [

    // First application
    {
      name      : "numbers",
      script    : "app.js",
      interpreter: interpreter,
      env: {
        NODE_ENV: "development",
        PORT: 4001,
        DEBUG: "koa*,nums*"
      },
      env_production : {
        NODE_ENV: "production",
        PORT: 4001,
        DEBUG: "nums*"
      }
    }
  ]
}
<commit_msg>update pm2 config<commit_after>const path = require('path');
const interpreter = path.resolve(process.env.HOME, 'n/n/versions/node/8.1.0/bin/node');

module.exports = {
  /**
   * Application configuration section
   * http://pm2.keymetrics.io/docs/usage/application-declaration/
   */
  apps : [

    // First application
    {
      name      : "numbers",
      script    : "./app.js",
      cwd: __dirname,
      interpreter: interpreter,
      env: {
        NODE_ENV: "development",
        PORT: 4001,
        DEBUG: "koa*,nums*"
      },
      env_production : {
        NODE_ENV: "production",
        PORT: 4001,
        DEBUG: "nums*"
      },
      max_restart: 10,
      error_file: path.resolve(process.env.HOME, 'logs/numbers-err.log'),
      out_file: path.resolve(process.env.HOME, 'logs/numbers-out.log')
    }
  ],
  deploy: {
    production: {
      user: "node",
      host: "nodeserver",
      ref: "origin/master",
      repo: "https://github.com/ftc-editorial/numbers.git",
      path: "/home/node/test",
      "pre-setup": "echo 'pre step'",
      "post-setup": "ls -la",
      "pre-deploy-local": "echo 'Begin to deploy'",
      "post-deploy": "npm install --production && npm run build && pm2 startOrRestart ecosystem.config.js --env production"
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Fix triggering with clip select<commit_after><|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Config;

(function ()
{
    Config =
    {
        configObject: {},
        types: {}
    };

    $(document).ready(loadConfig);

    function loadConfig()
    {
        var configXML = $($.parseXML($('#config').text())).children('config');
        var config = {};

        var defaultScopes = { statementScope: 'independent' };
        config.properties = loadPropertyGroup(configXML.children('properties'), defaultScopes);

        Config.configObject = config;
    }

    function loadPropertyGroup(groupXML, parentScopes)
    {
        var groupScopes = loadScopes(groupXML[0]);
        mergeScopes(groupScopes, parentScopes);

        var properties = {};
        groupXML.children().each(function (index, childXML)
        {
            if (childXML.nodeName === "property")
            {
                var id = childXML.getAttribute('id');
                var propertyScopes = loadScopes(childXML);
                mergeScopes(propertyScopes, groupScopes);
                properties[id] =
                {
                    id: id,
                    name: childXML.getAttribute('name'),
                    description: childXML.getAttribute('description'),
                    optional: Boolean(childXML.getAttribute('optional')),
                    scopes: propertyScopes,
                    type: loadType($(childXML).children().eq(0))
                }
            }
            else
            {
                $.extend(properties, loadPropertyGroup($(childXML), groupScopes));
            }
        });
        return properties;
    }

    function loadScopes(scopedXML)
    {
        return { statementScope: scopedXML.getAttribute('statementScope') };
    }

    function mergeScopes(localScopes, parentScopes)
    {
        for (var scopeName in parentScopes)
        {
            if (!localScopes[scopeName])
            {
                localScopes[scopeName] = parentScopes[scopeName];
            }
        }
    }

    function loadType(typeXML)
    {
        return Config.types[typeXML[0].nodeName.substr('type'.length).toLowerCase()];
    }

    Config.types =
    {
        'string': { name: 'string' },
        'integer': { name: 'integer' },
        'boolean': { name: 'boolean' },
        'enumeration': { name: 'enumeration' }
    };
})();
<commit_msg>Added type specialisation functions<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Config;

(function ()
{
    Config =
    {
        configObject: {},
        types: {}
    };

    $(document).ready(loadConfig);

    function loadConfig()
    {
        var configXML = $($.parseXML($('#config').text())).children('config');
        var config = {};

        var defaultScopes = { statementScope: 'independent' };
        config.properties = loadPropertyGroup(configXML.children('properties'), defaultScopes);

        Config.configObject = config;
    }

    function loadPropertyGroup(groupXML, parentScopes)
    {
        var groupScopes = loadScopes(groupXML[0]);
        mergeScopes(groupScopes, parentScopes);

        var properties = {};
        groupXML.children().each(function (index, childXML)
        {
            if (childXML.nodeName === "property")
            {
                var id = childXML.getAttribute('id');
                var propertyScopes = loadScopes(childXML);
                mergeScopes(propertyScopes, groupScopes);
                properties[id] =
                {
                    id: id,
                    name: childXML.getAttribute('name'),
                    description: childXML.getAttribute('description'),
                    optional: Boolean(childXML.getAttribute('optional')),
                    scopes: propertyScopes,
                    type: loadType($(childXML).children().eq(0))
                }
            }
            else
            {
                $.extend(properties, loadPropertyGroup($(childXML), groupScopes));
            }
        });
        return properties;
    }

    function loadScopes(scopedXML)
    {
        return { statementScope: scopedXML.getAttribute('statementScope') };
    }

    function mergeScopes(localScopes, parentScopes)
    {
        for (var scopeName in parentScopes)
        {
            if (!localScopes[scopeName])
            {
                localScopes[scopeName] = parentScopes[scopeName];
            }
        }
    }

    function loadType(typeXML)
    {
        var typeName = typeXML[0].nodeName.substr('type'.length).toLowerCase();
        return Config.types[typeName].loadType(typeXML);
    }

    Config.types =
    {
        'string':
        {
            name: 'string',
            loadType: function(typeXML) { return this; }
        },
        'integer':
        {
            name: 'integer',
            loadType: function(typeXML) { return this; }
        },
        'boolean':
        {
            name: 'boolean',
            loadType: function(typeXML) { return this; }
        },
        'enumeration':
        {
            name: 'enumeration',
            loadType: function(typeXML)
            {
                var values = [];
                typeXML.children('value').each(function(index, valueXML)
                {
                    values.push(valueXML.textContent);
                });
                return $.extend({ values: values }, this);
            }
        }
    };
})();
<|endoftext|>


<commit_before>function init() {
  gapi.hangout.onApiReady.add(function(eventObj) {
    if (eventObj.isApiReady) {
      console.log('ready');
    }
  });
}

gadgets.util.registerOnLoadHandler(init);
<commit_msg>hangout_test: add a code of participants event<commit_after>function init() {
  console.log('app init');

  gapi.hangout.onParticipantsAdded.add(function (participants) {
    console.log('onParticipantsAdded', participants);
  });
}

gadgets.util.registerOnLoadHandler(function () {
  gapi.hangout.onApiReady.add(function (eventObj) {
    if (eventObj.isApiReady) {
      init();
    }
  });
});
<|endoftext|>