<commit_before>/**
 * 虚拟终端模块
 * 更新：2016/04/13
 * 作者：蚁逅 <https://github.com/antoor>
 */

const LANG = antSword['language']['terminal'];
const LANG_T = antSword['language']['toastr'];

class Terminal {

  constructor(opts) {
    // 生存一个随机ID，用于标识多个窗口dom
    const hash = String(Math.random()).substr(2, 10);

    // 初始化UI::tabbar
    const tabbar = antSword['tabbar'];
    tabbar.addTab(
      `tab_terminal_${hash}`,
      `<i class="fa fa-terminal"></i> ${opts['ip']}`,
      null, null, true, true
    );
    tabbar.attachEvent('onTabClick', (id,lid) => {
      if (id !== `tab_terminal_${hash}`) { return };
      this.term ? this.term.focus() : 0;
    });
    // 初始化UI::cell
    const cell = tabbar.cells(`tab_terminal_${hash}`);
    cell.attachHTMLString(`

    `);

    this.path = '';
    this.opts = opts;
    this.hash = hash;
    this.term = null;
    this.cell = cell;
    this.isWin = true;
    this.core = new antSword['core'][opts['type']](opts);
    this.cache = new antSword['CacheManager'](this.opts['_id']);

    this
      .getInformation()
      .then((ret) => {
        this.initTerminal(ret['info'], ret['dom']);
      })
      .catch((err) => {
        toastr.error((typeof(err) === 'object') ? JSON.stringify(err) : String(err), LANG_T['error']);
        this.cell.progressOff();
        this.cell.close();
      })
  }

  /**
   * 获取目标信息
   * @return {Promise} 返回一个Promise操作对象//{dom,info}
   */
  getInformation() {
    return new Promise((ret, rej) => {
      // 获取DOM
      const dom = $(`#div_terminal_${this.hash}`);
      // 获取缓存
      let infoCache = this.cache.get('info');
      // 如果有缓存？初始化终端：获取信息&&保存缓存&&初始化终端
      if (infoCache) {
        return ret({
          dom: dom,
          info: infoCache
        });
      }
      // 开始获取信息
      this.cell.progressOn();
      this.core.request(
        this.core.base.info()
      ).then((_ret) => {
        this.cell.progressOff();
        this.cache.set('info', _ret['text']);
        return ret({
          dom: dom,
          info: _ret['text']
        });
      }).catch((e) => {
        rej(e);
      });
    });
  }

