<commit_before>window._config = {
  isDebug: location.hash.slice(1) === 'is-debug' ||
    ['localhost', 'dev.bootstrap-table.com'].indexOf(location.hostname) > -1,
  cdnUrl: 'https://unpkg.com/bootstrap-table@1.15.2/dist/',
  localUrl: '../bootstrap-table/dist/'
}

function _getLink(file) {
  var url = file
  if (!/^http/.test(file)) {
    url = window._config.cdnUrl + file

    if (window._config.isDebug) {
      url = window._config.localUrl + file.replace(/\.min/, '') + '?t=' + (+new Date())
    }
  }
  return '<link href="' + url + '" rel="stylesheet">'
}

function _getScript(file, isScriptTag) {
  var url = file
  if (!/^http/.test(file)) {
    url = window._config.cdnUrl + file

    if (window._config.isDebug) {
      url = window._config.localUrl + file + '?t=' + (+new Date())
    }
  }
  if (isScriptTag) {
    return ''
  }
  return url
}

function _link(file) {
  $('head').append(_getLink(file))
}

function _script(file, callback) {
  var head = document.getElementsByTagName('head')[0]
  var script = document.createElement('script')

  // if (window._config.isDebug && !/^http/.test(file)) {
    // script.type = 'module'
  // }

  script.src = _getScript(file)

  var done = false
  // Attach handlers for all browsers
  script.onload = script.onreadystatechange = function() {
    if (!done && (!this.readyState ||
      this.readyState === 'loaded' || this.readyState === 'complete')) {
      done = true
      if (callback)
        callback()

      // Handle memory leak in IE
      script.onload = script.onreadystatechange = null
    }
  }

  head.appendChild(script)
}

function _scripts(scripts, callback) {
  if (!scripts.length) {
    return callback()
  }

  var eachSeries = function (arr, iterator, callback_) {
    var callback = callback_ || function () {}
    if (!arr.length) {
      return callback()
    }
    var completed = 0
    var iterate = function () {
      iterator(arr[completed], function (err) {
        if (err) {
          callback(err)
          callback = function () {}
        } else {
          completed += 1
          if (completed >= arr.length) {
            callback(null)
          } else {
            iterate()
          }
        }
      })
    }
    iterate()
  }

  eachSeries(scripts, _script, function () {
    callback()
  })
}

function _themeUpdate(data) {
  if (/bootstrap3.html$/.test(location.pathname)) {
    return data.replace(/btn-secondary/g, 'btn-default')
  }
  if (/semantic.html$/.test(location.pathname)) {
    return data.replace(/btn btn-secondary/g, 'ui button')
      .replace(/btn btn-danger/g, 'ui red button')
      .replace(/select class="form-control"/g, 'select class="ui dropdown"')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/semantic/bootstrap-table-semantic.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/semantic/bootstrap-table-semantic.min.css\'')
  }
  if (/bulma.html$/.test(location.pathname)) {
    return data.replace(/btn btn-secondary/g, 'button')
      .replace(/btn btn-danger/g, 'button is-danger')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/bulma/bootstrap-table-bulma.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/bulma/bootstrap-table-bulma.min.css\'')
  }
  if (/materialize.html$/.test(location.pathname)) {
    return data.replace(/class="select"/g, 'class="input-field"')
      .replace(/btn btn-secondary/g, 'waves-effect waves-light btn')
      .replace(/btn btn-danger/g, 'waves-effect waves-light btn')
      .replace('', 'star')
      .replace('', 'clear')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/materialize/bootstrap-table-materialize.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/materialize/bootstrap-table-materialize.min.css\'')
  }
  if (/foundation.html$/.test(location.pathname)) {
    return data.replace(/btn btn-secondary/g, 'button')
      .replace(/btn btn-danger/g, 'alert button')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/foundation/bootstrap-table-foundation.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/foundation/bootstrap-table-foundation.min.css\'')
  }
  return data
}

function _beautifySource(data) {
  var lines = data.split('\n')
  var scriptStart = lines.indexOf('', scriptStart)
  var strings = lines.slice(scriptStart + 1, scriptEnd)
  strings = $.map(strings, function (s) {
    return $.trim(s)
  })
  /* eslint-disable no-control-regex */
  var obj = eval('(' + strings.join('').replace(/[^\u0000-\u007E]/g, '')
    .replace(/^init\((.*)\)$/, '$1') + ')')

  var result = []
  result = result.concat($.map(obj.links, _getLink))
  result.push('')
  result = result.concat($.map(obj.scripts, function (script) {
    return _getScript(script, true)
  }))
  lines = result.concat(lines.slice(scriptEnd + 1))

  var mountedStart = lines.indexOf('  function mounted() {')
  var mountedEnd = lines.indexOf('  }', mountedStart)
  lines[mountedStart] = '  $(function() {'
  lines[mountedEnd] = '  })'

  return lines.join('\n')
}

$(function () {
  var run = function () {
    var query = {}
    location.search.substring(1).split('&').forEach(function (item) {
      query[item.split('=')[0]] = item.split('=')[1]
    })
    var url = query.url
    var isSource = location.hash.substring(1) === 'view-source'

    delete query.url

    $.ajax({
      type: 'GET',
      url: url + '?' + $.param(query),
      dataType: 'html',
      global: false,
      cache: true, // (warning: setting it to false will cause a timestamp and will call the request twice)
      success: function (_data) {
        var data = _themeUpdate(_data)

        if (isSource) {
          $('#example').hide().html(data)
          $('.source-pre').show()
          $('#source').text(_beautifySource(data))
          window.hljs.initHighlightingOnLoad()
        } else {
          $('#example').html(data.replace(/data-toggle="table"/g, 'data-toggle="bootstrap-table"'))
        }
      },
      error: function () {
        parent.location.href = 'index.html'
      }
    })
  }

  window.addEventListener('popstate', run)
  run()
})

window.init = function (options_) {
  var options = $.extend({
    title: '',
    desc: '',
    links: [],
    scripts: [],
    callback: function () {
      if ($('[data-toggle="bootstrap-table"]').length) {
        $('[data-toggle="bootstrap-table"]').bootstrapTable()
      }
      if (/materialize.html$/.test(location.pathname)) {
        $('select').formSelect()
      }
      if (typeof window.mounted === 'function') {
        window.mounted()
      }
    }
  }, options_)

  $('.bd-title span').html(options.title)
  $('.bd-lead').html(options.desc)
  $.each(options.links, function (i, file) {
    _link(file)
  })
  _scripts(options.scripts, options.callback)
}
<commit_msg>Update template<commit_after>window._config = {
  isDebug: location.hash.slice(1) === 'is-debug' ||
    ['localhost', 'dev.bootstrap-table.com'].indexOf(location.hostname) > -1,
  cdnUrl: 'https://unpkg.com/bootstrap-table@1.15.1/dist/',
  localUrl: '../bootstrap-table/src/'
}

function _getLink(file) {
  var url = file
  if (!/^http/.test(file)) {
    url = window._config.cdnUrl + file

    if (window._config.isDebug) {
      url = window._config.localUrl + file.replace(/\.min/, '') + '?t=' + (+new Date())
    }
  }
  return '<link href="' + url + '" rel="stylesheet">'
}

function _getScript(file, isScriptTag) {
  var url = file
  if (!/^http/.test(file)) {
    url = window._config.cdnUrl + file

    if (window._config.isDebug) {
      url = window._config.localUrl + file.replace(/\.min/, '') + '?t=' + (+new Date())
    }
  }
  if (isScriptTag) {
    return ''
  }
  return url
}

function _link(file) {
  $('head').append(_getLink(file))
}

function _script(file, callback) {
  var head = document.getElementsByTagName('head')[0]
  var script = document.createElement('script')

  // if (window._config.isDebug && !/^http/.test(file)) {
    // script.type = 'module'
  // }

  script.src = _getScript(file)

  var done = false
  // Attach handlers for all browsers
  script.onload = script.onreadystatechange = function() {
    if (!done && (!this.readyState ||
      this.readyState === 'loaded' || this.readyState === 'complete')) {
      done = true
      if (callback)
        callback()

      // Handle memory leak in IE
      script.onload = script.onreadystatechange = null
    }
  }

  head.appendChild(script)
}

function _scripts(scripts, callback) {
  if (!scripts.length) {
    return callback()
  }

  var eachSeries = function (arr, iterator, callback_) {
    var callback = callback_ || function () {}
    if (!arr.length) {
      return callback()
    }
    var completed = 0
    var iterate = function () {
      iterator(arr[completed], function (err) {
        if (err) {
          callback(err)
          callback = function () {}
        } else {
          completed += 1
          if (completed >= arr.length) {
            callback(null)
          } else {
            iterate()
          }
        }
      })
    }
    iterate()
  }

  eachSeries(scripts, _script, function () {
    callback()
  })
}

function _themeUpdate(data) {
  if (/bootstrap3.html$/.test(location.pathname)) {
    return data.replace(/btn-secondary/g, 'btn-default')
  }
  if (/semantic.html$/.test(location.pathname)) {
    return data.replace(/btn btn-secondary/g, 'ui button')
      .replace(/btn btn-danger/g, 'ui red button')
      .replace(/select class="form-control"/g, 'select class="ui dropdown"')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/semantic/bootstrap-table-semantic.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/semantic/bootstrap-table-semantic.min.css\'')
  }
  if (/bulma.html$/.test(location.pathname)) {
    return data.replace(/btn btn-secondary/g, 'button')
      .replace(/btn btn-danger/g, 'button is-danger')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/bulma/bootstrap-table-bulma.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/bulma/bootstrap-table-bulma.min.css\'')
  }
  if (/materialize.html$/.test(location.pathname)) {
    return data.replace(/class="select"/g, 'class="input-field"')
      .replace(/btn btn-secondary/g, 'waves-effect waves-light btn')
      .replace(/btn btn-danger/g, 'waves-effect waves-light btn')
      .replace('', 'star')
      .replace('', 'clear')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/materialize/bootstrap-table-materialize.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/materialize/bootstrap-table-materialize.min.css\'')
  }
  if (/foundation.html$/.test(location.pathname)) {
    return data.replace(/btn btn-secondary/g, 'button')
      .replace(/btn btn-danger/g, 'alert button')
      .replace(/'bootstrap-table.min.js'/, '\'bootstrap-table.min.js\',\n      \'themes/foundation/bootstrap-table-foundation.min.js\'')
      .replace(/'bootstrap-table.min.css'/, '\'themes/foundation/bootstrap-table-foundation.min.css\'')
  }
  return data
}

function _beautifySource(data) {
  var lines = data.split('\n')
  var scriptStart = lines.indexOf('', scriptStart)
  var strings = lines.slice(scriptStart + 1, scriptEnd)
  strings = $.map(strings, function (s) {
    return $.trim(s)
  })
  /* eslint-disable no-control-regex */
  var obj = eval('(' + strings.join('').replace(/[^\u0000-\u007E]/g, '')
    .replace(/^init\((.*)\)$/, '$1') + ')')

  var result = []
  result = result.concat($.map(obj.links, _getLink))
  result.push('')
  result = result.concat($.map(obj.scripts, function (script) {
    return _getScript(script, true)
  }))
  lines = result.concat(lines.slice(scriptEnd + 1))

  var mountedStart = lines.indexOf('  function mounted() {')
  var mountedEnd = lines.indexOf('  }', mountedStart)
  lines[mountedStart] = '  $(function() {'
  lines[mountedEnd] = '  })'

  return lines.join('\n')
}

