<commit_before>/*
 * grunt-karma
 * https://github.com/karma-runner/grunt-karma
 *
 * Copyright (c) 2013 Dave Geddes
 * Licensed under the MIT license.
 */

var runner = require('karma').runner
var Server = require('karma').Server
var path = require('path')
var _ = require('lodash')

function finished (code) {
  return this(code === 0)
}

// Parse out all cli arguments in the form of `--arg=something` or
// `-c=otherthing` and return the array.
function parseArgs (args) {
  return _.filter(args, function (arg) {
    return arg.match(/^--?/)
  })
}

module.exports = function (grunt) {
  grunt.registerMultiTask('karma', 'run karma.', function () {
    var done = this.async()
    var options = this.options({
      background: false,
      client: {}
    })

    // Allow for passing cli arguments to `client.args` using  `--grep=x`
    var args = parseArgs(process.argv.slice(2))
    if (options.client && _.isArray(options.client.args)) {
      args = options.client.args.concat(args)
    }

    // If arguments are provided we pass them to karma
    if (args.length > 0) {
      if (!options.client) {
        options.client = {}
      }
      options.client.args = args
    }

    // Only create client info if data is provided
    if (options.client) {
      // Merge karma default options
      _.defaults(options.client, {
        args: [],
        useIframe: true,
        captureConsole: true
      })
    }

    var opts = _.cloneDeep(options)
    // Merge options onto data, with data taking precedence.
    var data = _.merge(opts, this.data)

    // But override the browsers array.
    if (data.browsers && this.data.browsers) {
      data.browsers = this.data.browsers
    }

    // Merge client.args
    if (this.data.client && _.isArray(this.data.client.args)) {
      data.client.args = this.data.client.args.concat(options.client.args)
    }

    if (data.configFile) {
      data.configFile = path.resolve(data.configFile)
    }

    if (data.files || options.files) {
      data.files = [].concat.apply(options.files || [], this.files.map(function (file) {
        return file.src.map(function (src) {
          var obj = {
            pattern: src
          }
          var opts = ['watched', 'served', 'included']
          opts.forEach(function (opt) {
            if (opt in file) {
              obj[opt] = file[opt]
            }
          })
          return obj
        })
      }))
      data.files = _.flattenDeep(data.files)
    }

    // Allow the use of templates in preprocessors
    if (_.isPlainObject(data.preprocessors)) {
      var preprocessors = {}
      Object.keys(data.preprocessors).forEach(function (key) {
        var value = data.preprocessors[key]
        key = path.resolve(key)
        key = grunt.template.process(key)
        preprocessors[key] = value
      })
      data.preprocessors = preprocessors
    }

    // support `karma run`, useful for grunt watch
    if (this.flags.run) {
      runner.run(data, finished.bind(done))
      return
    }

    // allow karma to be run in the background so it doesn't block grunt
    if (data.background) {
      var backgroundProcess = require('child_process').fork(
          path.join(__dirname, '..', 'lib', 'background.js'),
          { silent: true }
      )
      backgroundProcess.stdin.write(JSON.stringify(data))

      backgroundProcess.on('close', function (code) {
        var error = code
        if (error) {
          grunt.log.error('background karma process exited with error (code: ' + code + ')')
        }
      })

      process.on('exit', function () {
        backgroundProcess.kill()
      })

      done()
    } else {
      var server = new Server(data, finished.bind(done))
      server.start()
    }
  })
}
<commit_msg>fix: handle basePath option for preprocessors paths<commit_after>/*
 * grunt-karma
 * https://github.com/karma-runner/grunt-karma
 *
 * Copyright (c) 2013 Dave Geddes
 * Licensed under the MIT license.
 */

var runner = require('karma').runner
var Server = require('karma').Server
var path = require('path')
var _ = require('lodash')

function finished (code) {
  return this(code === 0)
}

// Parse out all cli arguments in the form of `--arg=something` or
// `-c=otherthing` and return the array.
function parseArgs (args) {
  return _.filter(args, function (arg) {
    return arg.match(/^--?/)
  })
}

module.exports = function (grunt) {
  grunt.registerMultiTask('karma', 'run karma.', function () {
    var done = this.async()
    var options = this.options({
      background: false,
      client: {}
    })

    // Allow for passing cli arguments to `client.args` using  `--grep=x`
    var args = parseArgs(process.argv.slice(2))
    if (options.client && _.isArray(options.client.args)) {
      args = options.client.args.concat(args)
    }

    // If arguments are provided we pass them to karma
    if (args.length > 0) {
      if (!options.client) {
        options.client = {}
      }
      options.client.args = args
    }

    // Only create client info if data is provided
    if (options.client) {
      // Merge karma default options
      _.defaults(options.client, {
        args: [],
        useIframe: true,
        captureConsole: true
      })
    }

    var opts = _.cloneDeep(options)
    // Merge options onto data, with data taking precedence.
    var data = _.merge(opts, this.data)

    // But override the browsers array.
    if (data.browsers && this.data.browsers) {
      data.browsers = this.data.browsers
    }

    // Merge client.args
    if (this.data.client && _.isArray(this.data.client.args)) {
      data.client.args = this.data.client.args.concat(options.client.args)
    }

    if (data.configFile) {
      data.configFile = path.resolve(data.configFile)
    }

    if (data.files || options.files) {
      data.files = [].concat.apply(options.files || [], this.files.map(function (file) {
        return file.src.map(function (src) {
          var obj = {
            pattern: src
          }
          var opts = ['watched', 'served', 'included']
          opts.forEach(function (opt) {
            if (opt in file) {
              obj[opt] = file[opt]
            }
          })
          return obj
        })
      }))
      data.files = _.flattenDeep(data.files)
    }

    // Allow the use of templates in preprocessors
    if (_.isPlainObject(data.preprocessors)) {
      var preprocessors = {}
      Object.keys(data.preprocessors).forEach(function (key) {
        var value = data.preprocessors[key]
        if (options.basePath) {
          key = options.basePath + key
        }
        key = path.resolve(key)
        key = grunt.template.process(key)
        preprocessors[key] = value
      })
      data.preprocessors = preprocessors
    }

    // support `karma run`, useful for grunt watch
    if (this.flags.run) {
      runner.run(data, finished.bind(done))
      return
    }

    // allow karma to be run in the background so it doesn't block grunt
    if (data.background) {
      var backgroundProcess = require('child_process').fork(
          path.join(__dirname, '..', 'lib', 'background.js'),
          { silent: true }
      )
      backgroundProcess.stdin.write(JSON.stringify(data))

      backgroundProcess.on('close', function (code) {
        var error = code
        if (error) {
          grunt.log.error('background karma process exited with error (code: ' + code + ')')
        }
      })

      process.on('exit', function () {
        backgroundProcess.kill()
      })

      done()
    } else {
      var server = new Server(data, finished.bind(done))
      server.start()
    }
  })
}
<|endoftext|>


<commit_before>jQuery(function($){
    var slider = window.slider = new Slider($('#sliderContainer'));
    slider.setSize(800, 500);
    slider.fetchJson('image/json/10');
    slider.setTransition('transition-zoomin');

});
<commit_msg>#21 circles effect using canvas api<commit_after>jQuery(function($){
    var slider = window.slider = new Slider($('#sliderContainer'));
    slider.setSize(800, 500);
    slider.fetchJson('image/json/10');
    slider.setTransitionFunction(SliderTransitionFunctions.circles);
});
<|endoftext|>