  /**
   * 初始化终端
   * @param  {String} ret 目标信息
   * @param  {Object} dom 要操作的dom元素
   * @return {None}     [description]
   */
  initTerminal(ret, dom) {
    let info = ret.split('\t');
    let infoUser, infoPath, infoDrive, infoSystem;
    let banner = `[[b;cyan;](*) ${LANG['banner']['title']}]`;

    // 判断数据是否正确
    if (info.length === 4) {
      infoPath = info[0];
      infoDrive = info[1];
      infoSystem = info[2];
      infoUser = info[3];
    } else if (info.length === 2) {
      infoPath = info[0];
      infoDrive = info[1];
    } else {
      toastr.error('Loading infomations failed!
' + ret, LANG_T['error']);
      this.cache.del('info');
      return this.cell.close();
    }

    // 转换路径特殊字符
    infoPath = infoPath.replace(/\\/g, '/').replace(/\.$/, '');

    // 判断是否为!win
    this.isWin = !(infoPath.substr(0, 1) === '/')
    this.path = infoPath;

    // 组合banner
    banner += `\n[[b;#99A50D;]${LANG['banner']['path']}]: [[;#C3C3C3;]${infoPath}]`;
    banner += `\n[[b;#99A50D;]${LANG['banner']['drive']}]: [[;#C3C3C3;]${infoDrive}]`;
    if (info.length === 4) {
      banner += `\n[[b;#99A50D;]${LANG['banner']['system']}]: [[;#C3C3C3;]${infoSystem}]`;
      banner += `\n[[b;#99A50D;]${LANG['banner']['user']}]: [[;#C3C3C3;]${infoUser}]`;
    }

    // 初始化终端
    this.term = dom.terminal( (cmd, term) => {
      if (!cmd) { return false }
      // 如果为exit||quit则关闭窗口
      if (cmd === 'exit' || cmd === 'quit') { return this.cell.close() }
      // clear清空
      if (cmd === 'cls' || cmd === 'clear') { return term.clear() }
      // term.pause();
      // 是否有缓存
      let cacheTag = 'command-' + new Buffer(this.path + cmd).toString('base64');
      let cacheCmd = this.cache.get(cacheTag);
      if (
        (this.opts.otherConf || {})['terminal-cache'] === 1 && cacheCmd
      ) {
        term.echo(
          antSword.noxss(cacheCmd, false)
        );
        return term.resume();
      };
      // 获取自定义执行路径
      let _bin = this.isWin ? 'cmd' : '/bin/sh';
      let _confBin = (this.opts['otherConf'] || {})['command-path'];
      _bin = _confBin || _bin;
      // 开始执行命令
      this.core.request(
        this.core.command.exec({
          cmd: this.parseCmd(cmd, this.path),
          bin: _bin
        })
      ).then((ret) => {
        let _ = ret['text'];
        // 解析出命令执行路径
        const indexS = _.indexOf('[S]');
        const indexE = _.lastIndexOf('[E]');
        let _path = _.substr(indexS + 3, indexE - indexS - 3);

        let output = _.replace(`[S]${_path}[E]`, '');
        _path = _path.replace(/\n/g, '').replace(/\r/g, '');

        this.path = _path || this.path;
        term.set_prompt(this.parsePrompt(infoUser));

        // 去除换行符
        [
          /\n\n$/, /^\n\n/, /\r\r$/,
          /^\r\r/, /\r\n$/, /^\r\n/,
          /\n\r$/, /^\n\r/, /\r$/,
          /^\r/, /\n$/, /^\n/
        ].map((_) => {
          output = output.replace(_, '');
        });
        if (output.length > 0) {
          term.echo(
            antSword.noxss(output, false)
          );
          // 保存最大100kb数据
          if (output.length < (1024 * 1024)) {
            this.cache.set(cacheTag, output);
          };
        };
        term.resume();
      }).catch((_) => {
        // term.error('ERR: ' + (_ instanceof Object) ? JSON.stringify(_) : String(_));
        term.resume();
      });
    }, {
        greetings: banner,
        name: `terminal_${this.hash}`,
        prompt: this.parsePrompt(infoUser),
        exit: false,
        completion: (term, value, callback) => {
          callback(
            this.isWin ? [
              'dir', 'whoami', 'net', 'ipconfig', 'netstat', 'cls',
              'wscript', 'nslookup', 'copy', 'del', 'ren', 'md', 'type',
              'ping'
            ] : [
              'cd', 'ls', 'find', 'cp', 'mv', 'rm', 'ps', 'kill',
              'file', 'tar', 'cat', 'chown', 'chmod', 'pwd', 'history',
              'whoami', 'ifconfig', 'clear',
              'ping'
            ]
          )
        }
    });
  }

  /**
   * 根据执行命令&&路径生成最终command
   * @param  {String} cmd  要执行的命令
   * @param  {String} path 当前路径
   * @return {String}      最终执行命令
   */
  parseCmd(cmd, path) {
    path = path.replace(/\\\\/g, '\\').replace(/"/g, '\\"').replace(/\\/g, '\\\\');
    return (this.isWin
      ? `cd /d "${path}"&${cmd}&echo [S]&cd&echo [E]`
      : `cd "${path}";${cmd};echo [S];pwd;echo [E]`
    );
  }

  /**
   * 生成路径提示符
   * @param  {String} user 当前用户名
   * @return {String}      term输出字符串
   */
  parsePrompt(user) {
    return antSword.noxss(this.isWin
      ? `[[b;white;]${this.path.replace(/\//g, '\\')}> ]`
      : (user ? `([[b;#E80000;]${user}]:[[;#0F93D2;]` : '[[;0F93D2;]') + this.path + ']) $ '
    );
  }

}

// export default Terminal;
module.exports = Terminal;
<commit_msg>Pause for command execution is completed<commit_after>/**
 * 虚拟终端模块
 * 更新：2016/04/13
 * 作者：蚁逅 <https://github.com/antoor>
 */

const LANG = antSword['language']['terminal'];
const LANG_T = antSword['language']['toastr'];

class Terminal {

  constructor(opts) {
    // 生存一个随机ID，用于标识多个窗口dom
    const hash = String(Math.random()).substr(2, 10);

    // 初始化UI::tabbar
    const tabbar = antSword['tabbar'];
    tabbar.addTab(
      `tab_terminal_${hash}`,
      `<i class="fa fa-terminal"></i> ${opts['ip']}`,
      null, null, true, true
    );
    tabbar.attachEvent('onTabClick', (id,lid) => {
      if (id !== `tab_terminal_${hash}`) { return };
      this.term ? this.term.focus() : 0;
    });
    // 初始化UI::cell
    const cell = tabbar.cells(`tab_terminal_${hash}`);
    cell.attachHTMLString(`

    `);

    this.path = '';
    this.opts = opts;
    this.hash = hash;
    this.term = null;
    this.cell = cell;
    this.isWin = true;
    this.core = new antSword['core'][opts['type']](opts);
    this.cache = new antSword['CacheManager'](this.opts['_id']);

    this
      .getInformation()
      .then((ret) => {
        this.initTerminal(ret['info'], ret['dom']);
      })
      .catch((err) => {
        toastr.error((typeof(err) === 'object') ? JSON.stringify(err) : String(err), LANG_T['error']);
        this.cell.progressOff();
        this.cell.close();
      })
  }

  /**
   * 获取目标信息
   * @return {Promise} 返回一个Promise操作对象//{dom,info}
   */
  getInformation() {
    return new Promise((ret, rej) => {
      // 获取DOM
      const dom = $(`#div_terminal_${this.hash}`);
      // 获取缓存
      let infoCache = this.cache.get('info');
      // 如果有缓存？初始化终端：获取信息&&保存缓存&&初始化终端
      if (infoCache) {
        return ret({
          dom: dom,
          info: infoCache
        });
      }
      // 开始获取信息
      this.cell.progressOn();
      this.core.request(
        this.core.base.info()
      ).then((_ret) => {
        this.cell.progressOff();
        this.cache.set('info', _ret['text']);
        return ret({
          dom: dom,
          info: _ret['text']
        });
      }).catch((e) => {
        rej(e);
      });
    });
  }

  /**
   * 初始化终端
   * @param  {String} ret 目标信息
   * @param  {Object} dom 要操作的dom元素
   * @return {None}     [description]
   */
  initTerminal(ret, dom) {
    let info = ret.split('\t');
    let infoUser, infoPath, infoDrive, infoSystem;
    let banner = `[[b;cyan;](*) ${LANG['banner']['title']}]`;

    // 判断数据是否正确
    if (info.length === 4) {
      infoPath = info[0];
      infoDrive = info[1];
      infoSystem = info[2];
      infoUser = info[3];
    } else if (info.length === 2) {
      infoPath = info[0];
      infoDrive = info[1];
    } else {
      toastr.error('Loading infomations failed!
' + ret, LANG_T['error']);
      this.cache.del('info');
      return this.cell.close();
    }

    // 转换路径特殊字符
    infoPath = infoPath.replace(/\\/g, '/').replace(/\.$/, '');

    // 判断是否为!win
    this.isWin = !(infoPath.substr(0, 1) === '/')
    this.path = infoPath;

    // 组合banner
    banner += `\n[[b;#99A50D;]${LANG['banner']['path']}]: [[;#C3C3C3;]${infoPath}]`;
    banner += `\n[[b;#99A50D;]${LANG['banner']['drive']}]: [[;#C3C3C3;]${infoDrive}]`;
    if (info.length === 4) {
      banner += `\n[[b;#99A50D;]${LANG['banner']['system']}]: [[;#C3C3C3;]${infoSystem}]`;
      banner += `\n[[b;#99A50D;]${LANG['banner']['user']}]: [[;#C3C3C3;]${infoUser}]`;
    }

    // 初始化终端
    this.term = dom.terminal( (cmd, term) => {
      if (!cmd) { return false }
      // 如果为exit||quit则关闭窗口
      if (cmd === 'exit' || cmd === 'quit') { return this.cell.close() }
      // clear清空
      if (cmd === 'cls' || cmd === 'clear') { return term.clear() }
      term.pause();
      // 是否有缓存
      let cacheTag = 'command-' + new Buffer(this.path + cmd).toString('base64');
      let cacheCmd = this.cache.get(cacheTag);
      if (
        (this.opts.otherConf || {})['terminal-cache'] === 1 && cacheCmd
      ) {
        term.echo(
          antSword.noxss(cacheCmd, false)
        );
        return term.resume();
      };
      // 获取自定义执行路径
      let _bin = this.isWin ? 'cmd' : '/bin/sh';
      let _confBin = (this.opts['otherConf'] || {})['command-path'];
      _bin = _confBin || _bin;
      // 开始执行命令
      this.core.request(
        this.core.command.exec({
          cmd: this.parseCmd(cmd, this.path),
          bin: _bin
        })
      ).then((ret) => {
        let _ = ret['text'];
        // 解析出命令执行路径
        const indexS = _.indexOf('[S]');
        const indexE = _.lastIndexOf('[E]');
        let _path = _.substr(indexS + 3, indexE - indexS - 3);

        let output = _.replace(`[S]${_path}[E]`, '');
        _path = _path.replace(/\n/g, '').replace(/\r/g, '');

        this.path = _path || this.path;
        term.set_prompt(this.parsePrompt(infoUser));

        // 去除换行符
        [
          /\n\n$/, /^\n\n/, /\r\r$/,
          /^\r\r/, /\r\n$/, /^\r\n/,
          /\n\r$/, /^\n\r/, /\r$/,
          /^\r/, /\n$/, /^\n/
        ].map((_) => {
          output = output.replace(_, '');
        });
        if (output.length > 0) {
          term.echo(
            antSword.noxss(output, false)
          );
          // 保存最大100kb数据
          if (output.length < (1024 * 1024)) {
            this.cache.set(cacheTag, output);
          };
        };
        term.resume();
      }).catch((_) => {
        // term.error('ERR: ' + (_ instanceof Object) ? JSON.stringify(_) : String(_));
        term.resume();
      });
    }, {
        greetings: banner,
        name: `terminal_${this.hash}`,
        prompt: this.parsePrompt(infoUser),
        exit: false,
        completion: (term, value, callback) => {
          callback(
            this.isWin ? [
              'dir', 'whoami', 'net', 'ipconfig', 'netstat', 'cls',
              'wscript', 'nslookup', 'copy', 'del', 'ren', 'md', 'type',
              'ping'
            ] : [
              'cd', 'ls', 'find', 'cp', 'mv', 'rm', 'ps', 'kill',
              'file', 'tar', 'cat', 'chown', 'chmod', 'pwd', 'history',
              'whoami', 'ifconfig', 'clear',
              'ping'
            ]
          )
        }
    });
  }

  /**
   * 根据执行命令&&路径生成最终command
   * @param  {String} cmd  要执行的命令
   * @param  {String} path 当前路径
   * @return {String}      最终执行命令
   */
  parseCmd(cmd, path) {
    path = path.replace(/\\\\/g, '\\').replace(/"/g, '\\"').replace(/\\/g, '\\\\');
    return (this.isWin
      ? `cd /d "${path}"&${cmd}&echo [S]&cd&echo [E]`
      : `cd "${path}";${cmd};echo [S];pwd;echo [E]`
    );
  }

  /**
   * 生成路径提示符
   * @param  {String} user 当前用户名
   * @return {String}      term输出字符串
   */
  parsePrompt(user) {
    return antSword.noxss(this.isWin
      ? `[[b;white;]${this.path.replace(/\//g, '\\')}> ]`
      : (user ? `([[b;#E80000;]${user}]:[[;#0F93D2;]` : '[[;0F93D2;]') + this.path + ']) $ '
    );
  }

}

// export default Terminal;
module.exports = Terminal;
<|endoftext|>


<commit_before>(function ContextMenu($angular, $document) {

    "use strict";

    /**
     * @module ngContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    var module = $angular.module('ngContextMenu', []);

    /**
     * @module ngContextMenu
     * @service ContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.factory('contextMenu', ['$rootScope', function contextMenuService($rootScope) {

        /**
         * @method cancelAll
         * @return {void}
         */
        function cancelAll() {
            $rootScope.$broadcast('context-menu/close');
        }

        return { cancelAll: cancelAll, eventBound: false };

    }]);

    /**
     * @module ngContextMenu
     * @directive contextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.directive('contextMenu', ['$timeout', '$interpolate', '$compile', 'contextMenu', '$templateRequest', '$sce',

        function contextMenuDirective($timeout, $interpolate, $compile, contextMenu, $templateRequest, $sce) {

            return {

                /**
                 * @property restrict
                 * @type {String}
                 */
                restrict: 'EA',

                /**
                 * @property scope
                 * @type {Boolean}
                 */
                scope: true,

                /**
                 * @property require
                 * @type {String}
                 */
                require: '?ngModel',

                /**
                 * @method link
                 * @param {Object} scope
                 * @param {angular.element} element
                 * @param {Object} attributes
                 * @param {Object} model
                 * @return {void}
                 */
                link: function link(scope, element, attributes, model) {

                    if (!contextMenu.eventBound) {

                        // Bind to the `document` if we haven't already.
                        $document.addEventListener('click', function click() {
                            contextMenu.cancelAll();
                            scope.$apply();
                        });

                        contextMenu.eventBound = true;

                    }

                    /**
                     * @method closeMenu
                     * @return {void}
                     */
                    function closeMenu() {

                        if (scope.menu) {
                            scope.menu.remove();
                            scope.menu     = null;
                            scope.position = null;
                        }

                    }

                    scope.$on('context-menu/close', closeMenu);

                    /**
                     * @method getModel
                     * @return {Object}
                     */
                    function getModel() {
                        return model ? $angular.extend(scope, model.$modelValue) : scope;
                    }

                    /**
                     * @method render
                     * @param {Object} event
                     * @param {String} [strategy="append"]
                     * @return {void}
                     */
                    function render(event, strategy) {

                        strategy = strategy || 'append';

                        if ('preventDefault' in event) {

                            contextMenu.cancelAll();
                            event.stopPropagation();
                            event.preventDefault();
                            scope.position = { x: event.pageX, y: event.pageY };

                        } else {

                            if (!scope.menu) {
                                return;
                            }

                        }

                        $templateRequest($sce.getTrustedResourceUrl(attributes.contextMenu)).then(function then(template) {
                            var compiled     = $compile(template)($angular.extend(getModel())),
                                menu         = $angular.element(compiled);

                            // Determine whether to append new, or replace an existing.
                            switch (strategy) {
                                case ('append'): angular.element(document.body).append(menu); break;
                                default: scope.menu.replaceWith(menu); break;
                            }

                            menu.css({
                                position: 'fixed',
                                top: 0,
                                left: 0,
                                transform: $interpolate('translate({{x}}px, {{y}}px)')({
                                    x: scope.position.x - 1, y: scope.position.y - 1
                                })
                            });

                            scope.menu = menu;
                            scope.menu.bind('click', closeMenu);

                        });

                    }

                    if (model) {

                        var listener = function listener() {
                            return model.$modelValue;
                        };

                        // Listen for updates to the model...
                        scope.$watch(listener, function modelChanged() {
                            render({}, 'replaceWith');
                        }, true);

                    }

                    element.bind(attributes.contextEvent || 'contextmenu', render);

                }

            }

        }]);

})(window.angular, window.document);
<commit_msg>Detecting when click is left<commit_after>(function ContextMenu($angular, $document) {

    "use strict";

    /**
     * @module ngContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    var module = $angular.module('ngContextMenu', []);

    /**
     * @constant KEY_LEFT
     * @type {Number}
     */
    var KEY_LEFT = 1;

    /**
     * @module ngContextMenu
     * @service ContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.factory('contextMenu', ['$rootScope', function contextMenuService($rootScope) {

        /**
         * @method cancelAll
         * @return {void}
         */
        function cancelAll() {
            $rootScope.$broadcast('context-menu/close');
        }

        return { cancelAll: cancelAll, eventBound: false };

    }]);

    /**
     * @module ngContextMenu
     * @directive contextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.directive('contextMenu', ['$timeout', '$interpolate', '$compile', 'contextMenu', '$templateRequest', '$sce',

        function contextMenuDirective($timeout, $interpolate, $compile, contextMenu, $templateRequest, $sce) {

            return {

                /**
                 * @property restrict
                 * @type {String}
                 */
                restrict: 'EA',

                /**
                 * @property scope
                 * @type {Boolean}
                 */
                scope: true,

                /**
                 * @property require
                 * @type {String}
                 */
                require: '?ngModel',

                /**
                 * @method link
                 * @param {Object} scope
                 * @param {angular.element} element
                 * @param {Object} attributes
                 * @param {Object} model
                 * @return {void}
                 */
                link: function link(scope, element, attributes, model) {

                    if (!contextMenu.eventBound) {

                        // Bind to the `document` if we haven't already.
                        $document.addEventListener('click', function click(event) {

                            if (event.which === KEY_LEFT) {
                                contextMenu.cancelAll();
                                scope.$apply();
                            }
                        });

                        contextMenu.eventBound = true;

                    }

                    /**
                     * @method closeMenu
                     * @return {void}
                     */
                    function closeMenu() {

                        if (scope.menu) {
                            scope.menu.remove();
                            scope.menu     = null;
                            scope.position = null;
                        }

                    }

                    scope.$on('context-menu/close', closeMenu);

                    /**
                     * @method getModel
                     * @return {Object}
                     */
                    function getModel() {
                        return model ? $angular.extend(scope, model.$modelValue) : scope;
                    }

                    /**
                     * @method render
                     * @param {Object} event
                     * @param {String} [strategy="append"]
                     * @return {void}
                     */
                    function render(event, strategy) {

                        strategy = strategy || 'append';

                        if ('preventDefault' in event) {

                            contextMenu.cancelAll();
                            event.stopPropagation();
                            event.preventDefault();
                            scope.position = { x: event.pageX, y: event.pageY };

                        } else {

                            if (!scope.menu) {
                                return;
                            }

                        }

                        $templateRequest($sce.getTrustedResourceUrl(attributes.contextMenu)).then(function then(template) {

                            var compiled = $compile(template)($angular.extend(getModel())),
                                menu     = $angular.element(compiled);

                            // Determine whether to append new, or replace an existing.
                            switch (strategy) {
                                case ('append'): angular.element($document.body).append(menu); break;
                                default: scope.menu.replaceWith(menu); break;
                            }

                            menu.css({
                                position: 'fixed',
                                top: 0,
                                left: 0,
                                transform: $interpolate('translate({{x}}px, {{y}}px)')({
                                    x: scope.position.x, y: scope.position.y
                                })
                            });

                            scope.menu = menu;
                            scope.menu.bind('click', closeMenu);

                        });

                    }

                    if (model) {

                        var listener = function listener() {
                            return model.$modelValue;
                        };

                        // Listen for updates to the model...
                        scope.$watch(listener, function modelChanged() {
                            render({}, 'replaceWith');
                        }, true);

                    }

                    element.bind(attributes.contextEvent || 'contextmenu', render);

                }

            }

        }]);

})(window.angular, window.document);
<|endoftext|>