$(function () {
  var run = function () {
    var query = {}
    location.search.substring(1).split('&').forEach(function (item) {
      query[item.split('=')[0]] = item.split('=')[1]
    })
    var url = query.url
    var isSource = location.hash.substring(1) === 'view-source'

    delete query.url

    $.ajax({
      type: 'GET',
      url: url + '?' + $.param(query),
      dataType: 'html',
      global: false,
      cache: true, // (warning: setting it to false will cause a timestamp and will call the request twice)
      success: function (_data) {
        var data = _themeUpdate(_data)

        if (isSource) {
          $('#example').hide().html(data)
          $('.source-pre').show()
          $('#source').text(_beautifySource(data))
          window.hljs.initHighlightingOnLoad()
        } else {
          $('#example').html(data.replace(/data-toggle="table"/g, 'data-toggle="bootstrap-table"'))
        }
      },
      error: function () {
        parent.location.href = 'index.html'
      }
    })
  }

  window.addEventListener('popstate', run)
  run()
})

window.init = function (options_) {
  var options = $.extend({
    title: '',
    desc: '',
    links: [],
    scripts: [],
    callback: function () {
      if ($('[data-toggle="bootstrap-table"]').length) {
        $('[data-toggle="bootstrap-table"]').bootstrapTable()
      }
      if (/materialize.html$/.test(location.pathname)) {
        $('select').formSelect()
      }
      if (typeof window.mounted === 'function') {
        window.mounted()
      }
    }
  }, options_)

  $('.bd-title span').html(options.title)
  $('.bd-lead').html(options.desc)
  $.each(options.links, function (i, file) {
    _link(file)
  })
  _scripts(options.scripts, options.callback)
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

const { Task } = require("devtools/shared/task");
const { LocalizationHelper } = require("devtools/shared/l10n");
const { gDevTools } = require("devtools/client/framework/devtools");
const { TargetFactory } = require("devtools/client/framework/target");
const { Toolbox } = require("devtools/client/framework/toolbox");
loader.lazyRequireGetter(this, "openContentLink", "devtools/client/shared/link", true);

const DBG_STRINGS_URI = "devtools/client/locales/debugger.properties";
const L10N = new LocalizationHelper(DBG_STRINGS_URI);

function DebuggerPanel(iframeWindow, toolbox) {
  this.panelWin = iframeWindow;
  this.panelWin.L10N = L10N;
  this.toolbox = toolbox;
}

DebuggerPanel.prototype = {
  open: async function() {
    if (!this.toolbox.target.isRemote) {
      await this.toolbox.target.attach();
    }

    const {
      actions,
      store,
      selectors,
      client
    } = await this.panelWin.Debugger.bootstrap({
      threadClient: this.toolbox.threadClient,
      tabTarget: this.toolbox.target,
      debuggerClient: this.toolbox.target.client,
      sourceMaps: this.toolbox.sourceMapService,
      toolboxActions: {
        // Open a link in a new browser tab.
        openLink: this.openLink.bind(this),
        openWorkerToolbox: this.openWorkerToolbox.bind(this)
      }
    });

    this._actions = actions;
    this._store = store;
    this._selectors = selectors;
    this._client = client;
    this.isReady = true;
    return this;
  },

  getVarsForTests() {
    return {
      store: this._store,
      selectors: this._selectors,
      actions: this._actions,
      client: this._client
    };
  },

  _getState: function() {
    return this._store.getState();
  },

  openLink: function(url) {
    openContentLink(url);
  },

  openWorkerToolbox: async function(worker) {
    const [response, workerClient] =
      await this.toolbox.target.client.attachWorker(worker.actor);
    const workerTarget = TargetFactory.forWorker(workerClient);
    const toolbox = await gDevTools.showToolbox(workerTarget, "jsdebugger", Toolbox.HostType.WINDOW);
    toolbox.once("destroy", () => workerClient.detach());
  },

  getFrames: function() {
    let frames = this._selectors.getFrames(this._getState());

    // Frames is null when the debugger is not paused.
    if (!frames) {
      return {
        frames: [],
        selected: -1
      };
    }

    const selectedFrame = this._selectors.getSelectedFrame(this._getState());
    const selected = frames.findIndex(frame => frame.id == selectedFrame.id);

    frames.forEach(frame => {
      frame.actor = frame.id;
    });

    return { frames, selected };
  },

  getMappedExpression(expression) {
    return this._actions.getMappedExpression(expression);
  },

  isPaused() {
    return this._selectors.isPaused(this._getState());
  },

  selectSource(url, line) {
    this._actions.selectSourceURL(url, { line });
  },

  getSource(sourceURL) {
    return this._selectors.getSourceByURL(this._getState(), sourceURL);
  },

  destroy: function() {
    this.panelWin.Debugger.destroy();
    this.emit("destroyed");
  }
};

exports.DebuggerPanel = DebuggerPanel;
<commit_msg>[sync]  Bug 1397020 - Remove useless calls to TabTarget.attach r=yulia<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

const { Task } = require("devtools/shared/task");
const { LocalizationHelper } = require("devtools/shared/l10n");
const { gDevTools } = require("devtools/client/framework/devtools");
const { TargetFactory } = require("devtools/client/framework/target");
const { Toolbox } = require("devtools/client/framework/toolbox");
loader.lazyRequireGetter(this, "openContentLink", "devtools/client/shared/link", true);

const DBG_STRINGS_URI = "devtools/client/locales/debugger.properties";
const L10N = new LocalizationHelper(DBG_STRINGS_URI);

function DebuggerPanel(iframeWindow, toolbox) {
  this.panelWin = iframeWindow;
  this.panelWin.L10N = L10N;
  this.toolbox = toolbox;
}

DebuggerPanel.prototype = {
  open: async function() {
    const {
      actions,
      store,
      selectors,
      client
    } = await this.panelWin.Debugger.bootstrap({
      threadClient: this.toolbox.threadClient,
      tabTarget: this.toolbox.target,
      debuggerClient: this.toolbox.target.client,
      sourceMaps: this.toolbox.sourceMapService,
      toolboxActions: {
        // Open a link in a new browser tab.
        openLink: this.openLink.bind(this),
        openWorkerToolbox: this.openWorkerToolbox.bind(this)
      }
    });

    this._actions = actions;
    this._store = store;
    this._selectors = selectors;
    this._client = client;
    this.isReady = true;
    return this;
  },

  getVarsForTests() {
    return {
      store: this._store,
      selectors: this._selectors,
      actions: this._actions,
      client: this._client
    };
  },

  _getState: function() {
    return this._store.getState();
  },

  openLink: function(url) {
    openContentLink(url);
  },

  openWorkerToolbox: async function(worker) {
    const [response, workerClient] =
      await this.toolbox.target.client.attachWorker(worker.actor);
    const workerTarget = TargetFactory.forWorker(workerClient);
    const toolbox = await gDevTools.showToolbox(workerTarget, "jsdebugger", Toolbox.HostType.WINDOW);
    toolbox.once("destroy", () => workerClient.detach());
  },

  getFrames: function() {
    let frames = this._selectors.getFrames(this._getState());

    // Frames is null when the debugger is not paused.
    if (!frames) {
      return {
        frames: [],
        selected: -1
      };
    }

    const selectedFrame = this._selectors.getSelectedFrame(this._getState());
    const selected = frames.findIndex(frame => frame.id == selectedFrame.id);

    frames.forEach(frame => {
      frame.actor = frame.id;
    });

    return { frames, selected };
  },

  getMappedExpression(expression) {
    return this._actions.getMappedExpression(expression);
  },

  isPaused() {
    return this._selectors.isPaused(this._getState());
  },

  selectSource(url, line) {
    this._actions.selectSourceURL(url, { line });
  },

  getSource(sourceURL) {
    return this._selectors.getSourceByURL(this._getState(), sourceURL);
  },

  destroy: function() {
    this.panelWin.Debugger.destroy();
    this.emit("destroyed");
  }
};

exports.DebuggerPanel = DebuggerPanel;
<|endoftext|>


<commit_before>define([
    '/bower_components/tweetnacl/nacl-fast.min.js',
], function () {
    var Nacl = window.nacl;

    var uid = function () {
        return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
            .toString(32).replace(/\./g, '');
    };

    var signMsg = function (data, signKey) {
        var buffer = Nacl.util.decodeUTF8(JSON.stringify(data));
        return Nacl.util.encodeBase64(Nacl.sign.detached(buffer, signKey));
    };

/*
types of messages:
    pin -> hash
    unpin -> hash
    getHash -> hash
    getTotalSize -> bytes
    getFileSize -> bytes
*/

    var sendMsg = function (ctx, data, cb) {
        var network = ctx.network;
        var hkn = network.historyKeeper;
        var txid = uid();

        ctx.pending[txid] = cb;
        return network.sendto(hkn, JSON.stringify([txid, data]));
    };

    var parse = function (msg) {
        try {
            return JSON.parse(msg);
        } catch (e) {
            return null;
        }
    };

    var onMsg = function (ctx, msg) {
        var parsed = parse(msg);

        if (!parsed) {
            return void console.error(new Error('could not parse message: %s', msg));
        }

        var txid = parsed[0];
        var cookie = parsed[1];

        var pending = ctx.pending[txid];

        if (!(parsed && parsed.slice)) {
            // RPC responses are arrays. this message isn't meant for us.
            return;
        }

        var response = parsed.slice(2);

        if (typeof(pending) === 'function') {
            if (parsed[1] === 'ERROR') {
                return void pending(parsed[2]);
            } else {
                // update the cookie
                if (/\|/.test(cookie)) {
                    if (ctx.cookie !== cookie) {
                        ctx.cookie = cookie;
                    }
                }
            }
            pending(void 0, response);
        }
        //else { console.log("No callback provided"); }
    };

    var create = function (network, edPrivateKey, edPublicKey, cb) {
        var signKey;

        try {
            signKey = Nacl.util.decodeBase64(edPrivateKey);
            if (signKey.length !== 64) {
                throw new Error('private key did not match expected length of 64');
            }
        } catch (err) {
            return void cb(err);
        }

        var pubBuffer;
        try {
            pubBuffer = Nacl.util.decodeBase64(edPublicKey);
            if (pubBuffer.length !== 32) {
                return void cb('expected public key to be 32 uint');
            }
        } catch (err) {
            return void cb(err);
        }

        var ctx = {
            network: network,
            timeouts: {}, // timeouts
            pending: {}, // callbacks
            cookie: null,
            connected: true,
        };

        var send = function (type, msg, cb) {
            if (!ctx.connected && type !== 'COOKIE') {
                return void window.setTimeout(function () {
                    cb('DISCONNECTED');
                });
            }

            // construct a signed message...

            var data = [type, msg];
            if (ctx.cookie && ctx.cookie.join) {
                data.unshift(ctx.cookie.join('|'));
            } else {
                data.unshift(ctx.cookie);
            }

            var sig = signMsg(data, signKey);

            data.unshift(edPublicKey);
            data.unshift(sig);

            // [sig, edPublicKey, cookie, type, msg]
            return sendMsg(ctx, data, cb);
        };

        send.unauthenticated = function (type, msg, cb) {
            if (!ctx.connected) {
                return void window.setTimeout(function () {
                    cb('DISCONNECTED');
                });
            }

            // construct an unsigned message
            var data = [null, edPublicKey, null, type, msg];
            if (ctx.cookie && ctx.cookie.join) {
                data[2] = ctx.cookie.join('|');
            } else {
                data[2] = ctx.cookie;
            }

            return sendMsg(ctx, data, cb);
        };

        network.on('message', function (msg) {
            onMsg(ctx, msg);
        });

        network.on('disconnect', function () {
            ctx.connected = false;
        });

        network.on('reconnect', function () {
            send('COOKIE', "", function (e) {
                if (e) { return void cb(e); }
                ctx.connected = true;
            });
        });

        send('COOKIE', "", function (e) {
            if (e) { return void cb(e); }
            // callback to provide 'send' method to whatever needs it
            cb(void 0, { send: send, });
        });
    };

    return { create: create };
});
<commit_msg>ask for new cookies and resend commands on NO_COOKIE errors<commit_after>define([
    '/bower_components/tweetnacl/nacl-fast.min.js',
], function () {
    var Nacl = window.nacl;

    var uid = function () {
        return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
            .toString(32).replace(/\./g, '');
    };

    var signMsg = function (data, signKey) {
        var buffer = Nacl.util.decodeUTF8(JSON.stringify(data));
        return Nacl.util.encodeBase64(Nacl.sign.detached(buffer, signKey));
    };

/*
types of messages:
    pin -> hash
    unpin -> hash
    getHash -> hash
    getTotalSize -> bytes
    getFileSize -> bytes
*/

    var sendMsg = function (ctx, data, cb) {
        var network = ctx.network;
        var hkn = network.historyKeeper;
        var txid = uid();

        var pending = ctx.pending[txid] = function (err, response) {
            cb(err, response);
        };
        pending.data = data;
        pending.called = 0;
        return network.sendto(hkn, JSON.stringify([txid, data]));
    };

    var parse = function (msg) {
        try {
            return JSON.parse(msg);
        } catch (e) {
            return null;
        }
    };

    var onMsg = function (ctx, msg) {
        var parsed = parse(msg);

        if (!parsed) {
            return void console.error(new Error('could not parse message: %s', msg));
        }

        var txid = parsed[0];
        var cookie = parsed[1];

        var pending = ctx.pending[txid];

        if (!(parsed && parsed.slice)) {
            // RPC responses are arrays. this message isn't meant for us.
            return;
        }

        var response = parsed.slice(2);

        if (typeof(pending) === 'function') {
            if (parsed[1] === 'ERROR') {
                if (parsed[2] === 'NO_COOKIE') {
                    return void ctx.send('COOKIE', "", function (e) {
                        if (e) {
                            console.error(e);
                            return void pending(e);
                        }

                        // resend the same command again
                        // give up if you've already tried resending
                        if (ctx.resend(txid)) { delete ctx.pending[txid]; }
                    });
                }

                pending(parsed[2]);
                delete ctx.pending[txid];
                return;
            } else {
                // update the cookie
                if (/\|/.test(cookie)) {
                    if (ctx.cookie !== cookie) {
                        ctx.cookie = cookie;
                    }
                }
            }
            pending(void 0, response);

            // if successful, delete the callback...
            delete ctx.pending[txid];
        }
        else {
            console.log("received message for txid with no callback");
        }
    };

    var create = function (network, edPrivateKey, edPublicKey, cb) {
        var signKey;

        try {
            signKey = Nacl.util.decodeBase64(edPrivateKey);
            if (signKey.length !== 64) {
                throw new Error('private key did not match expected length of 64');
            }
        } catch (err) {
            return void cb(err);
        }

        var pubBuffer;
        try {
            pubBuffer = Nacl.util.decodeBase64(edPublicKey);
            if (pubBuffer.length !== 32) {
                return void cb('expected public key to be 32 uint');
            }
        } catch (err) {
            return void cb(err);
        }

        var ctx = {
            network: network,
            timeouts: {}, // timeouts
            pending: {}, // callbacks
            cookie: null,
            connected: true,
        };

        var send = ctx.send = function (type, msg, cb) {
            if (!ctx.connected && type !== 'COOKIE') {
                return void window.setTimeout(function () {
                    cb('DISCONNECTED');
                });
            }

            // construct a signed message...

            var data = [type, msg];
            if (ctx.cookie && ctx.cookie.join) {
                data.unshift(ctx.cookie.join('|'));
            } else {
                data.unshift(ctx.cookie);
            }

            var sig = signMsg(data, signKey);

            data.unshift(edPublicKey);
            data.unshift(sig);

            // [sig, edPublicKey, cookie, type, msg]
            return sendMsg(ctx, data, cb);
        };

        ctx.resend = function (txid) {
            var pending = ctx.pending[txid];
            if (pending.called) {
                console.error("[%s] called too many times", txid);
                return true;
            }
            pending.called++;

            // update the cookie and signature...
            pending.data[2] = ctx.cookie;
            pending.data[0] = signMsg(pending.data.slice(2), signKey);
            try {
                return ctx.network.sendto(ctx.network.historyKeeper,
                    JSON.stringify([txid, pending.data]));
            } catch (e) {
                console.log("failed to resend");
                console.error(e);
            }
        };

        send.unauthenticated = function (type, msg, cb) {
            if (!ctx.connected) {
                return void window.setTimeout(function () {
                    cb('DISCONNECTED');
                });
            }

            // construct an unsigned message
            var data = [null, edPublicKey, null, type, msg];
            if (ctx.cookie && ctx.cookie.join) {
                data[2] = ctx.cookie.join('|');
            } else {
                data[2] = ctx.cookie;
            }

            return sendMsg(ctx, data, cb);
        };

        network.on('message', function (msg) {
            onMsg(ctx, msg);
        });

        network.on('disconnect', function () {
            ctx.connected = false;
        });

        network.on('reconnect', function () {
            send('COOKIE', "", function (e) {
                if (e) { return void cb(e); }
                ctx.connected = true;
            });
        });

        send('COOKIE', "", function (e) {
            if (e) { return void cb(e); }
            // callback to provide 'send' method to whatever needs it
            cb(void 0, { send: send, });
        });
    };

    return { create: create };
});
<|endoftext|>


<commit_before>var data = {};

$(document).ready(function () {

  function getSensor15(){
    var value = $.get("https://u5231p3363.web0091.zxcs.nl/Sleeptight/api/sensor/15", function(result, error){
      if(error){
        console.log(error)
      } else {
        return result;
      }
    })
    return value;
  }

  var sensor15data = getSensor15();
  console.log(sensor15data);

  var sensordata = [["2017-02-17 22:03:00", "start"], ["2017-02-17 22:23:00", "start"], ["2017-02-17 22:28:00", "start"],
                    ["2017-02-17 23:05:00", "start"],
                    ["2017-02-17 00:03:00", "start"], ["2017-02-17 00:24:00", "start"], ["2017-02-17 00:43:00", "start"],
                    ["2017-02-17 01:03:00", "start"], ["2017-02-17 01:12:00", "start"], ["2017-02-17 01:16:00", "start"],
                    ["2017-02-17 02:03:00", "start"], ["2017-02-17 02:45:00", "start"], ["2017-02-17 02:59:00", "start"],
                    ["2017-02-17 03:33:00", "start"], ["2017-02-17 03:38:00", "start"], ["2017-02-17 03:51:00", "start"],
                    ["2017-02-17 04:03:00", "start"], ["2017-02-17 04:12:00", "start"], ["2017-02-17 04:34:00", "start"]];

  // alle tijden = sensordata[x][0]
  // alle starten = sensordata[x][1]
  var lastArr = sensordata.length-1;
  var firstDate = new Date(sensordata[0][0]);

  var startH  = firstDate.getHours();
  var startM  = firstDate.getMinutes();
  var startTime   = startH * 60 + startM;

  // console.log('starttime: ' + startTime);

  // string to date conversion & insert time in minutes
  for (i = 0; i <= lastArr ; i++) {

    var date = new Date(sensordata[i][0]);
    sensordata[i][0] = date;

    var timeH      = sensordata[i][0].getHours();
    var timeM      = sensordata[i][0].getMinutes();
    var totalTime  = timeH * 60 + timeM;

    if (totalTime < startTime){
      totalTime = totalTime + 1440;
    };

    sensordata[i].push(totalTime);

    //console.log(sensordata[i][2]);
  }

  // nieuwe 15 minuten loop rekenen met datasets
  var lastTime   = sensordata[lastArr][2];
  data.hitsPerKwartier = [];
  var kwartierNR = 0;
  for(i = startTime; i < lastTime; i = i + 15){
    var time1 = i;
    var time2 = i + 15;
    var aantalHits = 0;
    kwartierNR++;
    //console.log(time1 + ' ' + time2);

    for (j = 0; j < lastArr; j++) {
      if (sensordata[j][2] >= time1 && sensordata[j][2] < time2) {
        if (sensordata[j][1] == "start") {
          aantalHits++;
        }
      }
    }

  data.hitsPerKwartier.push([time1, aantalHits]);

  //   if (aantalHits > 0) {
  //     console.log(aantalHits + ' hits');
  //   } else {
  //     console.log('0 hits');
  //   }

  }

  console.log(data.hitsPerKwartier);

    // var time = i;
    // var startInkwartier = [];
    // for (j = 0; j < sensordata.length; j++){
    //     var arrhours = sensordata[j][0].getHours();
    //     var arrminutes = sensordata[j][0].getMinutes();
    //     var arrseconds = sensordata[j][0].getSeconds();
    //     if (sensordata[j+1] !== undefined){
    //       var next = j + 1;
    //       var nextminutes = sensordata[next][0].getMinutes();
    //     }
    //
    //
    //     var sum = arrminutes + time
    //     if(sum < nextminutes){
    //       if (sensordata[j][1] == 'start'){
    //           var blub = {
    //             kwartier: time,
    //             data: sensordata[j]
    //           }
    //           startInkwartier.push(blub)
    //       }
    //     } else {
    //       console.log("blub")
    //     }
        //var n = arrtime.match(/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/ );
        //console.log(n)
    // }

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

  //   console.log(startInkwartier)
  //   alleKwartieren.push(i);
  // }

  // console.log(startTijd);
  // console.log(laatsteTijd);
  // loop startijd elke 15 min
  // for(i = starttijd; i <= laatsteTijd; i = i + .15) {
  //   c = i.toFixed(2);
  //   alleKwartieren.push(c);
  // };

  //
  // for (v = 0; v <= lastArr ; v++) {
  //   if(sensordata[v][0] < 14.00) {
  //     sensordata[v][0] = sensordata[v][0] + 24.00;
  //     // console.log(sensordata[v][0]);
  //   };
  // };
  //
  // var starttijd = sensordata[0][0];
  // var laatsteTijd = sensordata[lastArr][0];
  //
  // // laat alles uit de array zien
  // // for(var i=0; i < sensordata.length; i++){
  // //   console.log(sensordata[i]);
  // // }
  //
  // var alleKwartieren = [];
  //
  // // loop startijd elke 15 min
  // for(var i = starttijd; i <= laatsteTijd; i = i + .15) {
  //   c = i.toFixed(2);
  //   alleKwartieren.push(c);
  // };
  //
  // console.log(alleKwartieren);
  //

  // var new = parseInt(25.98)
  //
  // if (25.98 > new +.60){
  //
  // }

    // var sensordata = '';
    // var y = 22.00;
    // for(var x = 0; x < 20; x++) {
    //   var z = [y, "start"];
    //   sensordata = [z];
    //   y += 0.07;
    //   y.toFixed(2);
    //   console.log("sensor" + sensordata);
    // }

});
<commit_msg> een console log weg<commit_after>var data = {};

$(document).ready(function () {

  function getSensor15(){
    var value = $.get("https://u5231p3363.web0091.zxcs.nl/Sleeptight/api/sensor/15", function(result, error){
      if(error){
        console.log(error)
      } else {
        return result;
      }
    })
    return value;
  }

  var sensor15data = getSensor15();
  console.log(sensor15data);

  var sensordata = [["2017-02-17 22:03:00", "start"], ["2017-02-17 22:23:00", "start"], ["2017-02-17 22:28:00", "start"],
                    ["2017-02-17 23:05:00", "start"],
                    ["2017-02-17 00:03:00", "start"], ["2017-02-17 00:24:00", "start"], ["2017-02-17 00:43:00", "start"],
                    ["2017-02-17 01:03:00", "start"], ["2017-02-17 01:12:00", "start"], ["2017-02-17 01:16:00", "start"],
                    ["2017-02-17 02:03:00", "start"], ["2017-02-17 02:45:00", "start"], ["2017-02-17 02:59:00", "start"],
                    ["2017-02-17 03:33:00", "start"], ["2017-02-17 03:38:00", "start"], ["2017-02-17 03:51:00", "start"],
                    ["2017-02-17 04:03:00", "start"], ["2017-02-17 04:12:00", "start"], ["2017-02-17 04:34:00", "start"]];

  // alle tijden = sensordata[x][0]
  // alle starten = sensordata[x][1]
  var lastArr = sensordata.length-1;
  var firstDate = new Date(sensordata[0][0]);

  var startH  = firstDate.getHours();
  var startM  = firstDate.getMinutes();
  var startTime   = startH * 60 + startM;

  // console.log('starttime: ' + startTime);

  // string to date conversion & insert time in minutes
  for (i = 0; i <= lastArr ; i++) {

    var date = new Date(sensordata[i][0]);
    sensordata[i][0] = date;

    var timeH      = sensordata[i][0].getHours();
    var timeM      = sensordata[i][0].getMinutes();
    var totalTime  = timeH * 60 + timeM;

    if (totalTime < startTime){
      totalTime = totalTime + 1440;
    };

    sensordata[i].push(totalTime);

    //console.log(sensordata[i][2]);
  }

  // nieuwe 15 minuten loop rekenen met datasets
  var lastTime   = sensordata[lastArr][2];
  data.hitsPerKwartier = [];
  var kwartierNR = 0;
  for(i = startTime; i < lastTime; i = i + 15){
    var time1 = i;
    var time2 = i + 15;
    var aantalHits = 0;
    kwartierNR++;
    //console.log(time1 + ' ' + time2);

    for (j = 0; j < lastArr; j++) {
      if (sensordata[j][2] >= time1 && sensordata[j][2] < time2) {
        if (sensordata[j][1] == "start") {
          aantalHits++;
        }
      }
    }

  data.hitsPerKwartier.push([time1, aantalHits]);

  //   if (aantalHits > 0) {
  //     console.log(aantalHits + ' hits');
  //   } else {
  //     console.log('0 hits');
  //   }

  }

  // console.log(data.hitsPerKwartier);

    // var time = i;
    // var startInkwartier = [];
    // for (j = 0; j < sensordata.length; j++){
    //     var arrhours = sensordata[j][0].getHours();
    //     var arrminutes = sensordata[j][0].getMinutes();
    //     var arrseconds = sensordata[j][0].getSeconds();
    //     if (sensordata[j+1] !== undefined){
    //       var next = j + 1;
    //       var nextminutes = sensordata[next][0].getMinutes();
    //     }
    //
    //
    //     var sum = arrminutes + time
    //     if(sum < nextminutes){
    //       if (sensordata[j][1] == 'start'){
    //           var blub = {
    //             kwartier: time,
    //             data: sensordata[j]
    //           }
    //           startInkwartier.push(blub)
    //       }
    //     } else {
    //       console.log("blub")
    //     }
        //var n = arrtime.match(/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/ );
        //console.log(n)
    // }

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

  //   console.log(startInkwartier)
  //   alleKwartieren.push(i);
  // }

  // console.log(startTijd);
  // console.log(laatsteTijd);
  // loop startijd elke 15 min
  // for(i = starttijd; i <= laatsteTijd; i = i + .15) {
  //   c = i.toFixed(2);
  //   alleKwartieren.push(c);
  // };

  //
  // for (v = 0; v <= lastArr ; v++) {
  //   if(sensordata[v][0] < 14.00) {
  //     sensordata[v][0] = sensordata[v][0] + 24.00;
  //     // console.log(sensordata[v][0]);
  //   };
  // };
  //
  // var starttijd = sensordata[0][0];
  // var laatsteTijd = sensordata[lastArr][0];
  //
  // // laat alles uit de array zien
  // // for(var i=0; i < sensordata.length; i++){
  // //   console.log(sensordata[i]);
  // // }
  //
  // var alleKwartieren = [];
  //
  // // loop startijd elke 15 min
  // for(var i = starttijd; i <= laatsteTijd; i = i + .15) {
  //   c = i.toFixed(2);
  //   alleKwartieren.push(c);
  // };
  //
  // console.log(alleKwartieren);
  //

  // var new = parseInt(25.98)
  //
  // if (25.98 > new +.60){
  //
  // }

    // var sensordata = '';
    // var y = 22.00;
    // for(var x = 0; x < 20; x++) {
    //   var z = [y, "start"];
    //   sensordata = [z];
    //   y += 0.07;
    //   y.toFixed(2);
    //   console.log("sensor" + sensordata);
    // }

});
<|endoftext|>


<commit_before>
var config = require('../config.json');
var redisStore = require('../../index');

var redisCache;

beforeAll(function() {
  redisCache = require('cache-manager').caching({
    store: redisStore,
    host: config.redis.host,
    port: config.redis.port,
    db: config.redis.db,
    ttl: config.redis.ttl
  });
});

describe('set', function() {
  it('should store a value without ttl', function(done){
    redisCache.set('foo', 'bar', function(err) {
      expect(err).toBe(null);
      done();
    });
  });

  it('should store a value with a specific ttl', function(done){
    redisCache.set('foo', 'bar', config.redis.ttl, function(err) {
      expect(err).toBe(null);
      done();
    });
  });

  it('should store a value with a infinite ttl', function(done){
    redisCache.set('foo', 'bar', 0);
    done();
  });

  it('should store a value without callback', function(done){
    redisCache.set('foo', 'bar');
    done();
  });

  it('should not store an invalid value', function(done){
    redisCache.set('foo1', null);
    redisCache.set('foo2', undefined);
    done();
  });
});

describe('get', function() {
  it('should retrieve a value for a given key', function(done){
    var value = 'bar';
    redisCache.set('foo', value, function() {
      redisCache.get('foo', function(err, result) {
        expect(err).toBe(null);
        expect(result).toBe(value);
        done();
      });
    });
  });

  it('should return null when the key is invalid', function(done){
    redisCache.get('invalidKey', function(err, result) {
      expect(err).toBe(null);
      expect(result).toBe(null);
      done();
    });
  });
});

describe('del', function() {
  it('should delete a value for a given key', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.del('foo', function(err) {
        expect(err).toBe(null);
        done();
      });
    });
  });

  it('should delete a value for a given key without callback', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.del('foo');
      done();
    });
  });
});