<commit_before>function loadScript(url, callback){
  var script = document.createElement("script")
  script.type = "text/javascript";

  if (script.readyState){  //IE
    script.onreadystatechange = function(){
      if (script.readyState == "loaded" ||
          script.readyState == "complete"){
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  //Others
    script.onload = function(){
      callback();
    };
  }

  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Load the given HTML in the viewer iframe
function view(html) {
  var iframe = $("#viewer iframe", top.document);
  var doc = iframe[0].contentWindow.document;
  doc.open();
  doc.write(html);
  doc.close();
}

// Create a new ACE editor in the div with the given id, and return it
function new_editor(div_id) {
  var editor = ace.edit(div_id);
  editor.setTheme("ace/theme/github");
  editor.setShowPrintMargin(false);
  return editor;
}

function initialize_editor(div_id) {
  editor = new_editor(div_id);

  var session = editor.getSession();
  session.setMode("ace/mode/html");

  // Does editor need refreshing?
  var need_refresh = false;
  // How long (in ms) to wait between refreshes, at minimum
  var refresh_interval = 500;
  // Don't refresh if changes occur in rapid succession
  var ignore_threshold = 200;

  // Track timestamp of the last change made in the editor
  var last_change = new Date().getTime();
  session.on('change', function(e) {
    last_changed = new Date().getTime();
    need_refresh = true;
  });

  // At regular intervals, check for changes and refresh the view
  window.setInterval(function() {
    var now = new Date().getTime();
    // If last keystroke was a while ago, and editor has changed, refresh
    if (now - last_changed > ignore_threshold && need_refresh) {
      view(editor.getValue());
      need_refresh = false;
    }
    // Otherwise, either the last change was too recent, or the
    // last change has already been refreshed
  }, refresh_interval);

  $("#import_file").change(function() {
    function populate_editor(responseText, statusText, xhr, $form) {
      editor.setValue(responseText, -1);
    }
    $("#import_form").ajaxSubmit({success: populate_editor});
  });
}

$(document).ready(function() {
  initialize_editor("ace");
});

<commit_msg>Fix typo<commit_after>function loadScript(url, callback){
  var script = document.createElement("script")
  script.type = "text/javascript";

  if (script.readyState){  //IE
    script.onreadystatechange = function(){
      if (script.readyState == "loaded" ||
          script.readyState == "complete"){
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  //Others
    script.onload = function(){
      callback();
    };
  }

  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Load the given HTML in the viewer iframe
function view(html) {
  var iframe = $("#viewer iframe", top.document);
  var doc = iframe[0].contentWindow.document;
  doc.open();
  doc.write(html);
  doc.close();
}

// Create a new ACE editor in the div with the given id, and return it
function new_editor(div_id) {
  var editor = ace.edit(div_id);
  editor.setTheme("ace/theme/github");
  editor.setShowPrintMargin(false);
  return editor;
}

function initialize_editor(div_id) {
  editor = new_editor(div_id);

  var session = editor.getSession();
  session.setMode("ace/mode/html");

  // Does editor need refreshing?
  var need_refresh = false;
  // How long (in ms) to wait between refreshes, at minimum
  var refresh_interval = 500;
  // Don't refresh if changes occur in rapid succession
  var ignore_threshold = 200;

  // Track timestamp of the last change made in the editor
  var last_changed = new Date().getTime();
  session.on('change', function(e) {
    last_changed = new Date().getTime();
    need_refresh = true;
  });

  // At regular intervals, check for changes and refresh the view
  window.setInterval(function() {
    var now = new Date().getTime();
    // If last keystroke was a while ago, and editor has changed, refresh
    if (now - last_changed > ignore_threshold && need_refresh) {
      view(editor.getValue());
      need_refresh = false;
    }
    // Otherwise, either the last change was too recent, or the
    // last change has already been refreshed
  }, refresh_interval);

  $("#import_file").change(function() {
    function populate_editor(responseText, statusText, xhr, $form) {
      editor.setValue(responseText, -1);
    }
    $("#import_form").ajaxSubmit({success: populate_editor});
  });
}

$(document).ready(function() {
  initialize_editor("ace");
});

<|endoftext|>


<commit_before>Paloquiz = {};
Paloquiz.states = {};
Paloquiz.orientated = false;
Paloquiz.orientationBlock;
Paloquiz.booted = false;

Paloquiz.MAX_WIDTH_RATIO = 11.0 / 16.0;
Paloquiz.MAX_HEIGHT_RATIO = 16.0 / 9.0;

var GAME_CONTAINER_ID = 'game-container';
var ORIENTATION_BLOCK_ID = 'orientation';
var FB_BUTTONS_ID = 'fb-buttons';

window.onload = function() {

    // Check Facebook status
    fbInit();

    // Game container
    Paloquiz.gameContainer = document.getElementById(GAME_CONTAINER_ID);

    // Element with orientation image
    Paloquiz.orientationBlock = document.getElementById(ORIENTATION_BLOCK_ID);

    // Facebook buttons
    Paloquiz.fbButtons = document.getElementById(FB_BUTTONS_ID);

    // // Get game dimensions
    // var gameSize = Paloquiz.getGameScale();

    var renderer = Phaser.AUTO; // Phaser.CANVAS / Phaser.WEBGL / Phaser.AUTO
    var transparent = true;
    var antialias = true;

    var width = 640;
    var height = 960;
    Paloquiz.game = new Phaser.Game(width, height,
        renderer, GAME_CONTAINER_ID, {}, transparent, antialias);

    Paloquiz.game.state.add('Boot', Paloquiz.states.Boot);
    Paloquiz.game.state.add('Preloader', Paloquiz.states.Preloader);
    Paloquiz.game.state.add('Router', Paloquiz.states.Router);
    Paloquiz.game.state.add('Start', Paloquiz.states.Start);
    Paloquiz.game.state.add('Main', Paloquiz.states.Main);
    Paloquiz.game.state.add('Highscores', Paloquiz.states.Highscores);
    Paloquiz.game.state.add('Finish', Paloquiz.states.Finish);

    Paloquiz.game.state.start('Boot');
}

// Common game functions

Paloquiz.init = function() {
    Paloquiz.setupLoader();

    // Avoid multiple pointer input
    Paloquiz.game.input.maxPointers = 1;

    // Do not pause when focus is lost
    Paloquiz.game.stage.disableVisibilityChange = true;

    Paloquiz.setupScale();

    Paloquiz.game.state.onStateChange.add(Paloquiz.stateChanged);
}

Paloquiz.setupLoader = function() {
    // Base URL for the loader
    Paloquiz.game.load.baseURL = '/static/';
    // Enable cross-origin image loading
    Paloquiz.game.load.crossOrigin = 'anonymous';
}

Paloquiz.setupScale = function() {
    Paloquiz.orientated = true;

    var game = Paloquiz.game;

    // Stretch
    game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE;

    // Center
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;

    // Check device
    if (game.device.desktop) {
        // On desktop
    } else {
        // On mobile
        // Force portrait
        game.scale.forceOrientation(false, true);
        // Game orientation callbacks
        game.scale.enterIncorrectOrientation.add(function() {
            Paloquiz.orientated = false;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'block';
            }
        }, this);
        game.scale.leaveIncorrectOrientation.add(function() {
            Paloquiz.orientated = true;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'none';
            }
        }, this);
    }

    // Game resizing callback
    game.scale.setResizeCallback(Paloquiz.resize, this);
}

Paloquiz.resize = function () {
    var gameScale = Paloquiz.getGameScale();
    Paloquiz.game.scale.setUserScale(gameScale.x, gameScale.y);
    Paloquiz.positionFbButtons();
}

Paloquiz.getGameScale = function() {
    var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    if ((width / height) > Paloquiz.MAX_WIDTH_RATIO) {
        width = Math.round(height * Paloquiz.MAX_WIDTH_RATIO);
    } else if ((height / width) > Paloquiz.MAX_HEIGHT_RATIO) {
        height = Math.round(width * Paloquiz.MAX_HEIGHT_RATIO);
    }
    return {
        x: width / Paloquiz.game.width,
        y: height / Paloquiz.game.height
    };
}

Paloquiz.stateChanged = function() {
    // Overchecking doesn't hurt
    fbInit();

    Paloquiz.resize();
    Paloquiz.setupBackground();
    Paloquiz.enableFbButtons(true);
}

Paloquiz.setupBackground = function() {
    if (!Paloquiz.game.cache.checkImageKey('background')) {
        return;
    }
    if (!Paloquiz.background) {
        Paloquiz.background = new Phaser.Image(Paloquiz.game, 0, 0, 'background');
        Paloquiz.background.anchor.setTo(0, 0);
        Paloquiz.game.stage.addChildAt(Paloquiz.background, 0);
    }
    Paloquiz.background.smoothed = false;
    Paloquiz.background.width = Paloquiz.game.width;
    Paloquiz.background.height = Paloquiz.game.height;
}

Paloquiz.positionFbButtons = function () {
    var top = Paloquiz.game.scale.bounds.y;
    var left = Paloquiz.game.scale.bounds.x;
    var height = Paloquiz.game.scale.bounds.height;
    var width = Paloquiz.game.scale.bounds.width;
    var margin = width * .05;
    Paloquiz.fbButtons.style.top = Math.round(top + margin) + 'px';
    Paloquiz.fbButtons.style.left = Math.round(left + margin) + 'px';
}

Paloquiz.enableFbButtons = function (show) {
    if (show) {
        Paloquiz.fbButtons.style.display = 'block';
    } else {
        Paloquiz.fbButtons.style.display = 'none';
    }
}
<commit_msg>Repositioned FB buttons<commit_after>Paloquiz = {};
Paloquiz.states = {};
Paloquiz.orientated = false;
Paloquiz.orientationBlock;
Paloquiz.booted = false;

Paloquiz.MAX_WIDTH_RATIO = 11.0 / 16.0;
Paloquiz.MAX_HEIGHT_RATIO = 16.0 / 9.0;

var GAME_CONTAINER_ID = 'game-container';
var ORIENTATION_BLOCK_ID = 'orientation';
var FB_BUTTONS_ID = 'fb-buttons';

window.onload = function() {

    // Check Facebook status
    fbInit();

    // Game container
    Paloquiz.gameContainer = document.getElementById(GAME_CONTAINER_ID);

    // Element with orientation image
    Paloquiz.orientationBlock = document.getElementById(ORIENTATION_BLOCK_ID);

    // Facebook buttons
    Paloquiz.fbButtons = document.getElementById(FB_BUTTONS_ID);

    // // Get game dimensions
    // var gameSize = Paloquiz.getGameScale();

    var renderer = Phaser.AUTO; // Phaser.CANVAS / Phaser.WEBGL / Phaser.AUTO
    var transparent = true;
    var antialias = true;

    var width = 640;
    var height = 960;
    Paloquiz.game = new Phaser.Game(width, height,
        renderer, GAME_CONTAINER_ID, {}, transparent, antialias);

    Paloquiz.game.state.add('Boot', Paloquiz.states.Boot);
    Paloquiz.game.state.add('Preloader', Paloquiz.states.Preloader);
    Paloquiz.game.state.add('Router', Paloquiz.states.Router);
    Paloquiz.game.state.add('Start', Paloquiz.states.Start);
    Paloquiz.game.state.add('Main', Paloquiz.states.Main);
    Paloquiz.game.state.add('Highscores', Paloquiz.states.Highscores);
    Paloquiz.game.state.add('Finish', Paloquiz.states.Finish);

    Paloquiz.game.state.start('Boot');
}

// Common game functions

Paloquiz.init = function() {
    Paloquiz.setupLoader();

    // Avoid multiple pointer input
    Paloquiz.game.input.maxPointers = 1;

    // Do not pause when focus is lost
    Paloquiz.game.stage.disableVisibilityChange = true;

    Paloquiz.setupScale();

    Paloquiz.game.state.onStateChange.add(Paloquiz.stateChanged);
}

Paloquiz.setupLoader = function() {
    // Base URL for the loader
    Paloquiz.game.load.baseURL = '/static/';
    // Enable cross-origin image loading
    Paloquiz.game.load.crossOrigin = 'anonymous';
}

Paloquiz.setupScale = function() {
    Paloquiz.orientated = true;

    var game = Paloquiz.game;

    // Stretch
    game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE;

    // Center
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;

    // Check device
    if (game.device.desktop) {
        // On desktop
    } else {
        // On mobile
        // Force portrait
        game.scale.forceOrientation(false, true);
        // Game orientation callbacks
        game.scale.enterIncorrectOrientation.add(function() {
            Paloquiz.orientated = false;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'block';
            }
        }, this);
        game.scale.leaveIncorrectOrientation.add(function() {
            Paloquiz.orientated = true;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'none';
            }
        }, this);
    }

    // Game resizing callback
    game.scale.setResizeCallback(Paloquiz.resize, this);
}

Paloquiz.resize = function () {
    var gameScale = Paloquiz.getGameScale();
    Paloquiz.game.scale.setUserScale(gameScale.x, gameScale.y);
    Paloquiz.positionFbButtons();
}

Paloquiz.getGameScale = function() {
    var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    if ((width / height) > Paloquiz.MAX_WIDTH_RATIO) {
        width = Math.round(height * Paloquiz.MAX_WIDTH_RATIO);
    } else if ((height / width) > Paloquiz.MAX_HEIGHT_RATIO) {
        height = Math.round(width * Paloquiz.MAX_HEIGHT_RATIO);
    }
    return {
        x: width / Paloquiz.game.width,
        y: height / Paloquiz.game.height
    };
}

Paloquiz.stateChanged = function() {
    // Overchecking doesn't hurt
    fbInit();

    Paloquiz.resize();
    Paloquiz.setupBackground();
    Paloquiz.enableFbButtons(true);
}

Paloquiz.setupBackground = function() {
    if (!Paloquiz.game.cache.checkImageKey('background')) {
        return;
    }
    if (!Paloquiz.background) {
        Paloquiz.background = new Phaser.Image(Paloquiz.game, 0, 0, 'background');
        Paloquiz.background.anchor.setTo(0, 0);
        Paloquiz.game.stage.addChildAt(Paloquiz.background, 0);
    }
    Paloquiz.background.smoothed = false;
    Paloquiz.background.width = Paloquiz.game.width;
    Paloquiz.background.height = Paloquiz.game.height;
}

Paloquiz.positionFbButtons = function () {
    var top = Paloquiz.game.scale.bounds.y;
    var left = Paloquiz.game.scale.bounds.x;
    var height = Paloquiz.game.scale.bounds.height;
    var width = Paloquiz.game.scale.bounds.width;
    var margin = height * .02;
    Paloquiz.fbButtons.style.top = Math.round(top + margin) + 'px';
    Paloquiz.fbButtons.style.left = Math.round(left + margin) + 'px';
}

Paloquiz.enableFbButtons = function (show) {
    if (show) {
        Paloquiz.fbButtons.style.display = 'block';
    } else {
        Paloquiz.fbButtons.style.display = 'none';
    }
}
<|endoftext|>


<commit_before>import { PAGE_ACCESS_TOKEN } from './token';
import orderResolver from '../intentresolver/order';

const apiai = require('apiai');
const FBMessenger = require('fb-messenger');

const messenger = new FBMessenger(PAGE_ACCESS_TOKEN);
const app = apiai('73f11a6d692146bdb9708b4e434e7ec9');

export default function engineEnglish(data) {
  const senderID = data.sender.id;
  const request = app.textRequest(data.message.text, {
    sessionId: senderID,
  });

  function isDefined(obj) {
    if (typeof obj === 'undefined') {
      return false;
    }

    if (!obj) {
      return false;
    }

    return obj != null;
  }

  request.on('response', (response) => {
    if (isDefined(response.result) && isDefined(response.result.fulfillment)) {
      if (response.result.action === 'transactionorder.transactionorder-custom.transactionorder-whichone-yes') {
        messenger.getProfile(senderID, (err, body) => {
          const userProfile = body;
          const speech = response.result.fulfillment.speech;
          console.log(orderResolver(userProfile, data, response));
          messenger.sendTextMessage(senderID, `Okay ${userProfile.first_name}, ${speech}`);
          //messenger.sendReceiptMessage(senderID, orderResolver(userProfile, data, response));
        });
      } else if (response.result.metadata.intentName === 'smalltalk.agent.beautiful') {
        messenger.getProfile(senderID, (err, body) => {
          const userProfile = body;
          const speech = response.result.fulfillment.speech;

          messenger.sendTextMessage(senderID, `${speech} ${userProfile.first_name}`);
          messenger.sendImageMessage(senderID, 'https://68.media.tumblr.com/69a5c69c36489d90d9838850f5668af6/tumblr_ou0embggVR1ssnf1qo6_250.gif');
        });
      } else {
        messenger.sendTextMessage(senderID, response.result.fulfillment.speech);
      }
    }
  });
  request.on('error', (error) => {
    console.log(error);
  });
  request.end();
}
<commit_msg>Kumpul.co Order Pass Bug Fix 6<commit_after>import { PAGE_ACCESS_TOKEN } from './token';
import orderResolver from '../intentresolver/order';

const apiai = require('apiai');
const FBMessenger = require('fb-messenger');

const messenger = new FBMessenger(PAGE_ACCESS_TOKEN);
const app = apiai('73f11a6d692146bdb9708b4e434e7ec9');

export default function engineEnglish(data) {
  const senderID = data.sender.id;
  const request = app.textRequest(data.message.text, {
    sessionId: senderID,
  });

  function isDefined(obj) {
    if (typeof obj === 'undefined') {
      return false;
    }

    if (!obj) {
      return false;
    }

    return obj != null;
  }

  request.on('response', (response) => {
    if (isDefined(response.result) && isDefined(response.result.fulfillment)) {
      if (response.result.action === 'transactionorder.transactionorder-custom.transactionorder-whichone-yes') {
        messenger.getProfile(senderID, (err, body) => {
          const userProfile = body;
          const speech = response.result.fulfillment.speech;
          console.log(orderResolver(userProfile, data, response));
          messenger.sendTextMessage(senderID, `Okay ${userProfile.first_name}, ${speech}`);
          messenger.sendReceiptMessage(senderID, orderResolver(userProfile, data, response));
        });
      } else if (response.result.metadata.intentName === 'smalltalk.agent.beautiful') {
        messenger.getProfile(senderID, (err, body) => {
          const userProfile = body;
          const speech = response.result.fulfillment.speech;

          messenger.sendTextMessage(senderID, `${speech} ${userProfile.first_name}`);
          messenger.sendImageMessage(senderID, 'https://68.media.tumblr.com/69a5c69c36489d90d9838850f5668af6/tumblr_ou0embggVR1ssnf1qo6_250.gif');
        });
      } else {
        messenger.sendTextMessage(senderID, response.result.fulfillment.speech);
      }
    }
  });
  request.on('error', (error) => {
    console.log(error);
  });
  request.end();
}
<|endoftext|>


<commit_before>import Masonry from 'masonry-layout'
var imagesLoaded = require('imagesloaded')
var PhotoSwipe = require ('photoswipe')

import * as utils from './utils'
import Clipboard from 'clipboard'
import * as favorite from './favorite'

const columnWidth = 210
const gutter = 5

const init = (urls) => {
  var grid = document.querySelector('.grid')

  if (grid) {
    new Masonry(grid, {
      itemSelector: '.grid-item',
      columnWidth: columnWidth,
      gutter: gutter,
      fitWidth: true
    })
  }

  // Also grid for other provider results; this is kind of blah
  var grid1 = document.querySelector('.grid1')
  var grid2 = document.querySelector('.grid2')
  var grid3 = document.querySelector('.grid3')
  var grid4 = document.querySelector('.grid4')

  if (grid1) {
    new Masonry(grid1, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
  }
  if (grid2) {
    new Masonry(grid2, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
  }
  if (grid3) {
    new Masonry(grid3, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
  }
  if (grid4) {
    new Masonry(grid4, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
  }

}
window.addEventListener('load', () => {
    const isIE = utils.detectIE()
    var results = document.querySelector('.results')

    if (results) {
        var spinner = document.querySelector('.loading-spinner')
        if (document.querySelector('.image-result')) {
            // shows the spinner in the hope that it will be hidden once the images have loaded
            spinner.style.display = 'block'
        }

        var imgLoad = imagesLoaded('.results')
        //APARENTLY, images.length counts every image on the page, not only the ones in .results
        var lightBox, shown = false;

        imgLoad.on('always', () => {
            // detect which image is broken
            // add images' url to array so we can create a gallery with next/prev.
            var urls = [];
            for (var i=0, len=imgLoad.images.length; i < len; i++) {
                var image = imgLoad.images[i]
                if (!image.isLoaded && !isIE && image.img.dataset && image.img.dataset.title) {
                    // lets hide only the ones that were supposed to be included in the results page.
                    let parent = image.img.parentNode.parentNode.parentNode
                    parent.style.display = 'none'
                } else if (image.img.dataset && image.img.dataset.title) {
                    var captionFn = function () {
                        // function that duplicates the data_container and add the data for each picture.
                        return function (item, element, isFake) {
                            if (!isFake) {
                                while (element.firstChild) {
                                    element.removeChild (element.firstChild);
                                }
                                try {
                                    var x = document.querySelector (".not_caption .data_container").cloneNode (true);
                                    x.className += " show";
                                    element.appendChild (x);
                                } catch (e) { }
                                if (i !== undefined) {
                                    for (var d in item.data) {
                                        var m = document.querySelector('.data_container.show .' + d);
                                        if (m) {
                                            if (d == 'foreign_landing_url') {
                                                m.href = item.data [d];
                                            } else if (d == 'provider') {
                                                m.href = item.data ['provider_url'];
                                                m.innerText = item.data ['provider_name'];
                                            } else if (d == 'license') {
                                                //UGLIEST code ever but we dont have license_version in ES so we have to do this. >:@
                                                var license = item.data [d].toLowerCase (), with_cc = true, buttons = [],segments = license.split ('-');
                                                if (license == 'cc0' || license == 'pdm') with_cc = false;

                                                if (with_cc) {
                                                    buttons.push ('/static/images/cc.svg');
                                                }
                                                for (var b in segments) {
                                                    buttons.push ('/static/images/' + segments [b] + '.svg')
                                                }
                                                for (var b in buttons) {
                                                    var el = document.createElement ("IMG");
                                                    el.src = buttons [b];
                                                    el.title = buttons[b].toUpperCase ();
                                                    m.appendChild (el);
                                                }
                                            } else {
                                                m.innerText = item.data [d];
                                            }
                                        }
                                    }
                                }
                                return true;
                            } else {
                                var x = document.createElement ("DIV");
                                x.className = "data_container fake";
                                element.appendChild (x);
                            }
                            return false;
                        }
                    }
                    var fn = function (idx) {
                        return function (e) {
                            console.log ('click ' + idx);
                            //first and foremost let's stop propagation and default click actions.
                            e.preventDefault ();
                            e.stopPropagation ();

                            try {
                                //Init the gallery.
                                lightBox = new PhotoSwipe (document.querySelectorAll('.pswp')[0], PhotoSwipeUI_Default, urls, {index: idx, addCaptionHTMLFn: captionFn (), shareEl: false, listEl: true, favEl: true, attrEl: true});
                                lightBox.listen ('gettingData', function (index, item) {
                                    // we use this so we don't have to know the image size beforehand.
                                    var i = index;
                                    if (item.w < 1 || item.h < 1) {
                                        var img = new Image ();
                                        img.onload = function () {
                                            item.w = this.width;
                                            item.h = this.height;

                                            lightBox.invalidateCurrItems ();
                                            lightBox.updateSize (true);
                                        }
                                        img.src = item.src;
                                    }
                                    //TODO: set favorite status here

                                });
                                lightBox.init ();
                            } catch (e) { }
                        }

                    }
                    image.img.addEventListener ('click', fn (urls.length));
                    var w = 0, h = 0;
                    urls.push ({src: image.img.dataset.url, w: w, h: h, data: image.img.dataset, title: image.img.dataset.title});
                }
            }
            // Connect buttons
            // Copy attribution text
            // TODO: add HTML option
            var copy = document.querySelector(".pswp .pswp__button--attribution");
            var clipboardText = new Clipboard (copy, {
                text: function () {
                    var idx = lightBox.getCurrentIndex (), data = urls [idx].data;
                    return data.title + " by " + data.creator + " is licensed under " + data.license.toUpperCase ();
                }
            });
            clipboardText.on ("success", function (e) {
                e.trigger.classList.toggle ('done');

                window.setTimeout(function () {
                    e.trigger.classList.remove ('done');
                }, 1500)
            })

            //Toggle the favorite status

            var fav = document.querySelector(".pswp .pswp__button--favorite");
            fav.addEventListener ('click', function (e) {
                fav.classList.add ('waiting');
                // first we need to fetch the current item, the data and identifier to then fetch the form that contains the fav status
                var idx = lightBox.getCurrentIndex (), data = urls [idx].data;
                var form = document.querySelector("[data-identifier='"+data.identifier+"'] form.add-to-favorite"), isFav = form.dataset['is-favorite'];
                favorite.toggleFavoriteWithForm (form, (isFav) => {
                   fav.classList.remove ('waiting');

                   if (isFav) {
                       fav.classList.add ('is_fav')
                   } else {
                       fav.classList.remove ('is_fav')
                   }

                })

            });
            var list = document.querySelector(".pswp .pswp__button--list");
            list.addEventListener ('click', function (e) {
                list.classList.add ('waiting');
                var idx = lightBox.getCurrentIndex (), data = urls [idx].data;
                var formBtn = document.querySelector("[data-identifier='"+data.identifier+"'] .add-to-list-container button");
                formBtn.click ();
            });

            spinner.style.display = 'none'
            results.style.visibility = 'visible'

            init()
        })
    }

})
<commit_msg>Refactored (moved around) some of the code for the new gallery and made sure that the spinner was shown and hidden either when we have loaded all the images or only some.<commit_after>import Masonry from 'masonry-layout'
var imagesLoaded = require('imagesloaded')
var PhotoSwipe = require ('photoswipe')

import * as utils from './utils'
import Clipboard from 'clipboard'
import * as favorite from './favorite'

const columnWidth = 210
const gutter = 5
var loaded = false
var lightBox, spinner;

const init = (imgLoad) => {
    if (!loaded) {
        var grid = document.querySelector('.grid')

        if (grid) {
            new Masonry(grid, {
                itemSelector: '.grid-item',
                columnWidth: columnWidth,
                gutter: gutter,
                fitWidth: true
            })
        }

        // Also grid for other provider results; this is kind of blah
        var grid1 = document.querySelector('.grid1')
        var grid2 = document.querySelector('.grid2')
        var grid3 = document.querySelector('.grid3')
        var grid4 = document.querySelector('.grid4')

        if (grid1) {
            new Masonry(grid1, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
        }
        if (grid2) {
            new Masonry(grid2, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
        }
        if (grid3) {
            new Masonry(grid3, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
        }
        if (grid4) {
            new Masonry(grid4, { itemSelector: '.grid-item', columnWidth: columnWidth, gutter: gutter })
        }
        // Connect buttons
        // Copy attribution text
        // TODO: add HTML option
        var copy = document.querySelector(".pswp .pswp__button--attribution");
        var clipboardText = new Clipboard (copy, {
            text: function () {
                var idx = lightBox.getCurrentIndex (), data = urls [idx].data;
                return data.title + " by " + data.creator + " is licensed under " + data.license.toUpperCase ();
            }
        });
        clipboardText.on ("success", function (e) {
            e.trigger.classList.toggle ('done');

            window.setTimeout(function () {
                e.trigger.classList.remove ('done');
            }, 1500)
        })

        //Toggle the favorite status

        var fav = document.querySelector(".pswp .pswp__button--favorite");
        fav.addEventListener ('click', function (e) {
            fav.classList.add ('waiting');
            // first we need to fetch the current item, the data and identifier to then fetch the form that contains the fav status
            var idx = lightBox.getCurrentIndex (), data = urls [idx].data;
            var form = document.querySelector("[data-identifier='"+data.identifier+"'] form.add-to-favorite"), isFav = form.dataset['is-favorite'];
            favorite.toggleFavoriteWithForm (form, (isFav) => {
                fav.classList.remove ('waiting');

                if (isFav) {
                    fav.classList.add ('is_fav')
                } else {
                    fav.classList.remove ('is_fav')
                }

            })

        });
        var list = document.querySelector(".pswp .pswp__button--list");
        list.addEventListener ('click', function (e) {
            list.classList.add ('waiting');
            var idx = lightBox.getCurrentIndex (), data = urls [idx].data;
            var formBtn = document.querySelector("[data-identifier='"+data.identifier+"'] .add-to-list-container button");
            formBtn.click ();
        });

    }
    const isIE = utils.detectIE()
    for (var i=0, len=imgLoad.images.length; i < len; i++) {
        var image = imgLoad.images[i]
        if (!image.isLoaded && !isIE && image.img.dataset && image.img.dataset.title) {
            // lets hide only the ones that were supposed to be included in the results page.
            let parent = image.img.parentNode.parentNode.parentNode
            parent.style.display = 'none'
        }
    }
    spinner.style.display = 'none'
    loaded = true;
}
var urls = [];
const configImage = (image) => {
    var captionFn = function () {
        // function that duplicates the data_container and adds the data for each picture.
        return function (item, element, isFake) {
            if (!isFake) {
                while (element.firstChild) {
                    element.removeChild (element.firstChild);
                }
                try {
                    var x = document.querySelector (".not_caption .data_container").cloneNode (true);
                    x.className += " show";
                    element.appendChild (x);
                } catch (e) { }
                for (var d in item.data) {
                    var m = document.querySelector('.data_container.show .' + d);
                    if (m) {
                        if (d == 'foreign_landing_url') {
                            m.href = item.data [d];
                        } else if (d == 'provider') {
                            m.href = item.data ['provider_url'];
                            m.innerText = item.data ['provider_name'];
                        } else if (d == 'license') {
                            //UGLIEST code ever but we dont have license_version in ES so we have to do this. >:@
                            var license = item.data [d].toLowerCase (), with_cc = true, buttons = [],segments = license.split ('-');
                            if (license == 'cc0' || license == 'pdm') with_cc = false;

                            if (with_cc) {
                                buttons.push ('/static/images/cc.svg');
                            }
                            for (var b in segments) {
                                buttons.push ('/static/images/' + segments [b] + '.svg')
                            }
                            for (var b in buttons) {
                                var el = document.createElement ("IMG");
                                el.src = buttons [b];
                                el.title = buttons[b].toUpperCase ();
                                m.appendChild (el);
                            }
                        } else {
                            m.innerText = item.data [d];
                        }
                    }
                }
                return true;
            } else {
                var x = document.createElement ("DIV");
                x.className = "data_container fake";
                element.appendChild (x);
            }
            return false;
        }
    }
    var fn = function (idx) {
        return function (e) {
            //first and foremost let's stop propagation and default click actions.
            e.preventDefault ();
            e.stopPropagation ();

            try {
                //Init the gallery.
                lightBox = new PhotoSwipe (document.querySelectorAll('.pswp')[0], PhotoSwipeUI_Default, urls, {index: idx, addCaptionHTMLFn: captionFn (), shareEl: false, listEl: true, favEl: true, attrEl: true});
                lightBox.listen ('gettingData', function (index, item) {
                    // we use this so we don't have to know the image size beforehand.
                    var i = index;
                    if (item.w < 1 || item.h < 1) {
                        var img = new Image ();
                        img.onload = function () {
                            item.w = this.width;
                            item.h = this.height;

                            lightBox.invalidateCurrItems ();
                            lightBox.updateSize (true);
                        }
                        img.src = item.src;
                    }
                    //TODO: set favorite status here

                });
                lightBox.init ();
            } catch (e) { }
        }

    }
    image.addEventListener ('click', fn (urls.length));
    var w = 0, h = 0;
    console.log (image.dataset.url);
    if (image.dataset.url !== undefined) {
        urls.push ({src: image.dataset.url, w: w, h: h, data: image.dataset, title: image.dataset.title});
    }
    var results = document.querySelector (".results");
    if (results) {
        results.style.visibility = 'visible'
    }
}
document.addEventListener('DOMContentLoaded', () => {
        spinner = document.querySelector('.loading-spinner')
        if (document.querySelector('.image-result')) {
            // shows the spinner in the hope that it will be hidden once the images have loaded
            spinner.style.display = 'block'
        }

        var imgLoad = imagesLoaded('.results')
        //APARENTLY, images.length counts every image on the page, not only the ones in .results
        // So, even if we only have one image, we need to display it, thus hiding the spinner and stuff like that.
        imgLoad.on ('progress', function (inst, image) {
            configImage (image.img);
        });

        imgLoad.on('always', function (inst) {
            init (inst)
        })

        imgLoad.on ('fail', function (inst) {
            init (inst)
        })

})
<|endoftext|>


<commit_before>var app = {};

(function(app) {
   var settings = {
      impulseMagnitude : 0.0001,
      targetFPS : 30,
      stepSize : 4,
      beachHeight: 50
   }

   var Game = function() {};

   var world,
       bodies,
       running,
       gx = [],
       gy = [];

   // Sensor function for when the beachball falls through the floor
   var onFloorHit = function(sensor, bodyA, bodyB) {
      var body;
      if (bodyA.id == '#beachball') { body = bodyA; }
      else if (bodyB.id == '#beachball') { body = bodyB; }

      if (body) {
         $(Game).triggerHandler({type: 'game.wallHit', body: body});
      }
   };

   var onWallHit = function() {
      onFloorHit.apply(this, arguments);
   }

   var worldLastInterval;
   var worldStep = function() {
     world.world.Step(1/30, settings.stepSize, settings.stepSize);

     $.each(world.bodies, function(i, body) {
         if (body.id != undefined) {
            var pos = body.GetPosition(),
                obj = $(body.id);

            obj.css('left', pos.x * world.drawScale - obj.width()/2 + 'px');
            obj.css('top', pos.y * world.drawScale + 'px');
            obj.rotate(body.GetAngle() / Math.PI * 180);
         }
     });

     world.world.ClearForces();
   }

   // Smooth the gravity data from the device and change
   // the gravity of the world.
   var changeGravity = function() {
      var sumx = 0,
          sumy = 0;

      for (var i in gx) { sumx += gx[i]; }
      for (var i in gy) { sumy += gy[i]; }

      sumx /= gx.length;
      sumy /= gy.length;

      gx = [];
      gy = [];

      if (!isNaN(sumx) && !isNaN(sumy)) {
         world.gravity({
            x : sumx,
            y : -sumy
         });

         var angle = Math.atan(sumy/(sumx + 0.00001));

         bodies.beachball.ApplyImpulse({
            x : -Math.cos(angle) * settings.impulseMagnitude,
            y : Math.sin(angle) * settings.impulseMagnitude
         },
         bodies.beachball.GetWorldCenter());
      }
   };

   // The initial position of the beachball
   var beachballPosition;

   Game.drawScale = function() {
      return world.drawScale;
   }

   Game.running = function() {
      return running;
   }

   // Pause the simulation
   $(Game).on('game.pause', function() {
      if (worldLastInterval != undefined) { clearInterval(worldLastInterval); }
      running = false;
   });

   // Start the simulation if it hasn't been started
   $(Game).on('game.start game.startPhysics', function() {
      if (!running) {
         worldLastInterval = setInterval(worldStep, 1000/settings.targetFPS);
         running = true;
      }
   });

   // Reset the simulation
   $(Game).on('game.reset', function(msg) {
      if (worldLastInterval != undefined) { clearInterval(worldLastInterval); }
      bodies.beachball.SetAngularVelocity(0);
      bodies.beachball.SetLinearVelocity({
         x : 0,
         y : 0
      });
      bodies.beachball.SetPositionAndAngle({
         x : world.toMeters(beachballPosition.x),
         y : world.toMeters(beachballPosition.y)
      }, 0);
      running = false;
   });

   // Call when the DOM has been fully loaded and the game needs to
   // be initialized.
   Game.init = function() {
      var w = $(window),
          beachball = $('#beachball'),
          safeZone = $('#safe-zone'),
          dangerZone = $('#danger-zone');

      beachballPosition = {
         x : w.width() / 2 + 'px',
         y : '100px'
      }

      // Set up the box2d components
      world = box2dw.world({
         drawScale : w.width(),
         gravity : {
            x : 0,
            y : 9.8
         }
      });

      // Reposition the sand
      safeZone.css('left', w.width()/2 - safeZone.width()/2 + 'px')
              .css('top', w.height() - settings.beachHeight + 'px');
      dangerZone.css('left', w.width()/2 - dangerZone.width()/2 + 'px')
                .css('top', w.height() - settings.beachHeight + 'px');

      beachball.css('left', w.width()/2 - beachball.width()/2 + 'px');

      var beachRadius = parseInt(/([0-9]+)/.exec(dangerZone.css('-webkit-border-top-left-radius'))[1]),
          beachFlat = dangerZone.width() - beachRadius*2;

      // Set up the bodies.
      // The beach bodies consist of two circles capping the danger zone
      // with a rectangle over the safe zone between them

      var wallThickness = 10;

      bodies = {
         bottomWall : world.body({
            static : true,
            sensorCallback : onFloorHit,
            x : w.width()/2 + 'px',
            y : w.height() + beachball.height() * 2 + 'px',
            width : w.width() * 4 + 'px',
            height : wallThickness + 'px'
         }),
         leftWall : world.body({
            static : true,
            sensorCallback : onWallHit,
            x : -w.width() + 'px',
            y : w.height()/2 + 'px',
            width : wallThickness + 'px',
            height : w.height() * 4 + 'px'
         }),
         rightWall : world.body({
            static : true,
            sensorCallback : onWallHit,
            x : w.width() * 2 + 'px',
            y : w.height() / 2 + 'px',
            width : wallThickness + 'px',
            height : w.height() * 4 + 'px'
         }),
         topWall : world.body({
            static : true,
            sensorCallback: onWallHit,
            x : w.width()/2 + 'px',
            y : -beachball.height() * 2 + 'px',
            width : w.width() * 4 + 'px',
            height : wallThickness + 'px'
         }),
         beachCenter : world.body({
            shape : 'box',
            x : w.width()/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            width : beachFlat + 'px',
            height : beachRadius * 2 + 'px',
            id : '#dangerZone'
         }),
         beachCapRight : world.body({
            shape : 'circle',
            x : w.width()/2 + beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachCapLeft : world.body({
            shape : 'circle',
            x : w.width()/2 - beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachball : world.body({
            shape : 'circle',
            static : false,
            radius : beachball.width() + 'px',
            x : beachballPosition.x,
            y : beachballPosition.y,
            id : '#beachball'
         })
      }

      if (window.DeviceMotionEvent != undefined) {
         var gravityLastInterval,
             gravityDelay = 100;

         window.ondevicemotion = function (e) {
            gx.push(e.accelerationIncludingGravity.x);
            gy.push(e.accelerationIncludingGravity.y);
         }

         $(Game).on('game.reset game.stop game.pause', function(e) {
            if (gravityLastInterval != undefined) { clearInterval(gravityLastInterval); };
         });

         $(Game).on('game.start game.unpause', function(e) {
            gravityLastInterval = setInterval(changeGravity, gravityDelay);
         });
      }
      else {
         $(Game).triggerHandler({type : 'game.notLoaded', reason : 'device gravity not supported in your browser'});
      }
      // Start the simulation
      $(Game).triggerHandler({type : 'game.startPhysics'});
   };

   app.game = Game;
   app.settings = settings;

})(app);

// UI
(function(app) {
   $(document).ready(function() {
      var game = app.game,
          counterLastInterval,
          c = 0,
          delay = 50,
          running = false,
          counter = $('#counter');

      var step = function() {
        counter.text(c.toFixed(2));
        c += 1/delay;
      }

      $(game).on('game.reset game.stop', function(e) {
         if (counterLastInterval != undefined) { clearInterval(counterLastInterval); };
         counter.html(e.message || 'beachball madness!');
         c = 0;
         $('.start').show();
         running = false;
      });

      $(game).on('game.start game.unpause', function() {
         counterLastInterval = setInterval(step, delay);
         step();
         running = true;
      });

      $(game).on('game.pause', function() {
         if (counterLastInterval != undefined) { clearInterval(counterLastInterval); };
         running = false;
      });

      $(game).on('game.notLoaded', function(e) {
         $('#counter').html(e.reason);
         $('.start').fadeOut();
      });

      $(game).on('game.wallHit', function(e) {
         var drawScale = game.drawScale(),
             w = $(window);

         var splashX = ((e.body.GetPosition().x * drawScale) < w.width()/2)
                   ? 0
                   : w.width() - $('#splash').width();

         $('#splash').css('bottom', '0px')
                     .css('left', splashX + 'px')
                     .show(100, function() {
                        $(this).fadeOut(800, function() {
                           $(game).triggerHandler({type : 'game.reset', message : c.toFixed(2) + '
final time
'});
                        });
                     });
      });

      game.init();

      $('.start').click(function() {
         if (!running) {
            running = true;
            $('.start').fadeOut();
            $(game).triggerHandler({type: 'game.start'});
         }
      });
   });
})(app);
<commit_msg>Adjusted title<commit_after>var app = {};

(function(app) {
   var settings = {
      impulseMagnitude : 0.0001,
      targetFPS : 30,
      stepSize : 4,
      beachHeight: 50
   }

   var Game = function() {};

   var world,
       bodies,
       running,
       gx = [],
       gy = [];

   // Sensor function for when the beachball falls through the floor
   var onFloorHit = function(sensor, bodyA, bodyB) {
      var body;
      if (bodyA.id == '#beachball') { body = bodyA; }
      else if (bodyB.id == '#beachball') { body = bodyB; }

      if (body) {
         $(Game).triggerHandler({type: 'game.wallHit', body: body});
      }
   };

   var onWallHit = function() {
      onFloorHit.apply(this, arguments);
   }

   var worldLastInterval;
   var worldStep = function() {
     world.world.Step(1/30, settings.stepSize, settings.stepSize);

     $.each(world.bodies, function(i, body) {
         if (body.id != undefined) {
            var pos = body.GetPosition(),
                obj = $(body.id);

            obj.css('left', pos.x * world.drawScale - obj.width()/2 + 'px');
            obj.css('top', pos.y * world.drawScale + 'px');
            obj.rotate(body.GetAngle() / Math.PI * 180);
         }
     });

     world.world.ClearForces();
   }

   // Smooth the gravity data from the device and change
   // the gravity of the world.
   var changeGravity = function() {
      var sumx = 0,
          sumy = 0;

      for (var i in gx) { sumx += gx[i]; }
      for (var i in gy) { sumy += gy[i]; }

      sumx /= gx.length;
      sumy /= gy.length;

      gx = [];
      gy = [];

      if (!isNaN(sumx) && !isNaN(sumy)) {
         world.gravity({
            x : sumx,
            y : -sumy
         });

         var angle = Math.atan(sumy/(sumx + 0.00001));

         bodies.beachball.ApplyImpulse({
            x : -Math.cos(angle) * settings.impulseMagnitude,
            y : Math.sin(angle) * settings.impulseMagnitude
         },
         bodies.beachball.GetWorldCenter());
      }
   };

   // The initial position of the beachball
   var beachballPosition;

   Game.drawScale = function() {
      return world.drawScale;
   }

   Game.running = function() {
      return running;
   }

   // Pause the simulation
   $(Game).on('game.pause', function() {
      if (worldLastInterval != undefined) { clearInterval(worldLastInterval); }
      running = false;
   });

   // Start the simulation if it hasn't been started
   $(Game).on('game.start game.startPhysics', function() {
      if (!running) {
         worldLastInterval = setInterval(worldStep, 1000/settings.targetFPS);
         running = true;
      }
   });

   // Reset the simulation
   $(Game).on('game.reset', function(msg) {
      if (worldLastInterval != undefined) { clearInterval(worldLastInterval); }
      bodies.beachball.SetAngularVelocity(0);
      bodies.beachball.SetLinearVelocity({
         x : 0,
         y : 0
      });
      bodies.beachball.SetPositionAndAngle({
         x : world.toMeters(beachballPosition.x),
         y : world.toMeters(beachballPosition.y)
      }, 0);
      running = false;
   });

   // Call when the DOM has been fully loaded and the game needs to
   // be initialized.
   Game.init = function() {
      var w = $(window),
          beachball = $('#beachball'),
          safeZone = $('#safe-zone'),
          dangerZone = $('#danger-zone');

      beachballPosition = {
         x : w.width() / 2 + 'px',
         y : '100px'
      }

      // Set up the box2d components
      world = box2dw.world({
         drawScale : w.width(),
         gravity : {
            x : 0,
            y : 9.8
         }
      });

      // Reposition the sand
      safeZone.css('left', w.width()/2 - safeZone.width()/2 + 'px')
              .css('top', w.height() - settings.beachHeight + 'px');
      dangerZone.css('left', w.width()/2 - dangerZone.width()/2 + 'px')
                .css('top', w.height() - settings.beachHeight + 'px');

      beachball.css('left', w.width()/2 - beachball.width()/2 + 'px');

      var beachRadius = parseInt(/([0-9]+)/.exec(dangerZone.css('-webkit-border-top-left-radius'))[1]),
          beachFlat = dangerZone.width() - beachRadius*2;

      // Set up the bodies.
      // The beach bodies consist of two circles capping the danger zone
      // with a rectangle over the safe zone between them

      var wallThickness = 10;

      bodies = {
         bottomWall : world.body({
            static : true,
            sensorCallback : onFloorHit,
            x : w.width()/2 + 'px',
            y : w.height() + beachball.height() * 2 + 'px',
            width : w.width() * 4 + 'px',
            height : wallThickness + 'px'
         }),
         leftWall : world.body({
            static : true,
            sensorCallback : onWallHit,
            x : -w.width() + 'px',
            y : w.height()/2 + 'px',
            width : wallThickness + 'px',
            height : w.height() * 4 + 'px'
         }),
         rightWall : world.body({
            static : true,
            sensorCallback : onWallHit,
            x : w.width() * 2 + 'px',
            y : w.height() / 2 + 'px',
            width : wallThickness + 'px',
            height : w.height() * 4 + 'px'
         }),
         topWall : world.body({
            static : true,
            sensorCallback: onWallHit,
            x : w.width()/2 + 'px',
            y : -beachball.height() * 2 + 'px',
            width : w.width() * 4 + 'px',
            height : wallThickness + 'px'
         }),
         beachCenter : world.body({
            shape : 'box',
            x : w.width()/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            width : beachFlat + 'px',
            height : beachRadius * 2 + 'px',
            id : '#dangerZone'
         }),
         beachCapRight : world.body({
            shape : 'circle',
            x : w.width()/2 + beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachCapLeft : world.body({
            shape : 'circle',
            x : w.width()/2 - beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachball : world.body({
            shape : 'circle',
            static : false,
            radius : beachball.width() + 'px',
            x : beachballPosition.x,
            y : beachballPosition.y,
            id : '#beachball'
         })
      }

      if (window.DeviceMotionEvent != undefined) {
         var gravityLastInterval,
             gravityDelay = 100;

         window.ondevicemotion = function (e) {
            gx.push(e.accelerationIncludingGravity.x);
            gy.push(e.accelerationIncludingGravity.y);
         }

         $(Game).on('game.reset game.stop game.pause', function(e) {
            if (gravityLastInterval != undefined) { clearInterval(gravityLastInterval); };
         });

         $(Game).on('game.start game.unpause', function(e) {
            gravityLastInterval = setInterval(changeGravity, gravityDelay);
         });
      }
      else {
         $(Game).triggerHandler({type : 'game.notLoaded', reason : 'device gravity not supported in your browser'});
      }
      // Start the simulation
      $(Game).triggerHandler({type : 'game.startPhysics'});
   };

   app.game = Game;
   app.settings = settings;

})(app);

// UI
(function(app) {
   $(document).ready(function() {
      var title = 'beachball madness!';

      var game = app.game,
          counterLastInterval,
          c = 0,
          delay = 50,
          running = false,
          counter = $('#counter');

      var step = function() {
        counter.text(c.toFixed(2));
        c += 1/delay;
      }

      $(game).on('game.reset game.stop', function(e) {
         if (counterLastInterval != undefined) { clearInterval(counterLastInterval); };
         counter.html(e.message || title);
         c = 0;
         $('.start').show();
         running = false;
      });

      $(game).on('game.start game.unpause', function() {
         counterLastInterval = setInterval(step, delay);
         step();
         running = true;
      });

      $(game).on('game.pause', function() {
         if (counterLastInterval != undefined) { clearInterval(counterLastInterval); };
         running = false;
      });

      $(game).on('game.notLoaded', function(e) {
         $('#counter').html(e.reason);
         $('.start').fadeOut();
      });

      $(game).on('game.wallHit', function(e) {
         var drawScale = game.drawScale(),
             w = $(window);

         var splashX = ((e.body.GetPosition().x * drawScale) < w.width()/2)
                   ? 0
                   : w.width() - $('#splash').width();

         $('#splash').css('bottom', '0px')
                     .css('left', splashX + 'px')
                     .show(100, function() {
                        $(this).fadeOut(800, function() {
                           $(game).triggerHandler({type : 'game.reset', message : c.toFixed(2) + '
final time
'});
                        });
                     });
      });

      game.init();

      $('.start').click(function() {
         if (!running) {
            running = true;
            $('.start').fadeOut();
            $(game).triggerHandler({type: 'game.start'});
         }
      });

      $('#counter').text(title);
   });
})(app);
<|endoftext|>


<commit_before>define((require, exports, module) => {
  const TRHMasterData = require('app/core/master')
  const TRHRequestRouter = require('./router')
  return class TRHRequestListener {
    static init (store) {
      // Listen Response
      chrome.devtools && chrome.devtools.network.onRequestFinished.addListener((request) => {
        if (store.state.debug.config.replayMode) {
          return
        }
        let tohken = request.request.url.match(/https?:\/\/(.*?)\.touken-ranbu\.jp\/(.*)/)
        if (tohken != null) {
          let server = tohken[1]
          let path = tohken[2]
          if (server  !== 'static' && path.indexOf('?uid') > -1) {
            let action = path.split('?')[0]
            let postData = _.isObject(request['request']['postData'])
              ? _(request['request']['postData']['text'])
                .replace(/%5F/g, '_')
                .split('&')
                .map(o => o.split('='))
              : {}
            request.getContent((content, encoding) => {
              let jsonObj = JSON.parse(content) || {}
              jsonObj['postData'] = _.isArray(postData) ? _.fromPairs(postData) : postData
              if (_(jsonObj).pick(['iv', 'data']).keys().value().length === 2) {
                // Need decrypt
                let iv = jsonObj.iv
                let inflatedData = jsonObj.data
                let decryptData = CryptoJS.AES.decrypt(
                  {
                    ciphertext: CryptoJS.enc.Hex.parse(inflatedData)
                  },
                  CryptoJS.enc.Utf8.parse('9ij8pNKv7qVJnpj4'),
                  {
                    iv: CryptoJS.enc.Hex.parse(iv),
                    mode: CryptoJS.mode.CBC,
                    padding: CryptoJS.pad.NoPadding
                  }
                )
                let textData = CryptoJS.enc.Utf8.stringify(decryptData)
                // Magic ?
                let jsonText = textData.substr(0, textData.lastIndexOf('}') + 1)
                // To Object
                let dataObj = JSON.parse(jsonText)
                // Assign
                _.assign(jsonObj, dataObj)
              }
              if (store.state.debug.config.inRecordMode) {
                store.commit('debug/addRecord', {
                  url: request.request.url,
                  time: Date.now(),
                  content: _.omit(_.cloneDeep(jsonObj), ['data', 'iv'])
                })
              }
              // Route
              TRHRequestRouter.route(action, jsonObj)
            })
          }
        } else {
          if(request.request.url.match(/1f1fa3d5e6cdc140f3c493457940e761\.bin/)) {
            request.getContent((content, encoding) => {
              TRHMasterData.init(content, store)
            })
          }
        }
      })
    }
    static runDebugData (data) {
      let tohken = data.url.match(/https?:\/\/(.*?)\.touken-ranbu\.jp\/(.*)/)
      let path = tohken[2]
      if (path.indexOf('?uid') > -1) {
        let action = path.split('?')[0]
        TRHRequestRouter.route(action, data.content)
      }
    }
  }
})
<commit_msg>fix master data's file name<commit_after>define((require, exports, module) => {
  const TRHMasterData = require('app/core/master')
  const TRHRequestRouter = require('./router')
  return class TRHRequestListener {
    static init (store) {
      // Listen Response
      chrome.devtools && chrome.devtools.network.onRequestFinished.addListener((request) => {
        if (store.state.debug.config.replayMode) {
          return
        }
        let tohken = request.request.url.match(/https?:\/\/(.*?)\.touken-ranbu\.jp\/(.*)/)
        if (tohken != null) {
          let server = tohken[1]
          let path = tohken[2]
          if (server  !== 'static' && path.indexOf('?uid') > -1) {
            let action = path.split('?')[0]
            let postData = _.isObject(request['request']['postData'])
              ? _(request['request']['postData']['text'])
                .replace(/%5F/g, '_')
                .split('&')
                .map(o => o.split('='))
              : {}
            request.getContent((content, encoding) => {
              let jsonObj = JSON.parse(content) || {}
              jsonObj['postData'] = _.isArray(postData) ? _.fromPairs(postData) : postData
              if (_(jsonObj).pick(['iv', 'data']).keys().value().length === 2) {
                // Need decrypt
                let iv = jsonObj.iv
                let inflatedData = jsonObj.data
                let decryptData = CryptoJS.AES.decrypt(
                  {
                    ciphertext: CryptoJS.enc.Hex.parse(inflatedData)
                  },
                  CryptoJS.enc.Utf8.parse('9ij8pNKv7qVJnpj4'),
                  {
                    iv: CryptoJS.enc.Hex.parse(iv),
                    mode: CryptoJS.mode.CBC,
                    padding: CryptoJS.pad.NoPadding
                  }
                )
                let textData = CryptoJS.enc.Utf8.stringify(decryptData)
                // Magic ?
                let jsonText = textData.substr(0, textData.lastIndexOf('}') + 1)
                // To Object
                let dataObj = JSON.parse(jsonText)
                // Assign
                _.assign(jsonObj, dataObj)
              }
              if (store.state.debug.config.inRecordMode) {
                store.commit('debug/addRecord', {
                  url: request.request.url,
                  time: Date.now(),
                  content: _.omit(_.cloneDeep(jsonObj), ['data', 'iv'])
                })
              }
              // Route
              TRHRequestRouter.route(action, jsonObj)
            })
          }
        } else {
          if(request.request.url.match(/d87515923124453e51fdd097ab74289f\.bin/)) {
            request.getContent((content, encoding) => {
              TRHMasterData.init(content, store)
            })
          }
        }
      })
    }
    static runDebugData (data) {
      let tohken = data.url.match(/https?:\/\/(.*?)\.touken-ranbu\.jp\/(.*)/)
      let path = tohken[2]
      if (path.indexOf('?uid') > -1) {
        let action = path.split('?')[0]
        TRHRequestRouter.route(action, data.content)
      }
    }
  }
})
<|endoftext|>


<commit_before>$(function() {
    $(window).unload(function(){
        console.log('leaving');
        $.ajax({
            type: 'POST',
            url: '/api/update_page_view',
            async:false,
            data: {uuid:page_view_uuid, data: '{}'}
        });
    });
});<commit_msg>started adding frontend code to handle updating of page view data<commit_after>$(function() {
    $(window).on("unload", function(e) {
        console.log('leaving');
        $.ajax({
            type: 'POST',
            url: '/api/update_page_view',
            async:false,
            data: {uuid:page_view_uuid, data: '{}'}
        });
    });
});<|endoftext|>


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

    var DrawingArea = function DrawingArea(canvas) {
        this._canvas = canvas;
        this._ctx = canvas.getContext('2d');

        this._enabled = false;

        var that = this;
        canvas.addEventListener('mouseup',
            function(evt) { return that._onmouseup(evt); });
        canvas.addEventListener('mousedown',
            function(evt) { return that._onmousedown(evt); });
        canvas.addEventListener('mousemove',
            function(evt) { that._onmousemove(evt); });
    };

    DrawingArea.prototype._getMouseCoords = function _getMouseCoords(evt) {
        var mouseX, mouseY;
        if (typeof(evt.offsetX) !== 'undefined') {
            mouseX = evt.offsetX;
            mouseY = evt.offsetY;
        } else if (typeof(evt.layerX) !== 'undefined') {
            mouseX = evt.layerX;
            mouseY = evt.layerY;
        }
        return [mouseX, mouseY];
    };

    DrawingArea.prototype._onmousedown = function _onmousedown(evt) {
        if (!this._enabled) { return; }
        var point = this._getMouseCoords(evt);
        this._path = [point];

        // TODO: Start a timer to report partial strokes
    };

    DrawingArea.prototype._onmouseup = function _onmouseup(evt) {
        if (!this._enabled) { return; }
        var point = this._getMouseCoords(evt);
        this._drawPoint(point[0], point[1]);

        if (this.onstroke) {
            this.onstroke(this._path);
        }
    };

    DrawingArea.prototype._onmousemove = function _onmousemove(evt) {
        if (!this._enabled) { return; }
        if (evt.buttons !== 1) {
            return;
        }

        var point = this._getMouseCoords(evt);
        this._drawPoint(point[0], point[1]);
    };

    DrawingArea.prototype._drawPoint = function _drawPoint(mouseX, mouseY) {
        var lastMouse = this._path[this._path.length - 1];
        this._ctx.beginPath();
        this._ctx.moveTo(lastMouse[0], lastMouse[1]);
        this._ctx.lineTo(mouseX, mouseY);
        this._ctx.stroke();
        this._path.push([mouseX, mouseY]);
    };

    DrawingArea.prototype.start = function start() { this._enabled = true; };
    DrawingArea.prototype.stop = function stop() { this._enabled = false; };

    var SketchTable = function SketchTable(target) {
        this._root = $(target);

        /* Initialize the drawing area */
        this._drawing = new DrawingArea(this._root.find('.the-canvas').get(0));
        this._drawing.onstroke = function(path) { console.log(path); };
    };

    SketchTable.prototype._log = function _log() {
        return console.log.apply(console, arguments);
    };

    SketchTable.prototype._send = function _send(obj) {
        this._log('Sending:', obj);
        this._socket.send(JSON.stringify(obj));
    };

    SketchTable.prototype._onopen = function _onopen(evt) {
        this._log('Connecting');

        /* Restablish State */
        if (typeof(this._player_name) !== 'undefined') {
            this._send({verb: 'CONNECT', player_name: this._player_name});
        }

        if (typeof(this._table) !== 'undefined') {
            this.join(this._table);
        }
    };

    SketchTable.prototype._onmessage = function _onmessage(evt) {
        this._log(evt);
    };

    SketchTable.prototype.login = function login(to, player_name) {
        this._url = to;
        this._player_name = player_name;

        var ws = new ReconnectingWebSocket(this._url);

        var that = this;
        ws.onopen = function(evt) { that._onopen(evt); };
        ws.onmessage = function(evt) { that._onmessage(evt); };

        this._socket = ws;
    };

    SketchTable.prototype.join = function join(table) {
        this._table = table;

        this._send({verb: 'JOIN', table: table});
    };

    SketchTable.prototype.leave = function leave() {
        delete this._table;
        this._send({verb: 'LEAVE'});
    };

    SketchTable.prototype.pass = function pass() {
        this._send({verb: 'PASS'});
    };

    global.SketchTable = SketchTable;
}(this));

$(function() {
    'use strict';

});
<commit_msg>Add license for JS<commit_after>/*
 * Copyright 2014 Sam Wilson <tecywiz121@gmail.com>
 *
 * This file is part of SketchWith.Us.
 *
 * SketchWith.Us is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SketchWith.Us is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with SketchWith.Us.  If not, see <http://www.gnu.org/licenses/>.
 */
(function(global) {
    'use strict';

    var DrawingArea = function DrawingArea(canvas) {
        this._canvas = canvas;
        this._ctx = canvas.getContext('2d');

        this._enabled = false;

        var that = this;
        canvas.addEventListener('mouseup',
            function(evt) { return that._onmouseup(evt); });
        canvas.addEventListener('mousedown',
            function(evt) { return that._onmousedown(evt); });
        canvas.addEventListener('mousemove',
            function(evt) { that._onmousemove(evt); });
    };

    DrawingArea.prototype._getMouseCoords = function _getMouseCoords(evt) {
        var mouseX, mouseY;
        if (typeof(evt.offsetX) !== 'undefined') {
            mouseX = evt.offsetX;
            mouseY = evt.offsetY;
        } else if (typeof(evt.layerX) !== 'undefined') {
            mouseX = evt.layerX;
            mouseY = evt.layerY;
        }
        return [mouseX, mouseY];
    };

    DrawingArea.prototype._onmousedown = function _onmousedown(evt) {
        if (!this._enabled) { return; }
        var point = this._getMouseCoords(evt);
        this._path = [point];

        // TODO: Start a timer to report partial strokes
    };

    DrawingArea.prototype._onmouseup = function _onmouseup(evt) {
        if (!this._enabled) { return; }
        var point = this._getMouseCoords(evt);
        this._drawPoint(point[0], point[1]);

        if (this.onstroke) {
            this.onstroke(this._path);
        }
    };

    DrawingArea.prototype._onmousemove = function _onmousemove(evt) {
        if (!this._enabled) { return; }
        if (evt.buttons !== 1) {
            return;
        }

        var point = this._getMouseCoords(evt);
        this._drawPoint(point[0], point[1]);
    };

    DrawingArea.prototype._drawPoint = function _drawPoint(mouseX, mouseY) {
        var lastMouse = this._path[this._path.length - 1];
        this._ctx.beginPath();
        this._ctx.moveTo(lastMouse[0], lastMouse[1]);
        this._ctx.lineTo(mouseX, mouseY);
        this._ctx.stroke();
        this._path.push([mouseX, mouseY]);
    };

    DrawingArea.prototype.start = function start() { this._enabled = true; };
    DrawingArea.prototype.stop = function stop() { this._enabled = false; };

    var SketchTable = function SketchTable(target) {
        this._root = $(target);

        /* Initialize the drawing area */
        this._drawing = new DrawingArea(this._root.find('.the-canvas').get(0));
        this._drawing.onstroke = function(path) { console.log(path); };
    };

    SketchTable.prototype._log = function _log() {
        return console.log.apply(console, arguments);
    };

    SketchTable.prototype._send = function _send(obj) {
        this._log('Sending:', obj);
        this._socket.send(JSON.stringify(obj));
    };

    SketchTable.prototype._onopen = function _onopen(evt) {
        this._log('Connecting');

        /* Restablish State */
        if (typeof(this._player_name) !== 'undefined') {
            this._send({verb: 'CONNECT', player_name: this._player_name});
        }

        if (typeof(this._table) !== 'undefined') {
            this.join(this._table);
        }
    };

    SketchTable.prototype._onmessage = function _onmessage(evt) {
        this._log(evt);
    };

    SketchTable.prototype.login = function login(to, player_name) {
        this._url = to;
        this._player_name = player_name;

        var ws = new ReconnectingWebSocket(this._url);

        var that = this;
        ws.onopen = function(evt) { that._onopen(evt); };
        ws.onmessage = function(evt) { that._onmessage(evt); };

        this._socket = ws;
    };

    SketchTable.prototype.join = function join(table) {
        this._table = table;

        this._send({verb: 'JOIN', table: table});
    };

    SketchTable.prototype.leave = function leave() {
        delete this._table;
        this._send({verb: 'LEAVE'});
    };

    SketchTable.prototype.pass = function pass() {
        this._send({verb: 'PASS'});
    };

    global.SketchTable = SketchTable;
}(this));

$(function() {
    'use strict';

});
<|endoftext|>


<commit_before>// toggle display of all code cells
"use strict";

var toggle_codecells_extension = (function() {

     var show=true;

     function toggle(){
         if (show){
             $('div.input').hide();
             IPython.notebook.metadata.hide_input = true;
         }else{
             $('div.input').show();
             IPython.notebook.metadata.hide_input = false;
         }
         show = !show;
     }

    /**
    * Add run control buttons to toolbar and initialize codecells
    *
    */
    IPython.toolbar.add_buttons_group([
                {
                    id : 'toggle_codecells',
                    label : 'Toggle codecell display',
                    icon : 'fa-bars',
                    callback : toggle
                }
          ]);
    if (IPython.notebook.metadata.hide_input == true) toggle();
})();
<commit_msg>Make the hide_input_all extension work with jupyter<commit_after>// toggle display of all code cells
define([], function () {

	"use strict";

	var toggle_codecells_extension = function() {

		var show=true;

		function toggle(){
			if (show){
				$('div.input').hide();
				IPython.notebook.metadata.hide_input = true;
			}else{
				$('div.input').show();
				IPython.notebook.metadata.hide_input = false;
			}
			show = !show;
		}

		/**
		 * Add run control buttons to toolbar and initialize codecells
		 *
		 */
		IPython.toolbar.add_buttons_group([
            {
                id : 'toggle_codecells',
                label : 'Toggle codecell display',
                icon : 'fa-bars',
                callback : toggle
            }
        ]);
		if (IPython.notebook.metadata.hide_input == true) toggle();
	};

	return {
		load_ipython_extension : toggle_codecells_extension
	}
});
<|endoftext|>


<commit_before>openerp.quickship = function (instance) {
    instance.quickship = {};
    instance.quickship.API  = instance.web.Class.extend({
        init: function(options){
            options = options || {};

            this.connection = new instance.web.JsonRPC();
            this.connection.setup(options.url || 'http://localhost:8069');
            this.model = new instance.web.Model('stock.packages');
            this.notifications = {};
        },

        // Makes a JSON-RPC call to the local OpenERP server.
        message : function(name,params){
            var ret = new $.Deferred();
            var callbacks = this.notifications[name] || [];
            for(var i = 0; i < callbacks.length; i++){
                callbacks[i](params);
            }

            this.connection.rpc('/quickship/' + name, params || {}).done(function(result) {
                ret.resolve(result);
            }).fail(function(error) {
                ret.reject(error);
            });
            return ret;
        },

        // Allows triggers to be set for when particular JSON-RPC function calls are made via 'message.'
        add_notification: function(name, callback){
            if(!this.notifications[name]){
                this.notifications[name] = [];
            }
            this.notifications[name].push(callback);
        },

        // Convenience function for creating a new package.
        create_package: function (sale_order, pkg) {
            return this.model.call("create_package", {
                "sale_order": sale_order,
                "package": pkg
            });
        },

        // Convenience function for getting quotes for a package.
        get_quotes: function (package_id, test) {
            var params = {};

            if (test !== undefined) {
                params['test'] = test;
            }
            return this.model.call('get_quotes', [package_id], params);
        },

        // Convenience function for getting the label for a package.
        get_label: function (package_id, shipping, test) {
            var params = {"shipping": shipping};

            if (test !== undefined) {
                params['test'] = test;
            }
            return this.model.call('get_label', [package_id], params);
        }
    });

    // Client actions
    instance.quickship.create_package = function (parent, action) {
        var api = new instance.quickship.API();
        return api.create_package(action.params.sale_order, action.params.package);
    }
    instance.web.client_actions.add('quickship.create_package', "instance.quickship.create_package");

    instance.quickship.get_label = function (parent, action) {
        var api = new instance.quickship.API();
        return api.get_label(action.params.package_id, action.params.shipping, action.params.test);
    }
    instance.web.client_actions.add('quickship.get_label', "instance.quickship.get_label");

    instance.quickship.get_quotes = function (parent, action) {
        var api = new instance.quickship.API();
        return api.get_quotes(action.params.package_id, action.params.weight, action.params.test);
    }
    instance.web.client_actions.add('quickship.get_quotes', "instance.quickship.get_quotes");

    instance.quickship.WidgetBehaviors = new (function () {
        var that = this;
        that.hash = "";
        that.package_id = null;

        var addEvent = function (elem, evnt, func) {
           if (elem.addEventListener)  // W3C DOM
              elem.addEventListener(evnt,func,false);
           else if (elem.attachEvent) { // IE DOM
              elem.attachEvent("on"+evnt, func);
           }
           else {
              elem[evnt] = func;
           }
        }

        addEvent(window, "hashchange", function () {
            if (window.location.hash != that.hash) {
                that._quickShipWidget.deactivate();
            }
        });

        var api = new instance.quickship.API();
        var printerAPI = new instance.printer_proxy.Printer({name: "zebra"});

        this._quickShipWidget = new openerp.quickship.QuickShipWidget(
            new instance.scale_proxy.Scale()
        );

        this._quickShipWidget.on("scanned", function (e, code) {
            $("#sale_order").text("Sale Order: " + code);
        });

        this._quickShipWidget.on("weighed", function (e, weight) {
            $("#weight").text(weight.value + " " + weight.unit + "s");
        });

        this._quickShipWidget.on("awaitingLabel", function (e, inputs) {
            includeLibraryMail = $("#no_library_mail:checked").length == 0;

            api.create_package(inputs.keyboard, {'weight': inputs.weight})
                .done(function (response) {
                   if (response.success) {
                       that.package_id = response.id;

                       api.get_quotes(response.id)
                           .done(function (result) {
                               that.quotes = [];

                               $(result.quotes).each(function (i, quote) {
                                   if (quote.service != "Library Mail" || includeLibraryMail) {
                                       that.quotes.push(quote);
                                       $("#quotes_list").append(
                                           "
" + quote.service + " - $" + quote.price.toFixed(2) + "
"
                                       );
                                   }
                               });
                               $("#step-2").show();
                           });

                   } else {
                       that.package_id = null;
                       console.log(response);
                       $("#sale_order").text(response.error);
                       that._quickShipWidget.resetState();
                       $("#step-2").hide();
                   }
                });
        });

        this._quickShipWidget.on("labelSelected", function (e, input) {
            if (!that.package_id) {
                console.log("No active package!");
            }

            if (isNaN(parseFloat(input)) || !isFinite(input)) {
                console.log("'" + input + "' is not a valid number.");
                return;
            }

            var quoteIndex = (parseFloat(input) - 1);
            if ((quoteIndex % 1) != 0 || quoteIndex >= that.quotes.length) {
                console.log("'" + input + "' is not a valid label selection.");
            }

            var quote = that.quotes[quoteIndex];

            api.get_label(that.package_id, quote)
                .done(function (result) {
                    if (result.errors) {
                        console.log(result);
                        instance.web.Notification.warn("Error", "Failed to get label. See JS console for details.")
                    } else {
                        printerAPI.print("EPL2", result.label);
                    }
                });

            $("#sale_order").text("Scan another barcode for more quotes...");
            $("#step-2").hide();
        });

        this.activate = function () {
            that._quickShipWidget.activate();
        };

        return this;
    })();

    instance.quickship.Widget = instance.web.Widget.extend({
        template: "quickship.widget",
        start: function () {
            instance.quickship.WidgetBehaviors.hash = window.location.hash;
            instance.quickship.WidgetBehaviors.activate();
            $("#step-2").hide();
        }
    });

    instance.web.client_actions.add('quickship.Widget', 'instance.quickship.Widget');
};
<commit_msg>Reset widget state after printing label.<commit_after>openerp.quickship = function (instance) {
    instance.quickship = {};
    instance.quickship.API  = instance.web.Class.extend({
        init: function(options){
            options = options || {};

            this.connection = new instance.web.JsonRPC();
            this.connection.setup(options.url || 'http://localhost:8069');
            this.model = new instance.web.Model('stock.packages');
            this.notifications = {};
        },

        // Makes a JSON-RPC call to the local OpenERP server.
        message : function(name,params){
            var ret = new $.Deferred();
            var callbacks = this.notifications[name] || [];
            for(var i = 0; i < callbacks.length; i++){
                callbacks[i](params);
            }

            this.connection.rpc('/quickship/' + name, params || {}).done(function(result) {
                ret.resolve(result);
            }).fail(function(error) {
                ret.reject(error);
            });
            return ret;
        },

        // Allows triggers to be set for when particular JSON-RPC function calls are made via 'message.'
        add_notification: function(name, callback){
            if(!this.notifications[name]){
                this.notifications[name] = [];
            }
            this.notifications[name].push(callback);
        },

        // Convenience function for creating a new package.
        create_package: function (sale_order, pkg) {
            return this.model.call("create_package", {
                "sale_order": sale_order,
                "package": pkg
            });
        },

        // Convenience function for getting quotes for a package.
        get_quotes: function (package_id, test) {
            var params = {};

            if (test !== undefined) {
                params['test'] = test;
            }
            return this.model.call('get_quotes', [package_id], params);
        },

        // Convenience function for getting the label for a package.
        get_label: function (package_id, shipping, test) {
            var params = {"shipping": shipping};

            if (test !== undefined) {
                params['test'] = test;
            }
            return this.model.call('get_label', [package_id], params);
        }
    });

    // Client actions
    instance.quickship.create_package = function (parent, action) {
        var api = new instance.quickship.API();
        return api.create_package(action.params.sale_order, action.params.package);
    }
    instance.web.client_actions.add('quickship.create_package', "instance.quickship.create_package");

    instance.quickship.get_label = function (parent, action) {
        var api = new instance.quickship.API();
        return api.get_label(action.params.package_id, action.params.shipping, action.params.test);
    }
    instance.web.client_actions.add('quickship.get_label', "instance.quickship.get_label");

    instance.quickship.get_quotes = function (parent, action) {
        var api = new instance.quickship.API();
        return api.get_quotes(action.params.package_id, action.params.weight, action.params.test);
    }
    instance.web.client_actions.add('quickship.get_quotes', "instance.quickship.get_quotes");

    instance.quickship.WidgetBehaviors = new (function () {
        var that = this;
        that.hash = "";
        that.package_id = null;

        var addEvent = function (elem, evnt, func) {
           if (elem.addEventListener)  // W3C DOM
              elem.addEventListener(evnt,func,false);
           else if (elem.attachEvent) { // IE DOM
              elem.attachEvent("on"+evnt, func);
           }
           else {
              elem[evnt] = func;
           }
        }

        addEvent(window, "hashchange", function () {
            if (window.location.hash != that.hash) {
                that._quickShipWidget.deactivate();
            }
        });

        var api = new instance.quickship.API();
        var printerAPI = new instance.printer_proxy.Printer({name: "zebra"});

        this._quickShipWidget = new openerp.quickship.QuickShipWidget(
            new instance.scale_proxy.Scale()
        );

        this._quickShipWidget.on("scanned", function (e, code) {
            $("#sale_order").text("Sale Order: " + code);
        });

        this._quickShipWidget.on("weighed", function (e, weight) {
            $("#weight").text(weight.value + " " + weight.unit + "s");
        });

        this._quickShipWidget.on("awaitingLabel", function (e, inputs) {
            includeLibraryMail = $("#no_library_mail:checked").length == 0;

            api.create_package(inputs.keyboard, {'weight': inputs.weight})
                .done(function (response) {
                   if (response.success) {
                       that.package_id = response.id;

                       api.get_quotes(response.id)
                           .done(function (result) {
                               that.quotes = [];

                               $(result.quotes).each(function (i, quote) {
                                   if (quote.service != "Library Mail" || includeLibraryMail) {
                                       that.quotes.push(quote);
                                       $("#quotes_list").append(
                                           "
" + quote.service + " - $" + quote.price.toFixed(2) + "
"
                                       );
                                   }
                               });
                               $("#step-2").show();
                           });

                   } else {
                       that.package_id = null;
                       console.log(response);
                       $("#sale_order").text(response.error);
                       that._quickShipWidget.resetState();
                       $("#step-2").hide();
                   }
                });
        });

        this._quickShipWidget.on("labelSelected", function (e, input) {
            if (!that.package_id) {
                console.log("No active package!");
            }

            if (isNaN(parseFloat(input)) || !isFinite(input)) {
                console.log("'" + input + "' is not a valid number.");
                return;
            }

            var quoteIndex = (parseFloat(input) - 1);
            if ((quoteIndex % 1) != 0 || quoteIndex >= that.quotes.length) {
                console.log("'" + input + "' is not a valid label selection.");
            }

            var quote = that.quotes[quoteIndex];

            api.get_label(that.package_id, quote)
                .done(function (result) {
                    if (result.errors) {
                        console.log(result);
                        instance.web.Notification.warn("Error", "Failed to get label. See JS console for details.")
                    } else {
                        printerAPI.print("EPL2", result.label);
                    }
                });

            that.quotes = [];
            that.package_id = null;
            $("#quotes_list li").remove();
            that._quickShipWidget.resetState();
            $("#sale_order").text("Scan another barcode for more quotes...");
            $("#step-2").hide();
        });

        this.activate = function () {
            that._quickShipWidget.activate();
        };

        return this;
    })();

    instance.quickship.Widget = instance.web.Widget.extend({
        template: "quickship.widget",
        start: function () {
            instance.quickship.WidgetBehaviors.hash = window.location.hash;
            instance.quickship.WidgetBehaviors.activate();
            $("#step-2").hide();
        }
    });

    instance.web.client_actions.add('quickship.Widget', 'instance.quickship.Widget');
};
<|endoftext|>