<commit_before><commit_msg>Add initial gameplay functions<commit_after>window.addEventListener('load', function(){
  if(typeof web3 === 'undefined'){
    web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io'));
    // alert('Please Download Metamask')
    //disable everything
  }else{

    contractAddress = '0xde03ba19d5238c2e610c39f55f4cc4bb3f806d1d';
    abi = [{"constant":true,"inputs":[],"name":"bet","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"splitFunds","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"returnFunds","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"determineWinner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"player2","outputs":[{"name":"addy","type":"address"},{"name":"commitHash","type":"bytes32"},{"name":"commitTime","type":"uint256"},{"name":"gameThrow","type":"uint256"},{"name":"revealTime","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"resetTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"commitHash","type":"bytes32"}],"name":"playerOneCommit","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"commitHash","type":"bytes32"}],"name":"playerTwoCommit","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"gameThrow","type":"uint256"},{"name":"secret","type":"uint256"}],"name":"playerOneReveal","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"stage","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"player1","outputs":[{"name":"addy","type":"address"},{"name":"commitHash","type":"bytes32"},{"name":"commitTime","type":"uint256"},{"name":"gameThrow","type":"uint256"},{"name":"revealTime","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"winner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"gameThrow","type":"uint256"},{"name":"secret","type":"uint256"}],"name":"playerTwoReveal","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_player1","type":"address"},{"name":"_player2","type":"address"},{"name":"_bet","type":"uint256"}],"payable":false,"type":"constructor"}];

    rockPaperScissors = web3.eth.contract(abi).at(contractAddress);

    betValue();
    currentStage();
    playerOneInfo();
    playerTwoInfo();
    playerOneCommit();
    playerTwoCommit();
    playerOneReveal();
    playerTwoReveal();
    determineWinner();
  }
})

betValue = function(){
  rockPaperScissors.bet.call(function(e, response){
    if(response){
      console.log('BET: ', response.toNumber() / 1000000000000000000);
      response.toNumber() / 1000000000000000000;
    }else{
      console.log('ERROR: ', e);
    }
  })
}

currentStage = function(){
  rockPaperScissors.stage.call(function(e, response){
    if(response){
      console.log('STAGE: ', response.toNumber());
      response.toNumber();
    }else{
      console.log('ERROR: ', e)
    }
  })
}

playerOneInfo = function(){
  rockPaperScissors.player1.call(function(e, response){
    if(response){
      console.log('PLAYER_1: ', response);
      response;
    }else{
      console.log('ERROR: ', e)
    }
  })
}

playerTwoInfo = function(){
  rockPaperScissors.player2.call(function(e, response){
    if(response){
      console.log('PLAYER_2: ', response);
      response;
    }else{
      console.log('ERROR: ', e)
    }
  })
}

playerOneCommit = function(commitHash){
  rockPaperScissors.playerOneCommit.call(commitHash, function(e, response){
    if(response){
      console.log('PLAYER_1 COMMIT: ', response);
    }else{
      console.log('ERROR: ', e);
    }
  })
}

playerTwoCommit = function(commitHash){
  rockPaperScissors.playerTwoCommit.call(commitHash, function(e, response){
    if(response){
      console.log('PLAYER_2 COMMIT: ', response);
    }else{
      console.log('ERROR: ', e);
    }
  })
}

playerOneReveal = function(gameThrow, secret){
  rockPaperScissors.playerOneReveal.call(gameThrow, secret, function(e, response){
    if(response){
      console.log('PLAYER_1 Reveal: ', response);
    }else{
      console.log('ERROR: ', e);
    }
  })
}

playerTwoReveal = function(gameThrow, secret){
  rockPaperScissors.playerTwoReveal.call(gameThrow, secret, function(e, response){
    if(response){
      console.log('PLAYER_2 Reveal: ', response);
    }else{
      console.log('ERROR: ', e);
    }
  })
}

determineWinner = function(){
  rockPaperScissors.determineWinner.call(function(e, response){
    if(response){
      console.log('DETERMINE WINNER: ', response);
    }else{
      console.log('ERROR: ', e);
    }
  })
}

<|endoftext|>


<commit_before>console.log('LOADED APPLICATION');

// Store user's location
var userPosition = {
	latitude: 0,
	longitude: 0
};

// Function that updates user location
function updatePosition(position) {
	userPosition.latitude = position.coords.latitude;
	userPosition.longitude = position.coords.longitude;
}

// Using the navigator class to get a location and update it with update method to userPosition variable
function getGeolocation(callback) {
	navigator.geolocation.getCurrentPosition(function(position) {
		updatePosition(position);
		console.log("Called Geolocator");
		if (callback) {
			callback();
		}
	});
}

// Accessor methods
function getLat() {
	return userPosition.latitude;
}
function getLon() {
	return userPosition.longitude;
}

function moveMap(map, userPosition) {
	map.setCenter({lat: userPosition.latitude, lng: userPosition.longitude});
	map.setZoom(14);
}

function initHereMap() {
	// Initialized communication with back-end services
	var platform = new H.service.Platform({
		app_id: "habu7uC2upRacruDrUfu",
		app_code: "85_CDKXMNkoraKX54-ZS-g",
		useCIT: true,
		useHTTPS: true
	});

	// Obtain the default map type from the platform object
	var defaultLayers = platform.createDefaultLayers();

	// Initialized a map - if location not given then it will give a world view
	var map = new H.Map(document.getElementById("map-container"), defaultLayers.normal.map, {
		center: new H.geo.Point(0, 51),
		zoom: 2
	});

	//Step 3: make the map interactive
	// MapEvents enables the event system
	// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
	var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));

	// Create the default UI components
	var ui = H.ui.UI.createDefault(map, defaultLayers);
}

<commit_msg>Finds user location on startup<commit_after>console.log('LOADED APPLICATION');

// Store user's location
var userPosition = {
	latitude: 0,
	longitude: 0
};

var map = null; // will be initialze later

// Function that updates user location
function updatePosition(position) {
	userPosition.latitude = position.coords.latitude;
	userPosition.longitude = position.coords.longitude;
}

// Using the navigator class to get a location and update it with update method to userPosition variable
function getGeolocation(callback) {
	navigator.geolocation.getCurrentPosition(function(position) {
		updatePosition(position);
		console.log("Called Geolocator");
		if (callback) {
			callback();
		}
	});
}

// Accessor methods
function getLat() {
	return userPosition.latitude;
}
function getLon() {
	return userPosition.longitude;
}

// move the map
function moveMap(map) {
	map.setCenter({lat: getLat(), lng: getLon()});
	map.setZoom(10); // zooming is inverted, bigger number = more zoom
}

function initHereMap() {
	// Initialized communication with back-end services
	var platform = new H.service.Platform({
		app_id: "habu7uC2upRacruDrUfu",
		app_code: "85_CDKXMNkoraKX54-ZS-g",
		useCIT: true,
		useHTTPS: true
	});

	// Obtain the default map type from the platform object
	var defaultLayers = platform.createDefaultLayers();

	// Initialized a map - if location not given then it will give a world view
	var map = new H.Map(document.getElementById("map-container"), defaultLayers.normal.map /*, {
		remove the quotes to add a default init location
		center: setCenter({lat: getLat(), lng: getLon()});
		zoom: setZoom(11);
	} */ );

	//Step 3: make the map interactive
	// MapEvents enables the event system
	// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
	var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));

	// Create the default UI components
	var ui = H.ui.UI.createDefault(map, defaultLayers);

	moveMap(map)
}

<|endoftext|>


<commit_before>
var PN532_PREAMBLE = 0x00;
var PN532_STARTCODE2 = 0xFF;
var PN532_POSTAMBLE = 0x00;
var PN532_HOSTTOPN532 = 0xD4;
var PN532_COMMAND_GETFIRMWAREVERSION = 0x02;
var PN532_COMMAND_SAMCONFIGURATION = 0x14;
var PN532_COMMAND_INLISTPASSIVETARGET = 0x4A;
var PN532_COMMAND_INDATAEXCHANGE = 0x40;
var PN532_SPI_STATREAD = 0x02;
var PN532_SPI_DATAWRITE = 0x01;
var PN532_SPI_DATAREAD = 0x03;
var PN532_SPI_READY = 0x01;
var MIFARE_ULTRALIGHT_CMD_WRITE = 0xA2;
var MIFARE_CMD_READ = 0x30;

var PN532 = function(connect) {

  connect = connect || {};

  this._SPI = connect.spi;
  this._ss = connect.csPin;
  this._irq = connect.irqPin;

  this._pn532ack = new Uint8Array([0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00]);
  this._pn532responseFirmwarevers = new Uint8Array([
    0x00,
    0xFF,
    0x06,
    0xFA,
    0xD5,
    0x03
  ]);
  this._packetBuffer = new Uint8Array(64);

  this.imWaitingFor = new Array();

  this._maxPage = 48;
};

PN532.prototype.wakeUp = function(callback) {

  console.log('wakeUp function');

  setWatch(this.IRQ.bind(this), this._irq, {repeat: true, debounce: 0.1});

  this._packetBuffer[0] = PN532_COMMAND_GETFIRMWAREVERSION;
  this.sendCommandCheckAck(this._packetBuffer, 1);
  this.imWaitingFor.push(this.SAMConfig.bind(this, callback));
};

PN532.prototype.IRQ = function(e) {
  console.log('IRQ state', e.state);
  if (e.state === false) {
    // console.log('IRQ function', this.imWaitingFor);
    var irqWasFor = this.imWaitingFor.splice(0, 1);
    if (typeof irqWasFor[0] === 'function') {
      irqWasFor[0]();
    }
  }
};

PN532.prototype.sendCommandCheckAck = function(cmd, cmdLen) {
  console.log('sendCommandCheckAck function');
  this.writeCommand(cmd, cmdLen);
  // this.imWaitingFor.push('IRQ_readACK');
  this.imWaitingFor.push(this.readACK.bind(this));
};

PN532.prototype.printHex = function(data) {
  for (var i in data) {
    data[i] = data[i].toString(16) + ' ';
  }
  print(data);
};

PN532.prototype.version = function(callback) {
  this._packetBuffer[0] = PN532_COMMAND_GETFIRMWAREVERSION;
  this.sendCommandCheckAck(this._packetBuffer, 1);
  this.imWaitingFor.push(this.versionACK.bind(this, callback));
};

PN532.prototype.versionACK = function(callback) {

  var result = this.read(13);
  console.log('versionACK:', result);
  if (result !== this._pn532responseFirmwarevers) {
    callback(true);
    return;
  }
  // 6 - offset for data
  var offset = 6;
  var response = result[offset++];
  response <<= 8;
  response |= result[offset++];
  response <<= 8;
  response |= result[offset++];
  response <<= 8;
  response |= result[offset++];

  callback(false, response);
};

PN532.prototype.SAMConfig = function(callback) {
  console.log('SAMConfig function');
  this._packetBuffer[0] = PN532_COMMAND_SAMCONFIGURATION;
  this._packetBuffer[1] = 0x01; // normal mode;
  this._packetBuffer[2] = 0x14; // timeout 50ms * 20 = 1 second
  this._packetBuffer[3] = 0x01; // use IRQ pin!

  this.sendCommandCheckAck(this._packetBuffer, 4);
  // this.imWaitingFor.push('IRQ_SAMConfigACK');
  this.imWaitingFor.push(this.SAMConfigACK.bind(this, callback));
};

PN532.prototype.SAMConfigACK = function(callback) {
  console.log('SAMConfigACK function');
  this._packetBuffer = this.read(9);
  if (callback !== undefined) {
    callback(this._packetBuffer[6] !== 0x15);
  }
  // this.imWaitingFor.push('configured');
};

PN532.prototype.listen = function() {
  console.log('listen function');
  var buffer = new Uint8Array([PN532_COMMAND_INLISTPASSIVETARGET, 1, 0]);

  this.sendCommandCheckAck(buffer, 3);
  // this.imWaitingFor.push('IRQ_readPassiveTargetIDACK');
  this.imWaitingFor.push(this.listenACK.bind(this));
};

PN532.prototype.listenACK = function() {
  console.log('listenACK function');
  this._packetBuffer = this.read(20);
  if (this._packetBuffer[7] !== 1) {
    this.emit('tag', {success: false});
  }
  var ATQA = this._packetBuffer[9];
  ATQA <<= 8;
  ATQA |= this._packetBuffer[10];

  var uid = new Array(this._packetBuffer[12]);
  for (var i = 0; i < this._packetBuffer[12]; i++) {
    uid[i] = this._packetBuffer[13+i];
  }

  this.emit('tag', false, {uid: uid, ATQA: ATQA});
};

PN532.prototype.skipIRQ = function() {
  console.log('passIRQ function');
};