describe('reset', function() {
  it('should flush underlying db', function(done){
    redisCache.reset(function(err) {
      expect(err).toBe(null);
      done();
    });
  });

  it('should flush underlying db without callback', function(done){
    redisCache.reset();
    done();
  });
});

describe('ttl', function() {
  it('should retrieve ttl for a given key', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.ttl('foo', function(err, ttl) {
        expect(err).toBe(null);
        expect(ttl).toBe(config.redis.ttl);
        done();
      });
    });
  });

  it('should retrieve ttl for an invalid key', function(done){
    redisCache.ttl('invalidKey', function(err, ttl){
      expect(err).toBe(null);
      expect(ttl).not.toBe(null);
      done();
    });
  });
});

describe('keys', function() {
  it('should return an array of keys for the given pattern', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.keys('f*', function(err, arrayOfKeys) {
        expect(err).toBe(null);
        expect(arrayOfKeys).not.toBe(null);
        expect(arrayOfKeys.indexOf('foo')).not.toBe(-1);
        done();
      });
    });
  });

  it('should return an array of keys without pattern', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.keys(function(err, arrayOfKeys) {
        expect(err).toBe(null);
        expect(arrayOfKeys).not.toBe(null);
        expect(arrayOfKeys.indexOf('foo')).not.toBe(-1);
        done();
      });
    });
  });
});