PN532.prototype.sleep = function() {
  console.log('sleep function');
  this._packetBuffer[0] = 0x16;
  this._packetBuffer[1] = 0x20;
  this._packetBuffer[2] = 0x00;

  var len = this.imWaitingFor;
  this.imWaitingFor.splice(0, len);

  this.sendCommandCheckAck(this._packetBuffer, 3);
  this.imWaitingFor.push(this.sleepACK.bind(this));
  this.imWaitingFor.push(this.skipIRQ.bind(this));
};

PN532.prototype.sleepACK = function() {
  console.log('sleepACK function');
  var success = true;
  this._packetBuffer = this.read(8);
  if (this._packetBuffer[6] !== 0x17) {
    console.log('ERROR sleep:', this._packetBuffer.slice(6, 8));
  }
  var error = this._packetBuffer[7] & 0x3F;
  if (error !== 0) {
    console.log('ERROR sleep:', error);
  }
  this.emit('sleep', {success: success});
};

PN532.prototype.readPage = function(page, callback) {
  console.log('readPage function');
  if (page >= this._maxPage) {
    if (callback !== undefined) {
      callback(true);
    }
    return;
  }
  this._packetBuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
  this._packetBuffer[1] = 1;               // Card number
  this._packetBuffer[2] = MIFARE_CMD_READ; // Mifare Read command = 0x30
  this._packetBuffer[3] = page;            // Page Number (0..63 in most cases)

  this.sendCommandCheckAck(this._packetBuffer, 4);
  this.imWaitingFor.push(this.readPageACK.bind(this, callback));
};

PN532.prototype.readPageACK = function(callback) {
  console.log('readPageACK function');
  var error = true;
  this._packetBuffer = this.read(26);
  if (this._packetBuffer[7] !== 0x00) {
    if (callback !== undefined) {
      callback(error);
    }
    return;
  }
  var buffer = this._packetBuffer.slice(8, 12);
  callback(!error, buffer);
};

PN532.prototype.writePage = function(page, data, callback) {
  if (page >= this._maxPage) {
    if (callback !== undefined) {
      callback(true);
    }
    return;
  }

  this._packetBuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
  this._packetBuffer[1] = 1;                      /* Card number */
  this._packetBuffer[2] = MIFARE_ULTRALIGHT_CMD_WRITE;
  this._packetBuffer[3] = page;
  this._packetBuffer[4] = data[0];
  this._packetBuffer[5] = data[1];
  this._packetBuffer[6] = data[2];
  this._packetBuffer[7] = data[3];
  this.sendCommandCheckAck(this._packetBuffer, 8);

  this.imWaitingFor.push(this.writePageACK.bind(this, callback));
};

PN532.prototype.writePageACK = function(callback) {
  this._packetBuffer = this.read(26);
  if (callback !== undefined) {
    callback(false, this._packetBuffer);
  }
};

PN532.prototype.readACK = function() {
  console.log('readACK function');
  var ackBuff = this.read(6);
  if (ackBuff !== this._pn532ack) {
    console.log('readACK function ERROR');
    this.printHex(ackBuff);
    console.log('ackBuff not correct');
  }
  return this._pn532ack === ackBuff;
};

PN532.prototype.read = function(length) {

  // print('Reading: ');

  var send = new Uint8Array([PN532_SPI_DATAREAD]);
  this._SPI.send(send, this._ss);
  var send2 = new Uint8Array(length);
  send2.fill(PN532_SPI_DATAREAD);
  var data = this._SPI.send(send2, this._ss);
  // console.log('Reading data:', data);
  return data;
};

PN532.prototype.writeCommand = function(cmd, cmdlen) {

  cmdlen++;

  // print('writeCommand Sending: ');

  var toSend = [
    PN532_SPI_DATAWRITE,
    PN532_PREAMBLE,
    PN532_PREAMBLE,
    PN532_STARTCODE2,
    cmdlen,
    ~cmdlen + 1,
    PN532_HOSTTOPN532
  ];

  var checksum = new Uint8Array(1);

  checksum[0] = PN532_PREAMBLE + PN532_PREAMBLE
            + PN532_STARTCODE2 + PN532_HOSTTOPN532;

  for (var i = 0; i < cmdlen - 1; i++) {
    toSend.push(cmd[i]);
    checksum[0] += cmd[i];
  }

  toSend.push(~checksum[0]);
  toSend.push(PN532_POSTAMBLE);

  // print(toSend);

  var send = new Uint8Array(toSend, 0, 9 + cmdlen);

  this._SPI.send(send, this._ss);
};

exports.connect = function(opts) {
  return new PN532(opts);
};
<commit_msg>rid of logger<commit_after>
var PN532_PREAMBLE = 0x00;
var PN532_STARTCODE2 = 0xFF;
var PN532_POSTAMBLE = 0x00;
var PN532_HOSTTOPN532 = 0xD4;
var PN532_COMMAND_GETFIRMWAREVERSION = 0x02;
var PN532_COMMAND_SAMCONFIGURATION = 0x14;
var PN532_COMMAND_INLISTPASSIVETARGET = 0x4A;
var PN532_COMMAND_INDATAEXCHANGE = 0x40;
var PN532_SPI_DATAWRITE = 0x01;
var PN532_SPI_DATAREAD = 0x03;
var MIFARE_ULTRALIGHT_CMD_WRITE = 0xA2;
var MIFARE_CMD_READ = 0x30;

var PN532 = function(connect) {

  connect = connect || {};

  this._SPI = connect.spi;
  this._ss = connect.csPin;
  this._irq = connect.irqPin;

  this._packetBuffer = new Uint8Array(48);
  this.imWaitingFor = new Array();
  this._maxPage = 48;
};

PN532.prototype.wakeUp = function(callback) {

  setWatch(this._IRQ.bind(this), this._irq, {repeat: true, debounce: 0.1});

  this._packetBuffer[0] = PN532_COMMAND_GETFIRMWAREVERSION;
  this._sendCommandCheckAck(this._packetBuffer, 1);
  this.imWaitingFor.push(this.SAMConfig.bind(this, callback));
};

PN532.prototype._IRQ = function(e) {
  if (e.state === false) {
    var irqWasFor = this.imWaitingFor.splice(0, 1);
    if (typeof irqWasFor[0] === 'function') {
      irqWasFor[0]();
    }
  }
};

PN532.prototype._sendCommandCheckAck = function(cmd, cmdlen) {
  cmdlen++;
  var toSend = [
    PN532_SPI_DATAWRITE,
    PN532_PREAMBLE,
    PN532_PREAMBLE,
    PN532_STARTCODE2,
    cmdlen,
    ~cmdlen + 1,
    PN532_HOSTTOPN532
  ];
  var checksum = new Uint8Array(1);
  checksum[0] = PN532_PREAMBLE + PN532_PREAMBLE
            + PN532_STARTCODE2 + PN532_HOSTTOPN532;

  for (var i = 0; i < cmdlen - 1; i++) {
    toSend.push(cmd[i]);
    checksum[0] += cmd[i];
  }
  toSend.push(~checksum[0]);
  toSend.push(PN532_POSTAMBLE);

  var send = new Uint8Array(toSend, 0, 9 + cmdlen);
  this._SPI.send(send, this._ss);

  this.imWaitingFor.push(this.readACK.bind(this));
};

PN532.prototype.SAMConfig = function(callback) {
  this._packetBuffer[0] = PN532_COMMAND_SAMCONFIGURATION;
  this._packetBuffer[1] = 0x01; // normal mode;
  this._packetBuffer[2] = 0x14; // timeout 50ms * 20 = 1 second
  this._packetBuffer[3] = 0x01; // use IRQ pin!

  this._sendCommandCheckAck(this._packetBuffer, 4);
  this.imWaitingFor.push(this.SAMConfigACK.bind(this, callback));
};

PN532.prototype.SAMConfigACK = function(callback) {
  this._packetBuffer = this.read(9);
  if (callback !== undefined) {
    callback(this._packetBuffer[6] !== 0x15);
  }
};

PN532.prototype.listen = function() {
  var buffer = new Uint8Array([PN532_COMMAND_INLISTPASSIVETARGET, 1, 0]);
  this._sendCommandCheckAck(buffer, 3);
  this.imWaitingFor.push(this.listenACK.bind(this));
};

PN532.prototype.listenACK = function() {
  this._packetBuffer = this.read(20);
  if (this._packetBuffer[7] !== 1) {
    this.emit('tag', {success: false});
    return;
  }
  var ATQA = this._packetBuffer[9];
  ATQA <<= 8;
  ATQA |= this._packetBuffer[10];
  var uid = new Array(this._packetBuffer[12]);
  for (var i = 0; i < this._packetBuffer[12]; i++) {
    uid[i] = this._packetBuffer[13+i];
  }
  this.emit('tag', false, {uid: uid, ATQA: ATQA});
};

PN532.prototype.readPage = function(page, callback) {
  if (page >= this._maxPage) {
    if (callback !== undefined) {
      callback(true);
    }
    return;
  }
  this._packetBuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
  this._packetBuffer[1] = 1;               // Card number
  this._packetBuffer[2] = MIFARE_CMD_READ; // Mifare Read command = 0x30
  this._packetBuffer[3] = page;            // Page Number (0..63 in most cases)

  this._sendCommandCheckAck(this._packetBuffer, 4);
  this.imWaitingFor.push(this.readPageACK.bind(this, callback));
};

PN532.prototype.readPageACK = function(callback) {
  var error = true;
  this._packetBuffer = this.read(26);
  if (this._packetBuffer[7] !== 0x00) {
    if (callback !== undefined) {
      callback(error);
    }
    return;
  }
  var buffer = this._packetBuffer.slice(8, 12);
  callback(!error, buffer);
};

PN532.prototype.writePage = function(page, data, callback) {
  if (page >= this._maxPage) {
    if (callback !== undefined) {
      callback(true);
    }
    return;
  }

  this._packetBuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
  this._packetBuffer[1] = 1; /* Card number */
  this._packetBuffer[2] = MIFARE_ULTRALIGHT_CMD_WRITE;
  this._packetBuffer[3] = page;
  this._packetBuffer[4] = data[0];
  this._packetBuffer[5] = data[1];
  this._packetBuffer[6] = data[2];
  this._packetBuffer[7] = data[3];
  this._sendCommandCheckAck(this._packetBuffer, 8);

  this.imWaitingFor.push(this.writePageACK.bind(this, callback));
};

PN532.prototype.writePageACK = function(callback) {
  this._packetBuffer = this.read(26);
  if (callback !== undefined) {
    callback(false, this._packetBuffer);
  }
};

PN532.prototype.read = function(length) {
  var buffer = new Uint8Array(length);
  buffer.fill(PN532_SPI_DATAREAD);
  this._SPI.send(buffer.slice(0, 1), this._ss);
  var data = this._SPI.send(buffer, this._ss);
  return data;
};

PN532.prototype.readACK = function() {
  var ackBuff = this.read(6);
  var pn532ack = new Uint8Array([0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00]);
  if (ackBuff !== pn532ack) {
    print(ackBuff);
  }
  return this._pn532ack === ackBuff;
};

exports.connect = function(opts) {
  return new PN532(opts);
};
<|endoftext|>


<commit_before>// import "jquery.js"

$(document).ready(function(){
  getIP()
  $(document).click(getClicksPerSession)
  // $(window).unload(sendUser)
  $('a').click(addDestination)
  $(window).bind('beforeunload', sendUser)
})

function getIP(){
  $.get("http://ipinfo.io", function(response) {
    user = response;
    user.arrival = new Date
    user.clicks = 0
    user.domain = "test"
    // now = getTime()
  }, "jsonp");
}

function getClicksPerSession(e){
  user.clicks += 1

function addDestination(){
  user.destination = $(this).attr("href")
}

function sendUser(e){
  e.preventDefault()
  user.leave = new Date
  $.ajax({
    type: "POST",
    url: "http://localhost:3000/visitors/manage",
    data: user,
  }).done(function(){
    console.log(user.destination)
  }).fail(function(e){
    console.log(e)
  })
}
<commit_msg>update way clicks are managed<commit_after>// import "jquery.js"

$(document).ready(function(){
  getIP()
  $(document).click(getClicksPerSession)
  // $(window).unload(sendUser)
  $('a').click(addDestination)
  $(window).bind('beforeunload', sendUser)
})

function getIP(){
  $.get("http://ipinfo.io", function(response) {
    user = response;
    user.arrival = new Date
    user.clicks = 0
    user.domain = "test"
    // now = getTime()
  }, "jsonp");
}

function getClicksPerSession(e){
  user.clicks += 1
}

function addDestination(){
  user.destination = $(this).attr("href")
}

function sendUser(e){
  e.preventDefault()
  user.leave = new Date
  $.ajax({
    type: "POST",
    url: "http://localhost:3000/visitors/manage",
    data: user,
  }).done(function(){
    console.log(user.destination)
  }).fail(function(e){
    console.log(e)
  })
}
<|endoftext|>


<commit_before>// Инициализация класса
var Rtc = function(i2c) {
  this._time = undefined;
  this._i2c = i2c || PrimaryI2C;
  this._address = 0x68;
  this.start();
};

// Метод записывает данные data в регистр reg
Rtc.prototype.write = function(reg, data) {
  this._i2c.writeTo(this._address, [reg, data]);
};

// Метод производит чтение из регистра reg количестов байт count
Rtc.prototype.read = function(reg, count) {
  if (count === undefined) {
    count = 1;
  }
  this._i2c.writeTo(this._address, reg);
  return this._i2c.readFrom(this._address, count);
};

Rtc.prototype._decToBcd = function(val) {
  return Math.floor(val / 10) * 16 + (val % 10);
};

Rtc.prototype._bcdToDec = function(val) {
  return Math.floor(val / 16) * 10 + (val % 16);
};

Rtc.prototype.setTime = function(time) {
  if (time instanceof Date) {
    this._time = time;
  } else if (time instanceof Object){
    this._time = new Date(
      time.year,
      time.month,
      time.day,
      time.hour,
      time.minute,
      time.second
    );
  } else if (typeof time === 'number') {
    this._time = new Date(time * 1000);
  } else if (typeof time === 'string') {
    this._time = new Date(Date.parse(time));
  } else {
    this._time = new Date(getTime()*1000);
  }

  var halt = this.read(0x00, 1)[0] >> 7;
  this.write(0x00, [
    this._decToBcd(this._time.getSeconds()) | (halt << 7),
    this._decToBcd(this._time.getMinutes()),
    this._decToBcd(this._time.getHours()),
    this._decToBcd(this._time.getDay() + 1),
    this._decToBcd(this._time.getDate()),
    this._decToBcd(this._time.getMonth() + 1),
    this._decToBcd(this._time.getFullYear() - 2000)
  ]);
};

Rtc.prototype.getTime = function(unit) {
  var time = this.read(0x00, 7);
  this._time = new Date(
    this._bcdToDec(time[6]) + 2000,
    this._bcdToDec(time[5]) - 1,
    this._bcdToDec(time[4]),
    this._bcdToDec(time[2] & 0x3f),
    this._bcdToDec(time[1]),
    this._bcdToDec(time[0] & 0x7f)
  );

  var res = this._time;
  switch (unit) {
    case 'unixtime':
      res = Math.ceil(res.getTime() / 1000);
      break;
    case 'iso':
      res = res.getFullYear() + '-' + res.getMonth() + 1 +
         '-' + res.getDay() + 'T' + res.getHours() +
         ':' + res.getMinutes() + ':' + res.getSeconds();
      break;
  }
  return res;
};

Rtc.prototype.start = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7) {
    this.write(0x00, byte ^ 0x80);
  }
};

Rtc.prototype.stop = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7 === 0) {
    this.write(0x00, byte ^ 0x80);
  }
};

// Экспортируем класс
exports.connect = function(i2c) {
  return new Rtc(i2c);
};
<commit_msg>now u can work with it<commit_after>// Инициализация класса
var Rtc = function(i2c) {
  this._time = undefined;
  this._i2c = i2c || PrimaryI2C;
  this._address = 0x68;
  this.start();
};

// Метод записывает данные data в регистр reg
Rtc.prototype.write = function(reg, data) {
  this._i2c.writeTo(this._address, [reg, data]);
};

// Метод производит чтение из регистра reg количестов байт count
Rtc.prototype.read = function(reg, count) {
  if (count === undefined) {
    count = 1;
  }
  this._i2c.writeTo(this._address, reg);
  return this._i2c.readFrom(this._address, count);
};

Rtc.prototype._decToBcd = function(val) {
  return Math.floor(val / 10) * 16 + (val % 10);
};

Rtc.prototype._bcdToDec = function(val) {
  return Math.floor(val / 16) * 10 + (val % 16);
};

Rtc.prototype.setTime = function(time) {
  if (time instanceof Date) {
    this._time = time;
  } else if (time instanceof Object){
    this._time = new Date(
      time.year,
      time.month,
      time.day,
      time.hour,
      time.minute,
      time.second
    );
  } else if (typeof time === 'number') {
    this._time = new Date(time * 1000);
  } else if (typeof time === 'string') {
    this._time = new Date(Date.parse(time));
  } else {
    this._time = new Date(getTime()*1000);
  }

  var halt = this.read(0x00, 1)[0] >> 7;
  this.write(0x00, [
    this._decToBcd(this._time.getSeconds()) | (halt << 7),
    this._decToBcd(this._time.getMinutes()),
    this._decToBcd(this._time.getHours()),
    this._decToBcd(this._time.getDay() + 1),
    this._decToBcd(this._time.getDate()),
    this._decToBcd(this._time.getMonth() + 1),
    this._decToBcd(this._time.getFullYear() - 2000)
  ]);
};

Rtc.prototype.getTime = function(format) {
  var time = this.read(0x00, 7);
  this._time = new Date(
    this._bcdToDec(time[6]) + 2000,
    this._bcdToDec(time[5]) - 1,
    this._bcdToDec(time[4]),
    this._bcdToDec(time[2] & 0x3f),
    this._bcdToDec(time[1]),
    this._bcdToDec(time[0] & 0x7f)
  );

  var res = this._time;
  switch (format) {
    case 'unixtime':
      res = Math.ceil(res.getTime() / 1000);
      break;
    case 'iso':
      res = res.getFullYear() + '-' + res.getMonth() + 1 +
         '-' + res.getDay() + 'T' + res.getHours() +
         ':' + res.getMinutes() + ':' + res.getSeconds();
      break;
    default: break;
  }
  return res;
};

Rtc.prototype.start = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7) {
    this.write(0x00, byte ^ 0x80);
  }
};

Rtc.prototype.stop = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7 === 0) {
    this.write(0x00, byte ^ 0x80);
  }
};

// Экспортируем класс
exports.connect = function(i2c) {
  return new Rtc(i2c);
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Module dependencies.
 */
var express = require('express');
var app = express();
var path = require('path');

var port = 3000;

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(port);
console.log('Listening at http://localhost:' + port);
<commit_msg>Added route to static assets.<commit_after>#!/usr/bin/env node

/**
 * Module dependencies.
 */
var express = require('express');
var app = express();
var path = require('path');

var port = 3000;

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});
app.use(express.static(path.join(__dirname, '/')));

app.listen(port);
console.log('Listening at http://localhost:' + port);
<|endoftext|>


<commit_before>'use strict';

describe('myApp.view1 module', function() {

  beforeEach(module('myApp.view1'));

  describe('view1 controller', function(){

    var scope;

    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        $controller('View1Ctrl', {$scope: scope});
    }));

    //New tests testing just behaviour

    it('should return empty when new', function() {
      expect(scope.remove()).toBe("");
    });

    it('should return first/oldest added value when not overwriting', function() {
      var quantity = getRandomInt(1, scope.size);
      var memory = new Array(scope.size);
      for(var i = 0; i < quantity; i++) {
        var value = getRandomInt(0, 9);
        scope.add(value);
        memory[i] = value;
      }
      for(var i = 0; i < quantity; i++) {
        expect(scope.remove()).toBe(memory[i]);
      }
    });

    it('should return oldest added value when overwriting', function() {
      var quantity = getRandomInt(1, scope.size) + scope.size;
      var memory = new Array(quantity);
      //alert("Adding");
      for(var i = 0; i < quantity; i++) {
        var value = getRandomInt(0, 9);
        //printBuffer();
        scope.add(value);
        memory[i] = value;
      }
      //alert("Removing");
      //alert("Memory " + memory)
      for(var i = 0; i < scope.size; i++) {
        //printBuffer();
        var value = scope.remove();
        expect(value).toBe(memory[quantity-scope.size+i]);
      }
    });

    //Old tests testing state

    it('should initialize circularBuffer array with length=size and position 0', function() {
        expect(scope.circularBuffer.length).toBe(scope.size);
        expect(scope.end).toBe(0);
    });

    it('should add new value to end', function() {
        var end = scope.end;
        scope.add(5);
        expect(scope.end).toBe(end+1);
        expect(scope.circularBuffer[end].value).toBe(5);
    });

    it('should remove value from start, increment start', function() {
        scope.add(5);
        var start = scope.start;
        var temp = scope.remove();
        expect(scope.start).toBe(start+1);
        expect(temp).toBe(5);
        expect(scope.circularBuffer[start].value).toBe("");
    });

    it('should not change start and end if empty, returned value shoud be empty', function() {
        var start = scope.start;
        var end = scope.end;
        var temp = scope.remove();
        expect(scope.start).toBe(start);
        expect(scope.end).toBe(end);
        expect(temp).toBe("");
    });

    it('should go to beginning if end is reached', function() {
        var size = scope.size;
        for (var i = 0; i < size; i++) {
          scope.add(i);
        }
        expect(scope.end).toBe(0);
    });

    it('should overwrite if full', function() {
        var size = scope.size+1;
        var start = scope.start;
        for (var i = 0; i < size; i++) {
          scope.add(i);
        }
        expect(scope.circularBuffer[start].value).toBe(size-1);
    });

    it('should return oldest when overwrote', function() {
        var size = scope.size+2;
        var start = scope.start;
        for (var i = 0; i < size; i++) {
          scope.add(i);
        }
        expect(scope.remove()).toBe(2);
        expect(scope.remove()).toBe(3);
    });

    it('should add new value from inputValue and reset inputValue', function() {
        var end = scope.end;
        scope.inputValue = 10;
        scope.addInputValue();
        expect(scope.end).toBe(end+1);
        expect(scope.circularBuffer[end].value).toBe(10);
        expect(scope.inputValue).toBe("");
    });

/*    it('should add all values from array', function() {
        var values = [1,2,3,4,5,6,7];
        for (var i = 0; i < values.length; i++) {
            scope.add(values[i]);
        }
        //restart controller
        //var scopeState = scope;
        //scope = scope.$new();
        scope.addAll(values);
        expect(scope).toBe(scopeState);
    });*/

    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min+1) + min);
    }

    function printBuffer() {
      var buffer = "Buffer ";
      for(var i = 0; i < scope.size; i++) {
        buffer = buffer + i + ". " + scope.circularBuffer[i].value + " | ";
      }
      alert(buffer + " start " + scope.start + " end " + scope.end);
    }

  });
});
<commit_msg>Removed commented code<commit_after>'use strict';