describe('isCacheableValue', function() {
  it('should return true when the value is not null or undefined', function(done){
    expect(redisCache.store.isCacheableValue(0)).toBe(true);
    expect(redisCache.store.isCacheableValue(100)).toBe(true);
    expect(redisCache.store.isCacheableValue('')).toBe(true);
    expect(redisCache.store.isCacheableValue('test')).toBe(true);
    done();
  });

  it('should return false when the value is null or undefined', function(done){
    expect(redisCache.store.isCacheableValue(null)).toBe(false);
    expect(redisCache.store.isCacheableValue(undefined)).toBe(false);
    done();
  });
});

describe('getClient', function() {
  it('should return redis client', function(done) {
    redisCache.store.getClient(function(err, redis) {
      expect(err).toBe(null);
      expect(redis).not.toBe(null);
      expect(redis.client).not.toBe(null);
      redis.done(done);
    });
  });
});
<commit_msg>Add tests : redisErrorEventEmitter<commit_after>
var config = require('../config.json');
var redisStore = require('../../index');

var redisCache;

beforeAll(function() {
  redisCache = require('cache-manager').caching({
    store: redisStore,
    host: config.redis.host,
    port: config.redis.port,
    db: config.redis.db,
    ttl: config.redis.ttl
  });
});

describe('set', function() {
  it('should store a value without ttl', function(done){
    redisCache.set('foo', 'bar', function(err) {
      expect(err).toBe(null);
      done();
    });
  });

  it('should store a value with a specific ttl', function(done){
    redisCache.set('foo', 'bar', config.redis.ttl, function(err) {
      expect(err).toBe(null);
      done();
    });
  });

  it('should store a value with a infinite ttl', function(done){
    redisCache.set('foo', 'bar', 0);
    done();
  });

  it('should store a value without callback', function(done){
    redisCache.set('foo', 'bar');
    done();
  });

  it('should not store an invalid value', function(done){
    redisCache.set('foo1', null);
    redisCache.set('foo2', undefined);
    done();
  });
});