describe('myApp.view1 module', function() {

  beforeEach(module('myApp.view1'));

  describe('view1 controller', function(){

    var scope;

    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        $controller('View1Ctrl', {$scope: scope});
    }));

    //New tests testing just behaviour

    it('should return empty when new', function() {
      expect(scope.remove()).toBe("");
    });

    it('should return first/oldest added value when not overwriting', function() {
      var quantity = getRandomInt(1, scope.size);
      var memory = new Array(scope.size);
      for(var i = 0; i < quantity; i++) {
        var value = getRandomInt(0, 9);
        scope.add(value);
        memory[i] = value;
      }
      for(var i = 0; i < quantity; i++) {
        expect(scope.remove()).toBe(memory[i]);
      }
    });

    it('should return oldest added value when overwriting', function() {
      var quantity = getRandomInt(1, scope.size) + scope.size;
      var memory = new Array(quantity);
      for(var i = 0; i < quantity; i++) {
        var value = getRandomInt(0, 9);
        scope.add(value);
        memory[i] = value;
      }
      for(var i = 0; i < scope.size; i++) {
        var value = scope.remove();
        expect(value).toBe(memory[quantity-scope.size+i]);
      }
    });

    //Old tests testing state

    it('should initialize circularBuffer array with length=size and position 0', function() {
        expect(scope.circularBuffer.length).toBe(scope.size);
        expect(scope.end).toBe(0);
    });

    it('should add new value to end', function() {
        var end = scope.end;
        scope.add(5);
        expect(scope.end).toBe(end+1);
        expect(scope.circularBuffer[end].value).toBe(5);
    });

    it('should remove value from start, increment start', function() {
        scope.add(5);
        var start = scope.start;
        var temp = scope.remove();
        expect(scope.start).toBe(start+1);
        expect(temp).toBe(5);
        expect(scope.circularBuffer[start].value).toBe("");
    });

    it('should not change start and end if empty, returned value shoud be empty', function() {
        var start = scope.start;
        var end = scope.end;
        var temp = scope.remove();
        expect(scope.start).toBe(start);
        expect(scope.end).toBe(end);
        expect(temp).toBe("");
    });

    it('should go to beginning if end is reached', function() {
        var size = scope.size;
        for (var i = 0; i < size; i++) {
          scope.add(i);
        }
        expect(scope.end).toBe(0);
    });

    it('should overwrite if full', function() {
        var size = scope.size+1;
        var start = scope.start;
        for (var i = 0; i < size; i++) {
          scope.add(i);
        }
        expect(scope.circularBuffer[start].value).toBe(size-1);
    });

    it('should return oldest when overwrote', function() {
        var size = scope.size+2;
        var start = scope.start;
        for (var i = 0; i < size; i++) {
          scope.add(i);
        }
        expect(scope.remove()).toBe(2);
        expect(scope.remove()).toBe(3);
    });

    it('should add new value from inputValue and reset inputValue', function() {
        var end = scope.end;
        scope.inputValue = 10;
        scope.addInputValue();
        expect(scope.end).toBe(end+1);
        expect(scope.circularBuffer[end].value).toBe(10);
        expect(scope.inputValue).toBe("");
    });

/*    it('should add all values from array', function() {
        var values = [1,2,3,4,5,6,7];
        for (var i = 0; i < values.length; i++) {
            scope.add(values[i]);
        }
        //restart controller
        //var scopeState = scope;
        //scope = scope.$new();
        scope.addAll(values);
        expect(scope).toBe(scopeState);
    });*/

    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min+1) + min);
    }

    function printBuffer() {
      var buffer = "Buffer ";
      for(var i = 0; i < scope.size; i++) {
        buffer = buffer + i + ". " + scope.circularBuffer[i].value + " | ";
      }
      alert(buffer + " start " + scope.start + " end " + scope.end);
    }

  });
});
<|endoftext|>


<commit_before>/**
 * Admin
 *
 * for admin pages
 */
var Admin = {};

/**
 * Navigation
 *
 * @return void
 */
Admin.navigation = function() {
    //$("#navnew").accordion({header:'h3'});
	$('#navigation ul a').collapsor();

	// now find cookies and animate the li
	$("#navigation > ul > li").each(function(){
		var li_index = $("#navigation > ul > li").index(this);
		var cookie_name = "cms19_toggle_navigation_ul_li_"+li_index;
		if( $.cookie(cookie_name) ) {
			$("#navigation > ul > li:eq("+li_index+") > ul").animate({height:'toggle', opacity:'toggle'}, 500, 'swing');
		}
	});
}

/**
 * Forms
 *
 * @return void
 */
Admin.form = function() {
	$("form input[type=submit]").not('.filter input[type=submit]').addClass("ui-state-default ui-corner-all").hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	)

	$("input[type=text][rel], select[rel]").not(":hidden").each(function() {
		var sd = $(this).attr('rel');
		$(this).after(""+sd+"");
	});
	$("textarea[rel]").not(":hidden").each(function() {
		var sd = $(this).attr('rel');
        if (sd != '') {
            $(this).after("
"+sd+"");
        }
	});
}

/**
 * Extra stuff
 *
 * rounded corners, striped table rows, etc
 *
 * @return void
 */
Admin.extra = function() {
	$("table tr:nth-child(even)").not('.controller-row').addClass("striped");
	$("div.message").addClass("notice");
	$('#loading p').addClass('ui-corner-bl ui-corner-br');
}

/**
 * Rounded corners
 *
 * @return void
 */
Admin.roundedCorners = function() {
    $("#navigation ul li, #navigation ul li ul, table, .notice, .success, .error, input, select, textarea, div.actions ul li a, div.meta, div.filter").addClass('ui-corner-all');
}

/**
 * Document ready
 *
 * @return void
 */
$(document).ready(function() {
    Admin.navigation();
	Admin.form();
    Admin.extra();
    Admin.roundedCorners();

	$('.tabs').tabs();
    $('a.tooltip').tipsy({gravity: 's'});
    $('textarea').not('.file-content').elastic();
});<commit_msg>do not apply jQuery elastic plugin on Node.body textarea<commit_after>/**
 * Admin
 *
 * for admin pages
 */
var Admin = {};

/**
 * Navigation
 *
 * @return void
 */
Admin.navigation = function() {
    //$("#navnew").accordion({header:'h3'});
	$('#navigation ul a').collapsor();

	// now find cookies and animate the li
	$("#navigation > ul > li").each(function(){
		var li_index = $("#navigation > ul > li").index(this);
		var cookie_name = "cms19_toggle_navigation_ul_li_"+li_index;
		if( $.cookie(cookie_name) ) {
			$("#navigation > ul > li:eq("+li_index+") > ul").animate({height:'toggle', opacity:'toggle'}, 500, 'swing');
		}
	});
}

/**
 * Forms
 *
 * @return void
 */
Admin.form = function() {
	$("form input[type=submit]").not('.filter input[type=submit]').addClass("ui-state-default ui-corner-all").hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	)

	$("input[type=text][rel], select[rel]").not(":hidden").each(function() {
		var sd = $(this).attr('rel');
		$(this).after(""+sd+"");
	});
	$("textarea[rel]").not(":hidden").each(function() {
		var sd = $(this).attr('rel');
        if (sd != '') {
            $(this).after("
"+sd+"");
        }
	});
}

/**
 * Extra stuff
 *
 * rounded corners, striped table rows, etc
 *
 * @return void
 */
Admin.extra = function() {
	$("table tr:nth-child(even)").not('.controller-row').addClass("striped");
	$("div.message").addClass("notice");
	$('#loading p').addClass('ui-corner-bl ui-corner-br');
}

/**
 * Rounded corners
 *
 * @return void
 */
Admin.roundedCorners = function() {
    $("#navigation ul li, #navigation ul li ul, table, .notice, .success, .error, input, select, textarea, div.actions ul li a, div.meta, div.filter").addClass('ui-corner-all');
}

/**
 * Document ready
 *
 * @return void
 */
$(document).ready(function() {
    Admin.navigation();
	Admin.form();
    Admin.extra();
    Admin.roundedCorners();

	$('.tabs').tabs();
    $('a.tooltip').tipsy({gravity: 's'});
    $('textarea').not('.file-content, #NodeBody').elastic();
});<|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 urlParse = require('url').parse
const DataFile = require('./dataFile')
const Filtering = require('./filtering')
const session = require('electron').session

let httpsEverywhereInitialized = false
// Map of ruleset ID to ruleset content
var db = null
// Map of hostname pattern to ruleset ID
var targets = null
// Counter for detecting infinite redirect loops
var redirectCounter = {}
// Blacklist of canonicalized hosts (host+pathname) that lead to redirect loops
var redirectBlacklist = []

module.exports.resourceName = 'httpsEverywhere'

function loadRulesets (data) {
  var parsedData = JSON.parse(data)
  targets = parsedData.targets
  db = parsedData.rulesetStrings
}

/**
 * Rewrites a URL from HTTP to HTTPS if an HTTPS Everywhere rule is applicable.
 * @param {string} url The URL to rewrite
 * @return {string|undefined} the rewritten URL, or undefined if no rewrite
 */
function getRewrittenUrl (url) {
  // Get the set of ruleset IDs applicable to this host
  var rulesetIds = getHostnamePatterns(url).reduce((prev, hostname) => {
    var target = targets[hostname]
    return target ? prev.concat(target) : prev
  }, [])

  for (var i = 0; i < rulesetIds.length; ++i) {
    // Try applying each ruleset
    let result = applyRuleset(url, db[rulesetIds[i]])
    if (result) {
      // Redirect to the first rewritten URL
      return result
    }
  }
  return undefined
}

/**
 * Gets applicable hostname patterns for a given URL. Ex: for x.y.google.com,
 * rulesets matching x.y.google.com, *.y.google.com, and *.google.com are
 * applicable.
 * @param {string} url The url to get hostname patterns for
 * @return {Array.<string>}
 */
function getHostnamePatterns (url) {
  var host = urlParse(url).hostname
  var segmented = host.split('.')
  var hostPatterns = [host]

  // Since targets can contain a single wildcard, replace each label of the
  // hostname with "*" in turn.
  segmented.forEach((label, index) => {
    // copy the original array
    var tmp = segmented.slice()
    if (label.length === 0) {
      console.log('got host with 0-length label', url)
    } else {
      tmp[index] = '*'
      hostPatterns.push(tmp.join('*'))
    }
  })
  // Now eat away from the left with * so that for x.y.z.google.com we also
  // check *.z.google.com and *.google.com.
  for (var i = 2; i <= segmented.length - 2; ++i) {
    hostPatterns.push('*.' + segmented.slice(i, segmented.length).join('.'))
  }
  return hostPatterns
}

/**
 * Applies a applicable rewrite ruleset to a URL
 * @param {string} url original URL
 * @param {Object} applicableRule applicable ruleset
 * @return {string?} the rewritten URL, or null if no rewrite applied
 */
function applyRuleset (url, applicableRule) {
  var i, ruleset, exclusion, rule, fromPattern, newUrl, exclusionPattern
  ruleset = applicableRule.ruleset
  // If the rule is default_off or has a specified platform, ignore it.
  if (ruleset.$.default_off || ruleset.$.platform) {
    return null
  }
  exclusion = ruleset.exclusion
  rule = ruleset.rule
  // If covered by an exclusion, callback the original URL without trying any
  // more rulesets.
  if (exclusion) {
    for (i = 0; i < exclusion.length; ++i) {
      exclusionPattern = new RegExp(exclusion[i].$.pattern)
      if (exclusionPattern.test(url)) {
        return url
      }
    }
  }
  // Find the first rule that triggers a substitution
  for (i = 0; i < rule.length; ++i) {
    fromPattern = new RegExp(rule[i].$.from)
    newUrl = url.replace(fromPattern, rule[i].$.to)
    if (newUrl !== url) {
      return newUrl
    }
  }
  return null
}

/**
 * Called when the HTTPS EVerywhere data file
 * is downloaded and ready.
 */
function startHttpsEverywhere () {
  httpsEverywhereInitialized = true
  Filtering.registerBeforeRequestFilteringCB((onBeforeHTTPRequest))
}

function onBeforeHTTPRequest (details) {
  let result = {}
  if (!httpsEverywhereInitialized ||
      !Filtering.isResourceEnabled(module.exports.resourceName)) {
    return result
  }
  // Ignore URLs that are not HTTP
  if (urlParse(details.url).protocol !== 'http:') {
    return result
  }

  if (redirectBlacklist.includes(canonicalizeUrl(details.url))) {
    // Don't try to rewrite this request, it'll probably just redirect again.
    console.log('https everywhere ignoring blacklisted url', details.url)
  } else {
    result.redirectURL = getRewrittenUrl(details.url)
  }
  return result
}

function onBeforeRedirect (details) {
  if (!httpsEverywhereInitialized ||
      !Filtering.isResourceEnabled(module.exports.resourceName)) {
    return
  }

  var canonicalUrl = canonicalizeUrl(details.url)
  if (details.id in redirectCounter) {
    canonicalUrl = canonicalizeUrl(details.url)
    redirectCounter[details.id] += 1
    if (redirectCounter[details.id] > 5 && !redirectBlacklist.includes(canonicalUrl)) {
      // Blacklist this host
      console.log('blacklisting url', canonicalUrl)
      redirectBlacklist.push(canonicalUrl)
    }
  } else {
    redirectCounter[details.id] = 1
  }
}