describe('get', function() {
  it('should retrieve a value for a given key', function(done){
    var value = 'bar';
    redisCache.set('foo', value, function() {
      redisCache.get('foo', function(err, result) {
        expect(err).toBe(null);
        expect(result).toBe(value);
        done();
      });
    });
  });

  it('should return null when the key is invalid', function(done){
    redisCache.get('invalidKey', function(err, result) {
      expect(err).toBe(null);
      expect(result).toBe(null);
      done();
    });
  });
});

describe('del', function() {
  it('should delete a value for a given key', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.del('foo', function(err) {
        expect(err).toBe(null);
        done();
      });
    });
  });

  it('should delete a value for a given key without callback', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.del('foo');
      done();
    });
  });
});

describe('reset', function() {
  it('should flush underlying db', function(done){
    redisCache.reset(function(err) {
      expect(err).toBe(null);
      done();
    });
  });

  it('should flush underlying db without callback', function(done){
    redisCache.reset();
    done();
  });
});

describe('ttl', function() {
  it('should retrieve ttl for a given key', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.ttl('foo', function(err, ttl) {
        expect(err).toBe(null);
        expect(ttl).toBe(config.redis.ttl);
        done();
      });
    });
  });

  it('should retrieve ttl for an invalid key', function(done){
    redisCache.ttl('invalidKey', function(err, ttl){
      expect(err).toBe(null);
      expect(ttl).not.toBe(null);
      done();
    });
  });
});

describe('keys', function() {
  it('should return an array of keys for the given pattern', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.keys('f*', function(err, arrayOfKeys) {
        expect(err).toBe(null);
        expect(arrayOfKeys).not.toBe(null);
        expect(arrayOfKeys.indexOf('foo')).not.toBe(-1);
        done();
      });
    });
  });

  it('should return an array of keys without pattern', function(done){
    redisCache.set('foo', 'bar', function() {
      redisCache.keys(function(err, arrayOfKeys) {
        expect(err).toBe(null);
        expect(arrayOfKeys).not.toBe(null);
        expect(arrayOfKeys.indexOf('foo')).not.toBe(-1);
        done();
      });
    });
  });
});

describe('isCacheableValue', function() {
  it('should return true when the value is not null or undefined', function(done){
    expect(redisCache.store.isCacheableValue(0)).toBe(true);
    expect(redisCache.store.isCacheableValue(100)).toBe(true);
    expect(redisCache.store.isCacheableValue('')).toBe(true);
    expect(redisCache.store.isCacheableValue('test')).toBe(true);
    done();
  });

  it('should return false when the value is null or undefined', function(done){
    expect(redisCache.store.isCacheableValue(null)).toBe(false);
    expect(redisCache.store.isCacheableValue(undefined)).toBe(false);
    done();
  });
});

describe('getClient', function() {
  it('should return redis client', function(done) {
    redisCache.store.getClient(function(err, redis) {
      expect(err).toBe(null);
      expect(redis).not.toBe(null);
      expect(redis.client).not.toBe(null);
      redis.done(done);
    });
  });
});

describe('redisErrorEventEmitter', function(){
  it('should return an error when the redis server is unavailable', function(done){
    // Change redisCache host to receive an error
    redisCache = require('cache-manager').caching({
      store: redisStore,
      host: '127.0.0.10',
      port: config.redis.port,
      db: config.redis.db,
      connect_timeout: 1
    });

    redisCache.set('foo', 'bar', function(err) {
      expect(err).not.toBe(null);
      done();
    });
  });
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         yunpan.ru forum
// @namespace    https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/
// @version      1.0
// @description  Some usefal function for forum
// @author       alezhu
// @match        http://yunpan.ru/
// @include      http://yunpan.ru/
// @source      https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/yunpan.ru.user.js
// @updateURL   https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/yunpan.ru.user.js
// @downloadURL https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/yunpan.ru.user.js
// @grant        none
// ==/UserScript==

(function() {

})();
<commit_msg>test select works<commit_after>// ==UserScript==
// @name         yunpan.ru forum
// @namespace    https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/
// @version      1.0
// @description  Some usefal function for forum
// @author       alezhu
// @match        http://yunpan.ru/
// @include      http://yunpan.ru/
// @source      https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/yunpan.ru.user.js
// @updateURL   https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/yunpan.ru.user.js
// @downloadURL https://raw.githubusercontent.com/alezhu/yunpan_ru_forum_user_js/yunpan.ru.user.js
// @grant        none
// ==/UserScript==

(function() {
	var LOG = 1;
	var authors = {};
	$(document).ready(function(){
		$("ul.topics li.row").each(function() {
			var li = $(this);
			var a = li.find("a[href^=http://yunpan.ru/member]");
			if(a.length) {
				var name = a.text();
				var topics = authors[name];
				if(!topics) topics = [];
				topics.push(li);
			}
		});
	})
})();
<|endoftext|>


<commit_before>/*!
 *  * jQuery OAuth via popup window plugin
 *  *
 *  * @author  Nobu Funaki @zuzara
 *  *
 *  * Dual licensed under the MIT and GPL licenses:
 *  *   http://www.opensource.org/licenses/mit-license.php
 *  *   http://www.gnu.org/licenses/gpl.html
 *  *
 *  * @modified_by Geoffrey Bilder (center window)
 *  *
 *  */
var currentOAuthModel = null;
var currentOAuthCallback = null;

function oauthIframeCallback() {
  currentOAuthModel.modal('hide');
}

(function($){
    //  inspired by DISQUS
    $.oauthpopup = function(options)
    {
        if (!options || !options.path) {
            throw new Error("options.path must not be empty");
        }
      var width = 700;
      var height = 600;
      var left = (screen.width  - width)/2;
      var top = (screen.height - height)/2;
        options = $.extend({
            windowName: 'ConnectWithOAuth' // should not include space for IE
          , windowOptions: 'location=0,status=0,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top
          , callback: function(){ window.location.reload(); }
        }, options);

        var oauthWindow   = window.open(options.path, options.windowName, options.windowOptions);
        var oauthInterval = window.setInterval(function(){
            if (oauthWindow.closed) {
                window.clearInterval(oauthInterval);
                options.callback();
            }
        }, 1000);
    };

  $.oauthmodel = function(options) {
    var $model = $('<div>').addClass('model').addClass('hide').addClass('fade').appendTo($('body'));
    var $iframe = $('<iframe>').attr('src', options['path']).appendTo($model);

    $model.model('show');

    currentOAuthModel = $model;
    currentOAuthCallback = options['callback'];
  };
})(jQuery);<commit_msg>Added `scrollbars=yes` as window options for popup modal, to fix non- scrollable issue on new adaptive orcid.org website.<commit_after>/*!
 *  * jQuery OAuth via popup window plugin
 *  *
 *  * @author  Nobu Funaki @zuzara
 *  *
 *  * Dual licensed under the MIT and GPL licenses:
 *  *   http://www.opensource.org/licenses/mit-license.php
 *  *   http://www.gnu.org/licenses/gpl.html
 *  *
 *  * @modified_by Geoffrey Bilder (center window)
 *  *
 *  */
var currentOAuthModel = null;
var currentOAuthCallback = null;

function oauthIframeCallback() {
  currentOAuthModel.modal('hide');
}

(function($){
    //  inspired by DISQUS
    $.oauthpopup = function(options)
    {
        if (!options || !options.path) {
            throw new Error("options.path must not be empty");
        }
      var width = 700;
      var height = 600;
      var left = (screen.width  - width)/2;
      var top = (screen.height - height)/2;
        options = $.extend({
            windowName: 'ConnectWithOAuth' // should not include space for IE
          , windowOptions: 'location=0,status=0,scrollbars=yes,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top
          , callback: function(){ window.location.reload(); }
        }, options);

        var oauthWindow   = window.open(options.path, options.windowName, options.windowOptions);
        var oauthInterval = window.setInterval(function(){
            if (oauthWindow.closed) {
                window.clearInterval(oauthInterval);
                options.callback();
            }
        }, 1000);
    };

  $.oauthmodel = function(options) {
    var $model = $('<div>').addClass('model').addClass('hide').addClass('fade').appendTo($('body'));
    var $iframe = $('<iframe>').attr('src', options['path']).appendTo($model);

    $model.model('show');

    currentOAuthModel = $model;
    currentOAuthCallback = options['callback'];
  };
})(jQuery);<|endoftext|>


<commit_before>$(function () {
    $('.selectpicker').selectpicker({
        'selectedText': 'cat'
    });

    renderVoicebanks(json);
    history.pushState("","","/voicebanks");
});

var renderVoicebanks = function(values){
	var pagesCount = Math.ceil(values.voicebanksCount / $pageSize.val());
	var pagesCountArray = new Array();
	for(var i=0; i<pagesCount; i++){
		pagesCountArray[i] = {page:i};
		if(values.pageNow == i){
			pagesCountArray[i].active = true;
		}
	}
	values.pagesCount = pagesCountArray;
	if(values.pageNow-1>=0){
		values.prev = { exist: true, page: values.pageNow-1 };
	}
	if(values.pageNow+1<pagesCount){
		values.next ={ exist: true, page: values.pageNow+1 };
	}

	template = Handlebars.compile($('#all-voicebanks-tmpl').html());
    $('#voicebanks').html(template(values));
}

var showVoicebanks = function(pageNum){
	$.ajax({
	    url: "/json/getAllVoicebanks",
	    data: {
	    	page: pageNum,
	    	pageSize: $pageSize.val(),
	    	sortCode: $sortOrder.find(':selected').data('sort'),
	    	orderCode: $sortOrder.find(':selected').data('order')
	    	},
	    beforeSend: function(){
			            $('#voicebanks').html($("img").attr("src","../images/ajax-loader.gif"));
		            }
	}).done(function(data){
		var values = data;
		renderVoicebanks(values);

	    if(page != values.pageNow){
		    history.pushState("","","/voicebanks?page="+values.pageNow);
			page = values.pageNow; // Global
	    }
	}).fail(function(e){
	    console.log('error!!!');
	    console.log(e);
	}).always(function(){
	    $('.page-button').on('click', function(){
	    	showVoicebanks($(this).data('page'));
	    });

	    $pageSize.on('change', function(){
	    	showVoicebanks(0);
	    });

	    $sortOrder.on('change', function(){
	    	showVoicebanks(0);
	    })
	});
}<commit_msg>fix prev commit<commit_after>$(function () {
    $('.selectpicker').selectpicker({
        'selectedText': 'cat'
    });

    renderVoicebanks(json);
});

var renderVoicebanks = function(values){
	var pagesCount = Math.ceil(values.voicebanksCount / $pageSize.val());
	var pagesCountArray = new Array();
	for(var i=0; i<pagesCount; i++){
		pagesCountArray[i] = {page:i};
		if(values.pageNow == i){
			pagesCountArray[i].active = true;
		}
	}
	values.pagesCount = pagesCountArray;
	if(values.pageNow-1>=0){
		values.prev = { exist: true, page: values.pageNow-1 };
	}
	if(values.pageNow+1<pagesCount){
		values.next ={ exist: true, page: values.pageNow+1 };
	}

	template = Handlebars.compile($('#all-voicebanks-tmpl').html());
    $('#voicebanks').html(template(values));
}

var showVoicebanks = function(pageNum){
	$.ajax({
	    url: "/json/getAllVoicebanks",
	    data: {
	    	page: pageNum,
	    	pageSize: $pageSize.val(),
	    	sortCode: $sortOrder.find(':selected').data('sort'),
	    	orderCode: $sortOrder.find(':selected').data('order')
	    	},
	    beforeSend: function(){
			            $('#voicebanks').html($("img").attr("src","../images/ajax-loader.gif"));
		            }
	}).done(function(data){
		var values = data;
		renderVoicebanks(values);

	    if(page != values.pageNow){
		    history.pushState("","","/voicebanks?page="+values.pageNow);
			page = values.pageNow; // Global
	    }
	}).fail(function(e){
	    console.log('error!!!');
	    console.log(e);
	}).always(function(){
	    $('.page-button').on('click', function(){
	    	showVoicebanks($(this).data('page'));
	    });

	    $pageSize.on('change', function(){
	    	showVoicebanks(0);
	    });

	    $sortOrder.on('change', function(){
	    	showVoicebanks(0);
	    })
	});
}<|endoftext|>


<commit_before>'use strict';

angular.module('eMarketApp').directive('myEmarketDrafts', function(User) {
  return {
    templateUrl: 'views/myEmarketDrafts.html',
    restrict: 'E',
    scope: true,
    replace: true,
    controller: function($scope, SellItem) {
      $scope.setDraft = SellItem.setDraft;
      SellItem.isDraft = true;
    },
    link: function(scope, elem) {
      var page = $(elem[0]);
      var draftList = page.find('#draftList');

      page.on('pagebeforeshow', function() {
        User.me().getList('drafts').then(function(drafts) {
          scope.drafts = drafts;
          setTimeout(function() {
            draftList.listview('refresh');
          });
        });
      });
    }
  };
});
<commit_msg>Fixed bug with sellItem and drafts<commit_after>'use strict';

angular.module('eMarketApp').directive('myEmarketDrafts', function(User, SellItem) {
  return {
    templateUrl: 'views/myEmarketDrafts.html',
    restrict: 'E',
    scope: true,
    replace: true,
    controller: function($scope) {
      $scope.setDraft = SellItem.setDraft;
    },
    link: function(scope, elem) {
      var page = $(elem[0]);
      var draftList = page.find('#draftList');

      page.on('pagebeforeshow', function() {
        User.me().getList('drafts').then(function(drafts) {
          scope.drafts = drafts;
          setTimeout(function() {
            draftList.listview('refresh');
          });
        });
        SellItem.isDraft = true;
      });
    }
  };
});
<|endoftext|>


<commit_before>'use strict';

if (!MODULE) { var MODULE = {}; }

MODULE.LevelScreen = (function() {
    var LevelScreen = function() {
        var self = this;

        this.screen = document.getElementById('screen-level');

        this.level_el = this.screen.getElementsByClassName('level-container')[0];
        this.grid_el = this.screen.getElementsByClassName('grid-container')[0];

        this.footer = this.screen.getElementsByTagName('footer')[0];
        this.header = this.screen.getElementsByTagName('header')[0];

        this.playcontrols = this.footer.getElementsByClassName('play-controls')[0];
        this.stopcontrols = this.footer.getElementsByClassName('stop-controls')[0];

        this.generation = this.header.getElementsByClassName('generation')[0];
        this.played = this.header.getElementsByClassName('played')[0];

        this.title = this.header.getElementsByClassName('title')[0];

        this.autowin = this.header.getElementsByClassName('autowin')[0];
        this.autowin_goal = this.autowin.getElementsByClassName('autowin-gen')[0];

        this.maxplay = this.header.getElementsByClassName('maxplay')[0];
        this.maxplayval = this.maxplay.getElementsByClassName('maxplay-val')[0];

        this.segment_generation = this.header.getElementsByClassName('segment-gen')[0];
        this.segment_played = this.header.getElementsByClassName('segment-played')[0];
        this.segment_red = this.header.getElementsByClassName('segment-red')[0];
        this.segment_green = this.header.getElementsByClassName('segment-green')[0];

        this.maxred_current = this.segment_red.getElementsByClassName('current')[0];
        this.maxred_limit = this.segment_red.getElementsByClassName('limit')[0];

        this.mingreen_current = this.segment_green.getElementsByClassName('current')[0];
        this.mingreen_limit = this.segment_green.getElementsByClassName('limit')[0];

        this.buttons = {
            play: this.footer.getElementsByClassName('play')[0],
            stop: this.footer.getElementsByClassName('stop')[0],
            clear: this.footer.getElementsByClassName('clear')[0],
            help: this.footer.getElementsByClassName('help')[0],
            library: this.footer.getElementsByClassName('library')[0],
            exit: this.footer.getElementsByClassName('exit')[0]
        };

        this.level = null;
        this.grid = null;
        this.level_id = null;
        this.library = null;

        this.buttons.play.onclick = this.onPlay.bind(this);
        this.buttons.stop.onclick = this.onStop.bind(this);
        this.buttons.clear.onclick = this.onClear.bind(this);
        this.buttons.help.onclick = this.onHelp.bind(this);
        this.buttons.library.onclick = this.onLibrary.bind(this);
        this.buttons.exit.onclick = this.onExit.bind(this);
    };

    LevelScreen.HEADER_HEIGHT = 50;
    LevelScreen.FOOTER_HEIGHT = 50;

    LevelScreen.prototype.display = function(level_id) {
        var self = this;

        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');
        this.header.className = '';
        this.footer.className = '';

        this.level_id = level_id;

        var campaign = app.content.data.campaign[level_id];
        this.title.innerHTML = campaign.name;

        var constraints = {
            width: app.device.viewport.width,
            height: app.device.viewport.height - (LevelScreen.HEADER_HEIGHT + LevelScreen.FOOTER_HEIGHT)
        };

        console.log('constraints', constraints);

        this.level = new MODULE.Level(campaign, this.level_el, constraints);

        this.grid = new MODULE.Grid(
            this.level.dimensions.width,
            this.level.dimensions.height,
            this.level.size,
            this.grid_el
        );

        this.level
        .on('generation', function(generation) {
            self.generation.textContent = generation;
        })
        .on('play-count', function(played) {
            self.played.textContent = played;
        })
        .on('status', function(status) {
            if (status === MODULE.Level.STATUS.DONE) {
                self.win();
            } else if (status === MODULE.Level.STATUS.LOSE) {
                self.lose();
            }
        })
        .on('win', function(data) {
            var my_level = app.storage.get('level', 0);
            var max_level = Object.keys(app.content.data.campaign).length;
            var levelup = false;

            if (data.level === max_level) {
                // TODO: Congratulate user on winning
                console.log("Beat the final level... Now what?");
            }

            if (data.level === my_level + 1) {
                levelup = true;
                app.storage.set('level', data.level);
                self.displayAdIfNeeded(data.level);
            }

            var rank = app.rank.get(data.level, data.generation, data.played);

            var rank_up = app.rank.report(data.level, rank.id);

            console.log('Rank up?', rank_up, rank);

            var content = LevelScreen.resultModal(rank, campaign.win, data.generation, data.played);

            if (levelup || rank_up) {
                app.modal.show(
                    content, [{
                        text: "Watch"
                    },{
                        text: "Next Level",
                        callback: function() {
                            app.screen.display('level', self.level_id + 1);
                        }
                    }], true
                );
            }

            app.analytics.track('LEVEL-WIN', {
                level: data.level,
                generation: data.generation,
                played: data.played,
                levelup: levelup
            });
        })
        .on('lose', function(data) {
            var rank = app.rank.getFailure();

            var content = LevelScreen.resultModal(rank, campaign.lose, data.generation, data.played);

            app.modal.show(
                content, [{
                    text: "Watch"
                },{
                    text: "Try Again",
                    callback: function() {
                        self.onStop();
                    }
                }], true
            );
        })
        .on('green-count', function(count) {
            self.mingreen_current.textContent = count;
        })
        .on('red-count', function(count) {
            self.maxred_current.textContent = count;
        });

        this.level.initialize();

        if (level_id > app.storage.get('level')) {
            this.incomplete();
            this.intro();
        } else {
            this.complete();
        }

        this.setGenerationGoal(this.level.autowin);
        this.setMaxPlay(this.level.maxplay);
        this.togglePlayedSegment(!!this.level.playables.length);
        this.toggleRedSegment(this.level.maxred);
        this.toggleGreenSegment(this.level.mingreen);

        var gamefield = this.level.gamefield;
        var finger = new Hammer(gamefield);
        finger.get('pinch').set({enable: true});

        /*
        finger.add(new Hammer.Pan({
            direction: Hammer.DIRECTION_ALL,
            threshold: 0
        }));
        */

        finger.on('pinchstart', function() {
            self.level.scaleStart();
        });

        finger.on('pinch', function(event) {
            self.level.scale(event.scale);
            self.grid.scale(self.level.size);
        });

        finger.on('pinchend', function() {
            self.level.scaleEnd();
        });

        // finger.on('pan', function(event) {});

        gamefield.onclick = function(event) {
            self.level.onTap(event);
        };

        // But hammer, I don't want you to stop my panning!
        gamefield.setAttribute('style', '');

        app.audio.playMusic('chapter-' + this.level.chapter);

        this.screen.style.display = 'block';

        this.library = null;

        app.analytics.track('SCREEN-LEVEL', {
            level: level_id
        });
    };

    LevelScreen.prototype.hide = function() {
        this.level.onStop();
        this.level = null;
        this.setGenerationGoal(0);
        this.setMaxPlay(0);
        this.screen.style.display = 'none';
    };

    LevelScreen.prototype.displayAdIfNeeded = function(level) {
        var min = app.content.data.dictionary.ad_min_level;
        var mod = app.content.data.dictionary.ad_mod_level;

        if (level >= min && level % mod === 0) {
            app.interstitial.show();
        }
    };

    LevelScreen.resultModal = function(rank, flavor, gen, played) {
        var html = "
\n";
            html += "

\n";
            html += "
\n";
                html += "
" + rank.name + "
\n";
                html += "
Gen: " + gen + " Played: " + played + "
\n";
            html += "
\n";
        html += "
\n";
        html += "
\n" + flavor + "
\n";

        return html;
    };

    LevelScreen.prototype.setGenerationGoal = function(generation) {
        this.autowin_goal.textContent = generation;

        this.autowin.classList.toggle('hide', !generation);
    };

    LevelScreen.prototype.setMaxPlay = function(maxplay) {
        this.maxplayval.textContent = maxplay;

        this.maxplay.classList.toggle('hide', !maxplay);
    };

    LevelScreen.prototype.togglePlayedSegment = function(count) {
        this.segment_played.classList.toggle('hide', !count);
        this.buttons.clear.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleRedSegment = function(count) {
        this.maxred_limit.textContent = count;
        this.segment_red.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleGreenSegment = function(count) {
        this.mingreen_limit.textContent = count;
        this.segment_green.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.complete = function() {
        this.header.classList.add('done');
        this.footer.classList.add('done');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.win = function() {
        this.header.classList.add('win');
        this.footer.classList.add('win');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.lose = function() {
        this.header.classList.add('lose');
        this.footer.classList.add('lose');
    };

    LevelScreen.prototype.incomplete = function() {
        this.header.classList.remove('done');
        this.footer.classList.remove('done');
        this.buttons.exit.classList.remove('cycle');
    };

    LevelScreen.prototype.intro = function() {
        app.modal.show("
" + this.level.name + "
" + this.level.description, [{
            text: "Ok"
        }]);
    };

    LevelScreen.prototype.getLibrary = function() {
        if (this.library) {
            return this.library;
        }

        var self = this;

        var library = '
';

        Object.keys(app.content.data.library).forEach(function(lib) {
            var item = app.content.data.library[lib];

            if (item.id > self.level.library) {
                return;
            }

            library +=
                '
' +
                    '' + item.name + '
' +
                    '' +
                '
';
        });

        library += '
';

        this.library = library;

        return this.library;
    };

    LevelScreen.prototype.onPlay = function() {
        app.audio.playSound('play');
        this.playcontrols.classList.remove('hide');
        this.stopcontrols.classList.add('hide');

        this.header.classList.add('playing');
        this.footer.classList.add('playing');

        app.analytics.track('LEVEL-START', {
            level: this.level_id
        });

        this.level.onPlay();
    };

    LevelScreen.prototype.onStop = function() {
        app.audio.playSound('stop');
        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');

        this.header.classList.remove('playing');
        this.footer.classList.remove('playing');
        //this.header.classList.add('win');
        //this.footer.classList.add('win');

        app.analytics.track('LEVEL-STOP', {
            level: this.level_id,
            generation: this.level.generation
        });

        this.unLose();
        this.level.onStop();
    };

    LevelScreen.prototype.unLose = function() {
        this.header.classList.remove('lose');
        this.footer.classList.remove('lose');
    };

    LevelScreen.prototype.onClear = function() {
        app.audio.playSound('clear');

        app.analytics.track('LEVEL-CLEAR', {
            level: this.level_id
        });

        this.level.onClear();
    };

    LevelScreen.prototype.onHelp = function() {
        this.intro();

        app.analytics.track('LEVEL-HELP', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onLibrary = function() {
        app.modal.show(this.getLibrary(), [{
            text: 'Ok'
        }]);

        app.analytics.track('LEVEL-LIBRARY', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onExit = function() {
        app.audio.playSound('back');
        app.screen.display('campaign');
    };

    return LevelScreen;
}());
<commit_msg>broken ios<commit_after>'use strict';

if (!MODULE) { var MODULE = {}; }

MODULE.LevelScreen = (function() {
    var LevelScreen = function() {
        var self = this;

        this.screen = document.getElementById('screen-level');

        this.level_el = this.screen.getElementsByClassName('level-container')[0];
        this.grid_el = this.screen.getElementsByClassName('grid-container')[0];

        this.footer = this.screen.getElementsByTagName('footer')[0];
        this.header = this.screen.getElementsByTagName('header')[0];

        this.playcontrols = this.footer.getElementsByClassName('play-controls')[0];
        this.stopcontrols = this.footer.getElementsByClassName('stop-controls')[0];

        this.generation = this.header.getElementsByClassName('generation')[0];
        this.played = this.header.getElementsByClassName('played')[0];

        this.title = this.header.getElementsByClassName('title')[0];

        this.autowin = this.header.getElementsByClassName('autowin')[0];
        this.autowin_goal = this.autowin.getElementsByClassName('autowin-gen')[0];

        this.maxplay = this.header.getElementsByClassName('maxplay')[0];
        this.maxplayval = this.maxplay.getElementsByClassName('maxplay-val')[0];

        this.segment_generation = this.header.getElementsByClassName('segment-gen')[0];
        this.segment_played = this.header.getElementsByClassName('segment-played')[0];
        this.segment_red = this.header.getElementsByClassName('segment-red')[0];
        this.segment_green = this.header.getElementsByClassName('segment-green')[0];

        this.maxred_current = this.segment_red.getElementsByClassName('current')[0];
        this.maxred_limit = this.segment_red.getElementsByClassName('limit')[0];

        this.mingreen_current = this.segment_green.getElementsByClassName('current')[0];
        this.mingreen_limit = this.segment_green.getElementsByClassName('limit')[0];

        this.buttons = {
            play: this.footer.getElementsByClassName('play')[0],
            stop: this.footer.getElementsByClassName('stop')[0],
            clear: this.footer.getElementsByClassName('clear')[0],
            help: this.footer.getElementsByClassName('help')[0],
            library: this.footer.getElementsByClassName('library')[0],
            exit: this.footer.getElementsByClassName('exit')[0]
        };

        this.level = null;
        this.grid = null;
        this.level_id = null;
        this.library = null;

        this.buttons.play.onclick = this.onPlay.bind(this);
        this.buttons.stop.onclick = this.onStop.bind(this);
        this.buttons.clear.onclick = this.onClear.bind(this);
        this.buttons.help.onclick = this.onHelp.bind(this);
        this.buttons.library.onclick = this.onLibrary.bind(this);
        this.buttons.exit.onclick = this.onExit.bind(this);
    };

    LevelScreen.HEADER_HEIGHT = 50;
    LevelScreen.FOOTER_HEIGHT = 50;

    LevelScreen.prototype.display = function(level_id) {
        var self = this;

        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');
        this.header.className = '';
        this.footer.className = '';

        this.level_id = level_id;

        var campaign = app.content.data.campaign[level_id];
        this.title.innerHTML = campaign.name;

        var constraints = {
            width: app.device.viewport.width,
            height: app.device.viewport.height - (LevelScreen.HEADER_HEIGHT + LevelScreen.FOOTER_HEIGHT)
        };

        console.log('constraints', constraints);

        this.level = new MODULE.Level(campaign, this.level_el, constraints);

        this.grid = new MODULE.Grid(
            this.level.dimensions.width,
            this.level.dimensions.height,
            this.level.size,
            this.grid_el
        );

        this.level
        .on('generation', function(generation) {
            self.generation.textContent = generation;
        })
        .on('play-count', function(played) {
            self.played.textContent = played;
        })
        .on('status', function(status) {
            if (status === MODULE.Level.STATUS.DONE) {
                self.win();
            } else if (status === MODULE.Level.STATUS.LOSE) {
                self.lose();
            }
        })
        .on('win', function(data) {
            var my_level = app.storage.get('level', 0);
            var max_level = Object.keys(app.content.data.campaign).length;
            var levelup = false;

            if (data.level === max_level) {
                // TODO: Congratulate user on winning
                console.log("Beat the final level... Now what?");
            }

            if (data.level === my_level + 1) {
                levelup = true;
                app.storage.set('level', data.level);
                self.displayAdIfNeeded(data.level);
            }

            var rank = app.rank.get(data.level, data.generation, data.played);

            var rank_up = app.rank.report(data.level, rank.id);

            console.log('Rank up?', rank_up, rank);

            var content = LevelScreen.resultModal(rank, campaign.win, data.generation, data.played);

            if (levelup || rank_up) {
                app.modal.show(
                    content, [{
                        text: "Watch"
                    },{
                        text: "Next Level",
                        callback: function() {
                            app.screen.display('level', self.level_id + 1);
                        }
                    }], true
                );
            }

            app.analytics.track('LEVEL-WIN', {
                level: data.level,
                generation: data.generation,
                played: data.played,
                levelup: levelup
            });
        })
        .on('lose', function(data) {
            var rank = app.rank.getFailure();

            var content = LevelScreen.resultModal(rank, campaign.lose, data.generation, data.played);

            app.modal.show(
                content, [{
                    text: "Watch"
                },{
                    text: "Try Again",
                    callback: function() {
                        self.onStop();
                    }
                }], true
            );
        })
        .on('green-count', function(count) {
            self.mingreen_current.textContent = count;
        })
        .on('red-count', function(count) {
            self.maxred_current.textContent = count;
        });

        this.level.initialize();

        if (level_id > app.storage.get('level')) {
            this.incomplete();
            this.intro();
        } else {
            this.complete();
        }

        this.setGenerationGoal(this.level.autowin);
        this.setMaxPlay(this.level.maxplay);
        this.togglePlayedSegment(!!this.level.playables.length);
        this.toggleRedSegment(this.level.maxred);
        this.toggleGreenSegment(this.level.mingreen);

        var gamefield = this.level.gamefield;
        var finger = new Hammer(gamefield);
        finger.get('pinch').set({enable: true});

        /*
        finger.add(new Hammer.Pan({
            direction: Hammer.DIRECTION_ALL,
            threshold: 0
        }));
        */

        finger.on('pinchstart', function() {
            self.level.scaleStart();
        });

        finger.on('pinch', function(event) {
            self.level.scale(event.scale);
            self.grid.scale(self.level.size);
        });

        finger.on('pinchend', function() {
            self.level.scaleEnd();
        });

        // finger.on('pan', function(event) {});

        gamefield.onclick = function(event) {
            console.log('click');
            self.level.onTap(event);
        };

        // But hammer, I don't want you to stop my panning!
        gamefield.setAttribute('style', '');

        app.audio.playMusic('chapter-' + this.level.chapter);

        this.screen.style.display = 'block';

        this.library = null;

        app.analytics.track('SCREEN-LEVEL', {
            level: level_id
        });
    };

    LevelScreen.prototype.hide = function() {
        this.level.onStop();
        this.level = null;
        this.setGenerationGoal(0);
        this.setMaxPlay(0);
        this.screen.style.display = 'none';
    };

    LevelScreen.prototype.displayAdIfNeeded = function(level) {
        var min = app.content.data.dictionary.ad_min_level;
        var mod = app.content.data.dictionary.ad_mod_level;

        if (level >= min && level % mod === 0) {
            app.interstitial.show();
        }
    };

    LevelScreen.resultModal = function(rank, flavor, gen, played) {
        var html = "
\n";
            html += "

\n";
            html += "
\n";
                html += "
" + rank.name + "
\n";
                html += "
Gen: " + gen + " Played: " + played + "
\n";
            html += "
\n";
        html += "
\n";
        html += "
\n" + flavor + "
\n";

        return html;
    };

    LevelScreen.prototype.setGenerationGoal = function(generation) {
        this.autowin_goal.textContent = generation;

        this.autowin.classList.toggle('hide', !generation);
    };

    LevelScreen.prototype.setMaxPlay = function(maxplay) {
        this.maxplayval.textContent = maxplay;

        this.maxplay.classList.toggle('hide', !maxplay);
    };

    LevelScreen.prototype.togglePlayedSegment = function(count) {
        this.segment_played.classList.toggle('hide', !count);
        this.buttons.clear.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleRedSegment = function(count) {
        this.maxred_limit.textContent = count;
        this.segment_red.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleGreenSegment = function(count) {
        this.mingreen_limit.textContent = count;
        this.segment_green.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.complete = function() {
        this.header.classList.add('done');
        this.footer.classList.add('done');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.win = function() {
        this.header.classList.add('win');
        this.footer.classList.add('win');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.lose = function() {
        this.header.classList.add('lose');
        this.footer.classList.add('lose');
    };

    LevelScreen.prototype.incomplete = function() {
        this.header.classList.remove('done');
        this.footer.classList.remove('done');
        this.buttons.exit.classList.remove('cycle');
    };

    LevelScreen.prototype.intro = function() {
        app.modal.show("
" + this.level.name + "
" + this.level.description, [{
            text: "Ok"
        }]);
    };

    LevelScreen.prototype.getLibrary = function() {
        if (this.library) {
            return this.library;
        }

        var self = this;

        var library = '
';

        Object.keys(app.content.data.library).forEach(function(lib) {
            var item = app.content.data.library[lib];

            if (item.id > self.level.library) {
                return;
            }

            library +=
                '
' +
                    '' + item.name + '
' +
                    '' +
                '
';
        });

        library += '
';

        this.library = library;

        return this.library;
    };

    LevelScreen.prototype.onPlay = function() {
        app.audio.playSound('play');
        this.playcontrols.classList.remove('hide');
        this.stopcontrols.classList.add('hide');

        this.header.classList.add('playing');
        this.footer.classList.add('playing');

        app.analytics.track('LEVEL-START', {
            level: this.level_id
        });

        this.level.onPlay();
    };

    LevelScreen.prototype.onStop = function() {
        app.audio.playSound('stop');
        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');

        this.header.classList.remove('playing');
        this.footer.classList.remove('playing');
        //this.header.classList.add('win');
        //this.footer.classList.add('win');

        app.analytics.track('LEVEL-STOP', {
            level: this.level_id,
            generation: this.level.generation
        });

        this.unLose();
        this.level.onStop();
    };

    LevelScreen.prototype.unLose = function() {
        this.header.classList.remove('lose');
        this.footer.classList.remove('lose');
    };

    LevelScreen.prototype.onClear = function() {
        app.audio.playSound('clear');

        app.analytics.track('LEVEL-CLEAR', {
            level: this.level_id
        });

        this.level.onClear();
    };

    LevelScreen.prototype.onHelp = function() {
        this.intro();

        app.analytics.track('LEVEL-HELP', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onLibrary = function() {
        app.modal.show(this.getLibrary(), [{
            text: 'Ok'
        }]);

        app.analytics.track('LEVEL-LIBRARY', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onExit = function() {
        app.audio.playSound('back');
        app.screen.display('campaign');
    };

    return LevelScreen;
}());
<|endoftext|>


<commit_before>// ==UserScript==
// @name         A Mining Game: Fix minor issues
// @namespace    https://github.com/Phylogenesis/
// @version      0.1.4
// @description  Fixes some minor issues with the chat system and allows manual saving by clicking on the button in the top right
// @author       Luke Jones
// @include      /^http://trugul\.com/(index\.php)?$/
// @grant        none
// @downloadURL  https://github.com/Phylogenesis/greasemonkey/raw/master/AMGFixes.user.js
// ==/UserScript==

(function ($) {
    var AGame = {
        client: undefined
    };

    $(document).on(
        'click',
        'div.tabs a',
        function () {
            setTimeout(
                function () {
                    if ($('div.chat-room-message-container:visible').length > 0) {
                        $('div.chat-room-message-container').scrollTop($('div.chat-room-message-container')[0].scrollHeight);
                        $('body').css('padding-bottom', ($('div.popout').outerHeight() + 50) + 'px');
                    } else {
                        $('body').css('padding-bottom', '50px');
                    }
                },
                100
            );
        }
    );

    $(document).on(
        'click',
        'ul.navbar-right a',
        function (e) {
            if (AGame.client) {
                AGame.client.emit('save');
            }

            e.preventDefault();
        }
    );

    setTimeout(function () {
        AGame.client = io('http://5.189.137.117:469');
    }, 5000);
})(jQuery);

<commit_msg>Update AMGFixes.user.js<commit_after>// ==UserScript==
// @name         A Mining Game: Fix minor issues
// @namespace    https://github.com/Phylogenesis/
// @version      0.1.5
// @description  Fixes some minor issues with the chat system and allows manual saving by clicking on the button in the top right
// @author       Luke Jones
// @include      /^http://trugul\.com/(index\.php)?$/
// @grant        none
// @downloadURL  https://github.com/Phylogenesis/greasemonkey/raw/master/AMGFixes.user.js
// ==/UserScript==

(function ($) {
    var AGame = {
        client: undefined
    };

    $(document).on(
        'click',
        'div.tabs a',
        function () {
            setTimeout(
                function () {
                    if ($('div.chat-room-message-container:visible').length > 0) {
                        $('div.chat-room-message-container').scrollTop($('div.chat-room-message-container')[0].scrollHeight);
                        $('body').css('padding-bottom', $('div.popout').outerHeight() + 'px');
                    } else {
                        $('body').css('padding-bottom', 0);
                    }
                },
                100
            );
        }
    );

    $(document).on(
        'click',
        'ul.navbar-right a',
        function (e) {
            if (AGame.client) {
                AGame.client.emit('save');
            }

            e.preventDefault();
        }
    );

    setTimeout(function () {
        AGame.client = io('http://5.189.137.117:469');
    }, 5000);
})(jQuery);

<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * chameera.lakshitha212@gmail.com
 */
function checkPaginate(tblId) {
    jQuery('#'+tblId+'_paginate').hide();
    jQuery('#'+tblId+'_info').hide();
    jQuery('#comboId').change(function() {
        if (jQuery('#comboId').val() == 0) {
            jQuery('#'+tblId+'_paginate').hide();
            jQuery('#'+tblId+'_info').hide();
        } else {
            jQuery('#'+tblId+'_paginate').show();
            jQuery('#'+tblId+'_info').show();
        }
    });
}
function setupDataTableSettings(searchableText, paginateDiv, maxLength, tblId, printId, excelId) {
    checkPaginate(tblId);
    if (excelId == false) {
        $('.excelClz').hide();
    }
    if (printId == false) {
        $('.printClz').hide();
    }
    if (paginateDiv == false) {
        $('.dataTables_paginate ').remove();
    }
    if (searchableText == false) {
        $('.dataTables_filter ').remove();
    }
    var option = ['<option value="0">Select Count</option>'];
    for (var index = 0; index < maxLength.length; index++) {
        option.push('<option value="' + maxLength[index] + '" >' + maxLength[index] + '</option>');
    }
    $('#comboId').append(option.join());
    $('#comboId').css('width', '120px');
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("PRINT");
    btn.appendChild(t);
    document.getElementById(tblId).setAttribute("id", "dataTableId");
}
function setPrint(tableId) {
    var page = '
' + $('#' + tableId).html() + '
';
    w = window.open();
    w.document.write(page);
    w.print();
    w.close();

}
function setExcell(table_id) {
    var page = '
' + $('#' + table_id).html() + '
';
    window.open('data:application/vnd.ms-excel,' + encodeURIComponent(page));
    e.preventDefault();
}

<commit_msg>cutomize cetExcel funtion<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * chameera.lakshitha212@gmail.com
 */
function checkPaginate(tblId) {
    jQuery('#' + tblId + '_paginate').hide();
    jQuery('#' + tblId + '_info').hide();
    jQuery('#comboId').change(function() {
        if (jQuery('#comboId').val() == 0) {
            jQuery('#' + tblId + '_paginate').hide();
            jQuery('#' + tblId + '_info').hide();
        } else {
            jQuery('#' + tblId + '_paginate').show();
            jQuery('#' + tblId + '_info').show();
        }
    });
}
function setupDataTableSettings(searchableText, paginateDiv, maxLength, tblId, printId, excelId) {
    checkPaginate(tblId);
    if (excelId == false) {
        $('.excelClz').hide();
    }
    if (printId == false) {
        $('.printClz').hide();
    }
    if (paginateDiv == false) {
        $('.dataTables_paginate ').remove();
    }
    if (searchableText == false) {
        $('.dataTables_filter ').remove();
    }
    var option = ['<option value="0">Select Count</option>'];
    for (var index = 0; index < maxLength.length; index++) {
        option.push('<option value="' + maxLength[index] + '" >' + maxLength[index] + '</option>');
    }
    $('#comboId').append(option.join());
    $('#comboId').css('width', '120px');
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("PRINT");
    btn.appendChild(t);
    document.getElementById(tblId).setAttribute("id", "dataTableId");
}
function setPrint(tableId) {
    var page = '
' + $('#' + tableId).html() + '
';
    w = window.open();
    w.document.write(page);
    w.print();
    w.close();

}
var setExcell = function(table_id) {
    var uri = '';
    if (navigator.appVersion.indexOf("Win") != -1) {
        uri = 'data:application/vnd.ms-excel;base64,';
    }
    if (navigator.appVersion.indexOf("Linux") != -1) {
        uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,';
    }
    var ele = document.getElementById(table_id);
    if (ele.nodeName == "TABLE") {
        var template = '
' + document.getElementById(table_id).innerHTML + '
',
                a = document.createElement('a');
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
        a.setAttribute('download', 'a.xlsx');
        a.click();
    } else {
        alert('Not a table');
    }
}

<|endoftext|>


<commit_before>const React = require('react')
const {
  ComposableMap,
  ZoomableGroup,
  Geographies,
  Geography,
  Markers,
  Marker
} = require('react-simple-maps')
const { colors, grays } = require('../src/theme')
const locations = require('./locations')
const geo = require('./geo')
const styled = require('styled-components').default

const Pin = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    width={12}
    height={12}
  >
    <path
      d="M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3-8c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3z "
      fill={colors.primary}
    />
  </svg>
)

// const StyledGeo = styled(Geography)`
//   fill: ${grays.smoke};
//   stroke: ${grays.snow};
//   stroke-width: 0.75;
//   outline: none;
//   /* hide antarctica */
//   &[d^='M239.4352835706319'] {
//     display: none;
//   }
// `

const Map = props => (
  <ComposableMap width={1024} {...props}>
    <ZoomableGroup disablePanning>
      <Geographies geographyUrl="/static/geo.json">
        {(geographies, projection) =>
          geographies.map((geography, i) => (
            <Geography key={i} geography={geography} projection={projection} />
          ))}
      </Geographies>
      <Markers>
        {locations.map((marker, i) => (
          <Marker key={i} marker={marker} children={<Pin />} />
        ))}
      </Markers>
    </ZoomableGroup>
  </ComposableMap>
)

export default Map
<commit_msg>Fix Map<commit_after>const React = require('react')
const {
  ComposableMap,
  ZoomableGroup,
  Geographies,
  Geography,
  Markers,
  Marker
} = require('react-simple-maps')
const { colors, grays } = require('../theme')
const locations = require('./locations')
const geo = require('./geo')
const styled = require('styled-components').default

const StyledGeo = styled(Geography)`
  fill: ${grays.smoke};
  stroke: ${grays.snow};
  stroke-width: 0.75;
  outline: none;
  /* hide antarctica */
  &[d^='M239.4352835706319'] {
    display: none;
  }
`

const Map = props => (
  <ComposableMap
    width={1024}
    style={{
      width: '100%',
      height: 'auto'
    }}
    {...props}
  >
    <ZoomableGroup disablePanning>
      <Geographies geographyUrl="/geo.json">
        {(geographies, projection) =>
          geographies.map((geography, i) => (
            <StyledGeo key={i} geography={geography} projection={projection} />
          ))}
      </Geographies>
      <Markers>
        {locations.map((marker, i) => (
          <Marker key={i} marker={marker}>
            <circle
              cx={0}
              cy={0}
              r={8}
              style={{
                fill: colors.primary,
                strokeWidth: 0,
                opacity: 2 / 3
              }}
            />
          </Marker>
        ))}
      </Markers>
    </ZoomableGroup>
  </ComposableMap>
)

export default Map
<|endoftext|>