/**
 * Canonicalizes a URL to host + pathname.
 * @param {string} url
 * @return {string}
 */
function canonicalizeUrl (url) {
  var parsed = urlParse(url)
  return [parsed.host, parsed.pathname].join('')
}

/**
 * Register for notifications for webRequest notifications for
 * a particular session.
 * @param {object} The session to add webRequest filtering on
 */
function registerForSession (session) {
  // Try to catch infinite redirect loops on URLs we've redirected to HTTPS
  // TODO: Add this to Filtering.js
  session.webRequest.onBeforeRedirect({
    urls: ['https://*/*']
  }, onBeforeRedirect)
}

/**
 * Loads HTTPS Everywhere
 */
module.exports.init = () => {
  DataFile.init(module.exports.resourceName, startHttpsEverywhere, loadRulesets)
  registerForSession(session.fromPartition(''))
  registerForSession(session.fromPartition('private-1'))
  registerForSession(session.fromPartition('main-1'))
}

<commit_msg>Return null redirectURL for HTTPS Everywhere excluded URLs<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 urlParse = require('url').parse
const DataFile = require('./dataFile')
const Filtering = require('./filtering')
const session = require('electron').session

let httpsEverywhereInitialized = false
// Map of ruleset ID to ruleset content
var db = null
// Map of hostname pattern to ruleset ID
var targets = null
// Counter for detecting infinite redirect loops
var redirectCounter = {}
// Blacklist of canonicalized hosts (host+pathname) that lead to redirect loops
var redirectBlacklist = []

module.exports.resourceName = 'httpsEverywhere'

function loadRulesets (data) {
  var parsedData = JSON.parse(data)
  targets = parsedData.targets
  db = parsedData.rulesetStrings
}

/**
 * Rewrites a URL from HTTP to HTTPS if an HTTPS Everywhere rule is applicable.
 * @param {string} url The URL to rewrite
 * @return {string|undefined} the rewritten URL, or undefined if no rewrite
 */
function getRewrittenUrl (url) {
  // Get the set of ruleset IDs applicable to this host
  var rulesetIds = getHostnamePatterns(url).reduce((prev, hostname) => {
    var target = targets[hostname]
    return target ? prev.concat(target) : prev
  }, [])

  for (var i = 0; i < rulesetIds.length; ++i) {
    // Try applying each ruleset
    let result = applyRuleset(url, db[rulesetIds[i]])
    if (result) {
      // Redirect to the first rewritten URL
      return result
    }
  }
  return undefined
}

/**
 * Gets applicable hostname patterns for a given URL. Ex: for x.y.google.com,
 * rulesets matching x.y.google.com, *.y.google.com, and *.google.com are
 * applicable.
 * @param {string} url The url to get hostname patterns for
 * @return {Array.<string>}
 */
function getHostnamePatterns (url) {
  var host = urlParse(url).hostname
  var segmented = host.split('.')
  var hostPatterns = [host]

  // Since targets can contain a single wildcard, replace each label of the
  // hostname with "*" in turn.
  segmented.forEach((label, index) => {
    // copy the original array
    var tmp = segmented.slice()
    if (label.length === 0) {
      console.log('got host with 0-length label', url)
    } else {
      tmp[index] = '*'
      hostPatterns.push(tmp.join('*'))
    }
  })
  // Now eat away from the left with * so that for x.y.z.google.com we also
  // check *.z.google.com and *.google.com.
  for (var i = 2; i <= segmented.length - 2; ++i) {
    hostPatterns.push('*.' + segmented.slice(i, segmented.length).join('.'))
  }
  return hostPatterns
}

/**
 * Applies a applicable rewrite ruleset to a URL
 * @param {string} url original URL
 * @param {Object} applicableRule applicable ruleset
 * @return {string?} the rewritten URL, or null if no rewrite applied
 */
function applyRuleset (url, applicableRule) {
  var i, ruleset, exclusion, rule, fromPattern, newUrl, exclusionPattern
  ruleset = applicableRule.ruleset
  // If the rule is default_off or has a specified platform, ignore it.
  if (ruleset.$.default_off || ruleset.$.platform) {
    return null
  }
  exclusion = ruleset.exclusion
  rule = ruleset.rule
  // If covered by an exclusion, callback the original URL without trying any
  // more rulesets.
  if (exclusion) {
    for (i = 0; i < exclusion.length; ++i) {
      exclusionPattern = new RegExp(exclusion[i].$.pattern)
      if (exclusionPattern.test(url)) {
        return null
      }
    }
  }
  // Find the first rule that triggers a substitution
  for (i = 0; i < rule.length; ++i) {
    fromPattern = new RegExp(rule[i].$.from)
    newUrl = url.replace(fromPattern, rule[i].$.to)
    if (newUrl !== url) {
      return newUrl
    }
  }
  return null
}

/**
 * Called when the HTTPS EVerywhere data file
 * is downloaded and ready.
 */
function startHttpsEverywhere () {
  httpsEverywhereInitialized = true
  Filtering.registerBeforeRequestFilteringCB((onBeforeHTTPRequest))
}

function onBeforeHTTPRequest (details) {
  let result = {}
  if (!httpsEverywhereInitialized ||
      !Filtering.isResourceEnabled(module.exports.resourceName)) {
    return result
  }
  // Ignore URLs that are not HTTP
  if (urlParse(details.url).protocol !== 'http:') {
    return result
  }

  if (redirectBlacklist.includes(canonicalizeUrl(details.url))) {
    // Don't try to rewrite this request, it'll probably just redirect again.
    console.log('https everywhere ignoring blacklisted url', details.url)
  } else {
    result.redirectURL = getRewrittenUrl(details.url)
  }
  return result
}

function onBeforeRedirect (details) {
  if (!httpsEverywhereInitialized ||
      !Filtering.isResourceEnabled(module.exports.resourceName)) {
    return
  }

  var canonicalUrl = canonicalizeUrl(details.url)
  if (details.id in redirectCounter) {
    canonicalUrl = canonicalizeUrl(details.url)
    redirectCounter[details.id] += 1
    if (redirectCounter[details.id] > 5 && !redirectBlacklist.includes(canonicalUrl)) {
      // Blacklist this host
      console.log('blacklisting url', canonicalUrl)
      redirectBlacklist.push(canonicalUrl)
    }
  } else {
    redirectCounter[details.id] = 1
  }
}

/**
 * Canonicalizes a URL to host + pathname.
 * @param {string} url
 * @return {string}
 */
function canonicalizeUrl (url) {
  var parsed = urlParse(url)
  return [parsed.host, parsed.pathname].join('')
}

/**
 * Register for notifications for webRequest notifications for
 * a particular session.
 * @param {object} The session to add webRequest filtering on
 */
function registerForSession (session) {
  // Try to catch infinite redirect loops on URLs we've redirected to HTTPS
  // TODO: Add this to Filtering.js
  session.webRequest.onBeforeRedirect({
    urls: ['https://*/*']
  }, onBeforeRedirect)
}

/**
 * Loads HTTPS Everywhere
 */
module.exports.init = () => {
  DataFile.init(module.exports.resourceName, startHttpsEverywhere, loadRulesets)
  registerForSession(session.fromPartition(''))
  registerForSession(session.fromPartition('private-1'))
  registerForSession(session.fromPartition('main-1'))
}

<|endoftext|>


<commit_before>
      // PUT YOUR UNIQUE ID HERE
//  (from the devadmin page, the one with '-edgware' appended)
var dappId = 'pubcrawl-edgware';

// PUT YOUR CALLBACK URL HERE
var callbackUrl = 'http://localhost:8080';

var web3, walletBar, pubCrawl;
// the callback must EXACTLY match the string configured in the devadmin web UI.
// e.g. be careful of trailing slashes

// PUT YOUR CONTRACT ADDRESS HERE
var contractAddress = '0x5155b763e961a7bb2621eece8393d225ab208ff7';

window.onload = function() {
  walletBar = new WalletBar({
    dappNamespace: dappId,
    authServiceCallbackUrl: callbackUrl,
    containerName:'#signInId'
  });

  web3 = new Web3();
  web3.setProvider(walletBar.getHook('edgware'));
  pubCrawl = web3.eth.contract(PubCrawl.all_networks.default.abi).at(contractAddress);

  loadContracts();
}

function loadContracts() {
	var result = govContracts.getNumberContracts.call();
	var nbContracts = result.c[0];
	var contracts = [];
	for(var i = 0; i < nbContracts ; i++) {
		var result = pubCrawl.getContractName.call(i);
		var result = pubCrawl.getContractHash.call(i);
		console.log(result);
	}
}

function createGovContract() {
	console.log('creating gov contract!');
	walletBar.createSecureSigner();
	var currentAccount = walletBar.getCurrentAccount();

	  pubCrawl.buildContract.sendTransaction('helloworld','helloworld', { gas: 1e6, from: currentAccount },function(err,result){
	  	console.log(result);
	  });
}

<commit_msg>clean contract names<commit_after>
      // PUT YOUR UNIQUE ID HERE
//  (from the devadmin page, the one with '-edgware' appended)
var dappId = 'pubcrawl-edgware';

// PUT YOUR CALLBACK URL HERE
var callbackUrl = 'http://localhost:8080';

var web3, walletBar, pubCrawl;
// the callback must EXACTLY match the string configured in the devadmin web UI.
// e.g. be careful of trailing slashes

// PUT YOUR CONTRACT ADDRESS HERE
var contractAddress = '0x5155b763e961a7bb2621eece8393d225ab208ff7';

window.onload = function() {
  walletBar = new WalletBar({
    dappNamespace: dappId,
    authServiceCallbackUrl: callbackUrl,
    containerName:'#signInId'
  });

  web3 = new Web3();
  web3.setProvider(walletBar.getHook('edgware'));
  pubCrawl = web3.eth.contract(Pubcrawl.all_networks.default.abi).at(contractAddress);

  loadContracts();
}

function loadContracts() {
	var result = pubCrawl.getNumberContracts.call();
	var nbContracts = result.c[0];
	var contracts = [];
	for(var i = 0; i < nbContracts ; i++) {
		var result = pubCrawl.getContractName.call(i);
		var result = pubCrawl.getContractHash.call(i);
		console.log(result);
	}
}

function createGovContract() {
	console.log('creating gov contract!');
	walletBar.createSecureSigner();
	var currentAccount = walletBar.getCurrentAccount();

	  pubCrawl.buildContract.sendTransaction('helloworld','helloworld', { gas: 1e6, from: currentAccount },function(err,result){
	  	console.log(result);
	  });
}

<|endoftext|>


<commit_before>// import {} from "../stylesheets/app.css";
import 'react-notifications/lib/notifications.css';
import React from 'react';
import ReactDOM from 'react-dom';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import FlatButton from 'material-ui/FlatButton';
import ConferenceDetail from './ConferenceDetail';
import FormInput from './FormInput';
import Notification from './Notification';
import Instruction from './Instruction';
import Participants from './Participants';
import Avatar from 'material-ui/Avatar';
import AppBar from 'material-ui/AppBar';
import {List, ListItem} from 'material-ui/List';
import EventEmitter from 'event-emitter';
import Paper from 'material-ui/Paper';
import math from 'mathjs';
import injectTapEventPlugin from 'react-tap-event-plugin';

const styles = {
  div:{
    display: 'flex',
    justifyContent: 'space-between',
    flexDirection: 'row wrap',
    width: '100%'
  }
};

// Some settings to connect to Ethereum.
const Pudding = require("ether-pudding");
const web3 = new Web3();
Pudding.setWeb3(web3);
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
Conference.load(Pudding);
const contract = Conference.deployed();
const eventEmitter = EventEmitter()

// Functions to interact with contract
function getDetail(callback){
  Promise.all(['name', 'deposit', 'payout', 'balance', 'registered', 'attended'].map(attributeName => {
    return contract[attributeName].call();
  })).then(values => {
    var detail = {
      'name': values[0],
      'deposit': values[1],
      'payout': values[2],
      'balance': values[3],
      'registered': values[4],
      'attended': values[5],
      'contractBalance': web3.fromWei(web3.eth.getBalance(contract.address), "ether").toNumber()
    }

    if(detail.registered.toNumber() > 0 && detail.attended.toNumber() > 0 && detail.payout.toNumber() > 0){
      detail.canPayback = true
    }
    if(detail.registered.toNumber() > 0 && detail.attended.toNumber() > 0 && detail.payout.toNumber() == 0){
      detail.canReset = true
    }
    if(!detail.canReset){
      detail.canRegister = true
    }

    callback(detail);
  })
}

function getParticipants(callback){
  contract.registered.call().then(value => {
    let participantsArray = []
    for (var i = 1; i <= value.toNumber(); i++) {
      participantsArray.push(i);
    }
    Promise.all(participantsArray.map(index => {
      return contract.participantsIndex.call(index).then(address => {
        return contract.participants.call(address);
      })
    })).then(function(participants){
      return participants.map(participant => {
        var balance =  web3.fromWei(web3.eth.getBalance(participant[1]), "ether").toNumber();
        var object =  {
          name: participant[0],
          address: participant[1],
          attended: participant[2],
          balance: balance
        }
        console.log('participant', object);
        return object
      })
    }).then(participant => { if(participant) callback(participant); })
  })
}
var gas = 1000000;
window.gas = gas
window.eventEmitter = eventEmitter;
function action(name, address, argument) {
  var options = {from:address, gas:window.gas}
  eventEmitter.emit('notification', {status:'info', message:'Requested'});
  if (name == "register") {
    options.value = Math.pow(10,18)
  }

  console.log('name', name, 'address', address, 'argument', argument)
  contract[name](argument, options).then(function() {
    getDetail(function(model){
      eventEmitter.emit('change', model);
      eventEmitter.emit('notification', {status:'success', message:'Successfully Updated'});
    });
  }).catch(function(e) {
    eventEmitter.emit('notification', {status:'error', message:'Error has occored'});
  });
}

function watchEvent(){
  var event = contract.allEvents({fromBlock: 0, toBlock: 'latest'}).watch(function(error, result){
    if (error) {
      console.log("Error: " + error);
    } else {
      console.log('watchEvent result', result);
    }
  });
}

function getAccounts(callback){
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      eventEmitter.emit('instruction')
      return;
    }
    if (accs.length == 0) {
      var message = "Couldn't get any accounts! Make sure your Ethereum client is configured correctly.";
      eventEmitter.emit('notification', {status:'error', message:message});
      return;
    }
    callback(accs);
  })
}

const App = (props) => (

    <MuiThemeProvider muiTheme={getMuiTheme()}>

        <AppBar titleStyle={{textAlign:'center', fontSize:'xx-large', fontFamily:'Lobster'}} style={{backgroundColor:"#607D8B"}}
          title={
            Block Party - NO BLOCK NO PARTY -
          }
          iconElementLeft={<Avatar src="/images/nightclub-white.png" size="50" backgroundColor="white" />}
          iconElementRight={<FlatButton label="About" onClick={ () => {eventEmitter.emit('instruction')}} />}
        />
        <Instruction eventEmitter={eventEmitter} />
        <Notification eventEmitter={eventEmitter} />

          <ConferenceDetail eventEmitter={eventEmitter} getDetail={getDetail} web3={web3} math={math} contract={contract} web3={web3} />
          <Participants eventEmitter={eventEmitter} getDetail={getDetail} getParticipants={getParticipants} web3={web3} math={math} />

        <FormInput eventEmitter={eventEmitter} getAccounts = {getAccounts} getDetail = {getDetail} action = {action} />

    </MuiThemeProvider>

);

window.web3 = web3;
window.onload = function() {
  console.log("LOAD")
  injectTapEventPlugin();
  ReactDOM.render(
    <App
      getAccounts = {getAccounts}
      getDetail = {getDetail}
      eventEmitter = {eventEmitter}
      action = {action}
      getParticipants = {getParticipants}
      web3 = {web3}
      math = {math}
      contract={contract}
    />,
    document.getElementById('app')
  );
}
<commit_msg>Conference.setProvider instead of Conference.load<commit_after>// import {} from "../stylesheets/app.css";
import 'react-notifications/lib/notifications.css';
import React from 'react';
import ReactDOM from 'react-dom';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import FlatButton from 'material-ui/FlatButton';
import ConferenceDetail from './ConferenceDetail';
import FormInput from './FormInput';
import Notification from './Notification';
import Instruction from './Instruction';
import Participants from './Participants';
import Avatar from 'material-ui/Avatar';
import AppBar from 'material-ui/AppBar';
import {List, ListItem} from 'material-ui/List';
import EventEmitter from 'event-emitter';
import Paper from 'material-ui/Paper';
import math from 'mathjs';
import injectTapEventPlugin from 'react-tap-event-plugin';

const styles = {
  div:{
    display: 'flex',
    justifyContent: 'space-between',
    flexDirection: 'row wrap',
    width: '100%'
  }
};

const web3 = new Web3;
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
web3.setProvider(provider);
Conference.setProvider(provider);
const contract = Conference.deployed();
const eventEmitter = EventEmitter()

// Functions to interact with contract
function getDetail(callback){
  Promise.all(['name', 'deposit', 'payout', 'balance', 'registered', 'attended'].map(attributeName => {
    return contract[attributeName].call();
  })).then(values => {
    var detail = {
      'name': values[0],
      'deposit': values[1],
      'payout': values[2],
      'balance': values[3],
      'registered': values[4],
      'attended': values[5],
      'contractBalance': web3.fromWei(web3.eth.getBalance(contract.address), "ether").toNumber()
    }

    if(detail.registered.toNumber() > 0 && detail.attended.toNumber() > 0 && detail.payout.toNumber() > 0){
      detail.canPayback = true
    }
    if(detail.registered.toNumber() > 0 && detail.attended.toNumber() > 0 && detail.payout.toNumber() == 0){
      detail.canReset = true
    }
    if(!detail.canReset){
      detail.canRegister = true
    }

    callback(detail);
  })
}

function getParticipants(callback){
  contract.registered.call().then(value => {
    let participantsArray = []
    for (var i = 1; i <= value.toNumber(); i++) {
      participantsArray.push(i);
    }
    Promise.all(participantsArray.map(index => {
      return contract.participantsIndex.call(index).then(address => {
        return contract.participants.call(address);
      })
    })).then(function(participants){
      return participants.map(participant => {
        var balance =  web3.fromWei(web3.eth.getBalance(participant[1]), "ether").toNumber();
        var object =  {
          name: participant[0],
          address: participant[1],
          attended: participant[2],
          balance: balance
        }
        console.log('participant', object);
        return object
      })
    }).then(participant => { if(participant) callback(participant); })
  })
}
var gas = 1000000;
window.gas = gas
window.eventEmitter = eventEmitter;
function action(name, address, argument) {
  var options = {from:address, gas:window.gas}
  eventEmitter.emit('notification', {status:'info', message:'Requested'});
  if (name == "register") {
    options.value = Math.pow(10,18)
  }

  console.log('name', name, 'address', address, 'argument', argument)
  contract[name](argument, options).then(function() {
    getDetail(function(model){
      eventEmitter.emit('change', model);
      eventEmitter.emit('notification', {status:'success', message:'Successfully Updated'});
    });
  }).catch(function(e) {
    eventEmitter.emit('notification', {status:'error', message:'Error has occored'});
  });
}

function watchEvent(){
  var event = contract.allEvents({fromBlock: 0, toBlock: 'latest'}).watch(function(error, result){
    if (error) {
      console.log("Error: " + error);
    } else {
      console.log('watchEvent result', result);
    }
  });
}

function getAccounts(callback){
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      eventEmitter.emit('instruction')
      return;
    }
    if (accs.length == 0) {
      var message = "Couldn't get any accounts! Make sure your Ethereum client is configured correctly.";
      eventEmitter.emit('notification', {status:'error', message:message});
      return;
    }
    callback(accs);
  })
}

const App = (props) => (

    <MuiThemeProvider muiTheme={getMuiTheme()}>

        <AppBar titleStyle={{textAlign:'center', fontSize:'xx-large', fontFamily:'Lobster'}} style={{backgroundColor:"#607D8B"}}
          title={
            Block Party - NO BLOCK NO PARTY -
          }
          iconElementLeft={<Avatar src="/images/nightclub-white.png" size="50" backgroundColor="white" />}
          iconElementRight={<FlatButton label="About" onClick={ () => {eventEmitter.emit('instruction')}} />}
        />
        <Instruction eventEmitter={eventEmitter} />
        <Notification eventEmitter={eventEmitter} />

          <ConferenceDetail eventEmitter={eventEmitter} getDetail={getDetail} web3={web3} math={math} contract={contract} web3={web3} />
          <Participants eventEmitter={eventEmitter} getDetail={getDetail} getParticipants={getParticipants} web3={web3} math={math} />

        <FormInput eventEmitter={eventEmitter} getAccounts = {getAccounts} getDetail = {getDetail} action = {action} />

    </MuiThemeProvider>

);

window.web3 = web3;
window.onload = function() {
  console.log("LOAD")
  injectTapEventPlugin();
  ReactDOM.render(
    <App
      getAccounts = {getAccounts}
      getDetail = {getDetail}
      eventEmitter = {eventEmitter}
      action = {action}
      getParticipants = {getParticipants}
      web3 = {web3}
      math = {math}
      contract={contract}
    />,
    document.getElementById('app')
  );
}
<|endoftext|>


<commit_before>var accounts;
var account;

window.onload = function() {
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];
  });
};

function init() {
    var shipia = Shipia.deployed();
    shipia.reset({from:web3.eth.defaultAccount}).then(function() {
        shipia.setOwner(web3.eth.defaultAccount, {from:web3.eth.defaultAccount}).then(function() {
            shipia.setRole("0xf280d7eAE02D401CC319a73EFF9d1328AAD60A3D".toLowerCase(), 1, {from:web3.eth.defaultAccount});
            shipia.setRole("0x0aA7511BA4FE893a3d2D68F295eB052543Df9E9F".toLowerCase(), 2, {from:web3.eth.defaultAccount});
            shipia.setRole("0x37c6194E43a80F35B7B0A15B6635F9367F00073e".toLowerCase(), 3, {from:web3.eth.defaultAccount});
            console.log('setting roles');
        });
    });

}

function createSale() {
  var shipia = Shipia.deployed();
  var buyer = $("#buyer").val().toLowerCase();
  var seller = $("#seller").val().toLowerCase();
  var price = $("#price").val();
  var description = $("#cargo").val();

  console.log("createSale:", shipia, buyer, seller, price, description);
  shipia.initSale(buyer, seller, price, description, {from:web3.eth.defaultAccount}).then(function() {
      alert('sale created!');
  });
}
<commit_msg>get role<commit_after>var accounts;
var account;
var currentRole;

window.onload = function() {
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];

    Shipia.deployed().getRole(account).then(function(role) {
       currentRole = role.toNumber();
    });
  });
};

function init() {
    var shipia = Shipia.deployed();
    shipia.reset({from:web3.eth.defaultAccount}).then(function() {
        shipia.setOwner(web3.eth.defaultAccount, {from:web3.eth.defaultAccount}).then(function() {
            shipia.setRole("0xf280d7eAE02D401CC319a73EFF9d1328AAD60A3D".toLowerCase(), 1, {from:web3.eth.defaultAccount});
            shipia.setRole("0x0aA7511BA4FE893a3d2D68F295eB052543Df9E9F".toLowerCase(), 2, {from:web3.eth.defaultAccount});
            shipia.setRole("0x37c6194E43a80F35B7B0A15B6635F9367F00073e".toLowerCase(), 3, {from:web3.eth.defaultAccount});
            console.log('setting roles');
        });
    });

}

function createSale() {
  var shipia = Shipia.deployed();
  var buyer = $("#buyer").val().toLowerCase();
  var seller = $("#seller").val().toLowerCase();
  var price = $("#price").val();
  var description = $("#cargo").val();

  console.log("createSale:", shipia, buyer, seller, price, description);
  shipia.initSale(buyer, seller, price, description, {from:web3.eth.defaultAccount}).then(function() {
      alert('sale created!');
  });
}
<|endoftext|>