<commit_before>// vi: sts=2 sw=2 et
//
const dump = (v, opts = {values: true}) => {
  let segments = [];
  let indentStr = (i) => Array(i * 2 + 1).join(" ");
  let makeSegments = (v, objects=[], indent=1) => {
    if (indent > 10) {
      segments.push(" ... (indent limit)");
      return;
    }

    if (segments.length > 1000) {
      segments.push(" ... (segment limit)");
      return
    }

    if (v === null || v === undefined) {
      segments.push(String(v));
      return
    }

    let asString;
    try {
      asString = String(v);
    } catch (e) {
      asString = "<???>";
    }

    let isArguments = asString === "[object Arguments]";
    let isUnknown = false;
    let isArray = false;
    let isObject = false;
    try {
      isObject = (!isArguments) && (v.constructor === Object);
      isArray = v.constructor === Array;
    } catch (e) {
      isUnknown = true
    }

    let keys = null;
    try {
      if (opts.all) {
        keys = Object.getOwnPropertyNames(v);
      } else {
        keys = Object.keys(v);
      }
    } catch (e) {
      /* noop */
    }

    let hasKeys = (keys !== null);

    if (isArguments) {
      v = Array.prototype.slice.call(v);
    }

    if (isArray || isArguments || isObject || hasKeys) {
      if (objects.indexOf(v) >= 0) {
        segments.push("(recursion)");
        return
      }
    }

    let nextObjects = objects.concat([v]);

    if (isArray || isArguments) {
      segments.push("[");
      v.forEach((x,i) => {
        if (i > 0) {
          segments.push(", ");
        }
        makeSegments(x, nextObjects, indent+1)
      })
      segments.push("]");
    } else if (isObject || hasKeys) {
      segments.push("{ <", asString, "> ");
      let keys;
      if (opts.all) {
        keys = Object.getOwnPropertyNames(v);
      } else {
        keys = Object.keys(v);
      }
      keys.forEach((k,i) => {
        if (i > 0) {
          segments.push(", ")
        }
        segments.push(k.toString());
        segments.push(": ");
        if (opts.values) {
          let props = Object.getOwnPropertyDescriptor(v, k);
          if ("value" in props) {
            makeSegments(v[k], nextObjects, indent+1);
          } else {
            segments.push("(property)");
          }
        } else {
          segments.push("(", typeof v[k], ")");
        }
      })
      segments.push("}");
    } else {
      segments.push(asString, " (", typeof v, ")");
    }
  }
  makeSegments(v);
  return segments.join("");
}

if (window["ARGV"] && ARGV[0] === "test") {
  log(dump([1,2,3]));
  log(dump({a:{aa:{aaa:1,aab:2}},b:3}));

  const Obj = function () {
      this.x = 1;
      this.y = null;
  }
  const o = new Obj();
  log(dump(o, {all: true}));
  o.o = o;
  o.x = undefined;
  log(dump(o, {all: false}));
  log(dump(null));

  const prop = {
    get x() {
        return 1;
    },
    y: 1
  }
  log(dump(prop))
}
<commit_msg>Fix dump.js for gjs-1.48<commit_after>// vi: sts=2 sw=2 et
//
const dump = (v, opts = {values: true}) => {
  let segments = [];
  let indentStr = (i) => Array(i * 2 + 1).join(" ");
  let makeSegments = (v, objects=[], indent=1) => {
    if (indent > 10) {
      segments.push(" ... (indent limit)");
      return;
    }

    if (segments.length > 1000) {
      segments.push(" ... (segment limit)");
      return
    }

    if (v === null || v === undefined) {
      segments.push(String(v));
      return
    }

    let asString;
    try {
      asString = String(v);
    } catch (e) {
      asString = "<???>";
    }

    let isArguments = asString === "[object Arguments]";
    let isUnknown = false;
    let isArray = false;
    let isObject = false;
    try {
      isObject = (!isArguments) && (v.constructor === Object);
      isArray = v.constructor === Array;
    } catch (e) {
      isUnknown = true
    }

    let keys = null;
    try {
      if (opts.all) {
        keys = Object.getOwnPropertyNames(v);
      } else {
        keys = Object.keys(v);
      }
    } catch (e) {
      /* noop */
    }

    let hasKeys = (keys !== null);

    if (isArguments) {
      v = Array.prototype.slice.call(v);
    }

    let type = typeof v;
    let isPrimitive =
      (v == null) || ((type != "object") && (type != "function"));

    if (isArray || isArguments || isObject || hasKeys) {
      if (objects.indexOf(v) >= 0) {
        segments.push("(recursion)");
        return
      }
    }

    let nextObjects = objects.concat([v]);

    if (isArray || isArguments) {
      segments.push("[");
      v.forEach((x,i) => {
        if (i > 0) {
          segments.push(", ");
        }
        makeSegments(x, nextObjects, indent+1)
      })
      segments.push("]");
    } else if (!isPrimitive && (isObject || hasKeys)) {
      segments.push("{ <", asString, "> ");
      let keys;
      if (opts.all) {
        keys = Object.getOwnPropertyNames(v);
      } else {
        keys = Object.keys(v);
      }
      keys.forEach((k,i) => {
        if (i > 0) {
          segments.push(", ")
        }
        segments.push(k.toString());
        segments.push(": ");
        if (opts.values) {
          let props = Object.getOwnPropertyDescriptor(v, k);
          if ("value" in props) {
            makeSegments(v[k], nextObjects, indent+1);
          } else {
            segments.push("(property)");
          }
        } else {
          segments.push("(", typeof v[k], ")");
        }
      })
      segments.push("}");
    } else {
      segments.push(asString, " (", typeof v, ")");
    }
  }
  makeSegments(v);
  return segments.join("");
}

if (window["ARGV"] && ARGV[0] === "test") {
  log(dump("string"));
  log(dump(true));
  log(dump([1,2,3]));
  log(dump({a:{aa:{aaa:1,aab:2}},b:3}));

  const Obj = function () {
      this.x = 1;
      this.y = null;
  }
  const o = new Obj();
  log(dump(o, {all: true}));
  o.o = o;
  o.x = undefined;
  log(dump(o, {all: false}));
  log(dump(null));

  const prop = {
    get x() {
        return 1;
    },
    y: 1
  }
  log(dump(prop))
}
<|endoftext|>


<commit_before>import React, {PropTypes, Component} from 'react';
import {View} from 'react-native';

export default class Form extends Component {
  _listeners = [];

  static PropTypes = {
    onSuccess: PropTypes.func,
    onFail: PropTypes.func,
    submitButton: PropTypes.element.isRequired
  }

  static childContextTypes = {
    addFormListener: PropTypes.func,
    removeFormListener: PropTypes.func
  }

  getChildContext() {
    return {
      addFormListener: this.addFormListener.bind(this),
      removeFormListener: this.removeFormListener.bind(this)
    }
  }

  addFormListener(ln) {
    this._listeners.push(ln);
  }

  removeFormListener(ln) {
    this._listeners = this._listeners.filter(l => l  !== ln);
  }

  onSubmit() {
    const defaultFn = () => {};
    const {onFail = defaultFn, onSuccess = defaultFn} = this.props;

    const stop = this._listeners.reduce((stop, _listener) => {
      return _listener() || stop;
    }, false);
    if (stop) {
      return onFail();
    };
    onSuccess();
  }

  render() {
    const {submitButton, children, style} = this.props;

    return (
        <View style={style}>
          {children}
          {submitButton(this.onSubmit.bind(this))}
        </View>
    )
  }
}
<commit_msg>Add prop to disable submit<commit_after>import React, {PropTypes, Component} from 'react';
import {View} from 'react-native';

export default class Form extends Component {
  _listeners = [];

  static PropTypes = {
    onSuccess: PropTypes.func,
    onFail: PropTypes.func,
    submitButton: PropTypes.element.isRequired
  }

  static childContextTypes = {
    addFormListener: PropTypes.func,
    removeFormListener: PropTypes.func
  }

  getChildContext() {
    return {
      addFormListener: this.addFormListener.bind(this),
      removeFormListener: this.removeFormListener.bind(this)
    }
  }

  addFormListener(ln) {
    this._listeners.push(ln);
  }

  removeFormListener(ln) {
    this._listeners = this._listeners.filter(l => l  !== ln);
  }

  onSubmit() {
    const defaultFn = () => {};
    const {onFail = defaultFn, onSuccess = defaultFn} = this.props;

    const stop = this._listeners.reduce((stop, _listener) => {
      return _listener() || stop;
    }, false);
    if (stop) {
      return onFail();
    };
    onSuccess();
  }

  render() {
    const {submitButton, children, style, disableSubmit} = this.props;

    return (
        <View style={style}>
          {children}
          {submitButton(this.onSubmit.bind(this), disableSubmit)}
        </View>
    )
  }
}
<|endoftext|>


<commit_before>var player, enemies = [], attacking=[], currentlevel, interval;
function Entity(sprite,ai){
  this.sprite = sprite;
  this.ai = ai;
  this.direction = 1;
  this.dead = false;
  this.setDirection = function(d){
    if(d === this.direction)
      return;
    this.sprite.setX(this.sprite.getX()-0.65*d*this.sprite.getWidth());
    this.sprite.setScaleX(d);
    this.direction = d;
  };
  this.die = function(){
    this.sprite.setAnimation('death');
    this.dead = true;
    var self = this;
    this.sprite.afterFrame(self.sprite.getAnimations().death.length - 1,function(){
      self.sprite.setAnimation('death_stay');
    });
  };
  this.attack = function(){
    this.sprite.setAnimation('attack');
    var self = this;
    this.sprite.afterFrame(self.sprite.getAnimations().attack.length - 1,function(){
      attacking.push(self);
      self.sprite.setAnimation('idle');
    });
  };
}
function makeEnemy(){
  var i = Math.floor(Math.random()*400);
  var frame = Math.floor(Math.random()*pirateanimation.walk.length);
  var sprite = new Kinetic.Sprite({
    x: i,
    y: 200,
    image: piratesheet,
    animation: 'walk',
    animations: pirateanimation,
    frameRate: 8,
    index: frame,
    width: 128,
    height:128
  });
  var temp =new Entity(sprite,enemyAI);
  temp.speed =  Math.random()*2+3;
  temp.setDirection((i%2)?1:-1);
  return temp;
}
function enemyAI(){
  if(this.sprite.getAnimation()==='walk'){
    this.sprite.setX(this.sprite.getX()+this.speed*this.direction);
    var temp = this.sprite.getX()+this.direction*this.sprite.getWidth();
    if(temp>1.1*stage.getWidth() || temp< -0.1*stage.getWidth())
      this.setDirection(-this.direction);
    this.sprite.setY(getYofFloor(this.sprite.getX()+0.45*this.direction*this.sprite.getWidth()-20));
  }
}
function getYofFloor(x){
  if(x > 945)
    return 155;
  else if(x > 900)
    return -(x-900)+200;
  else if(x > 133)
    return 200;
  else if(x > 69)
    return (x-69)+145;
  else
    return 145;
}
function init_game(){
  stage.add(background);
  stage.add(ship);
  stage.add(people);
  stage.add(main);
  pirateship = new Kinetic.Image({
          x: -500,
          y: -450,
          image: shipsheet,
          width: shipsheet.width,
          height: shipsheet.height
        });
  ship.add(pirateship);
  ship.batchDraw();
  back= new Kinetic.Image({
          x: 0,
          y: -125,
          image: backsheet,
          width: backsheet.width,
          height: backsheet.height
        });
  background.add(back);
  background.batchDraw();
  for(var i = 0; i < 8; i++){
    enemies[i] = makeEnemy();
  }
  red = new Kinetic.Sprite({
    x: 0,
    y: 0,
    image: redsheet,
    animation: 'idle',
    animations: redanimation,
    frameRate: 16,
    index: 0,
    width: 128,
    height:128,
    scale:1
  });
  orange = new Kinetic.Sprite({
    x: 10,
    y: -75,
    image: orangesheet,
    animation: 'idle',
    animations: orangeanimation,
    frameRate: 8,
    index: 0,
    width: 64,
    height:64
  });
  main.add(red);
  main.add(orange);
  main.setY(200);
  main.setX(400);
  for(i = 0; i < 8; i++){
    people.add(enemies[i].sprite);
  }
  red.start();
  orange.start();
  enemies[0].sprite.start();
  for(i = 0; i < 8; i++){
    enemies[i].sprite.start();
  }
  player = new Entity(red,function(){
    if(this.sprite.getAnimation()==='walk'){
      people.setX(people.getX()-8*this.direction);
      ship.setX(ship.getX()-8*this.direction);
    }
  });
  currentlevel={"env":{}};
  init_bindings();
  interval = window.setInterval(loop,100);
}
function getX(sprite,d){
  return sprite.sprite.getX()+(d||0.45)*sprite.direction*sprite.sprite.getWidth();
}
function loop(){
  if(!player.dead)player.ai();
  for(var i = 0; i < 8; i++){
    if(!enemies[i].dead)enemies[i].ai();
  }
  var tmp = main.getX()-ship.getX()+getX(player);
  for(i = 0; i < attacking.length; i++){
    if(attacking[i]===player){
      console.log('atc');
      var t = tmp + player.direction*0.55*player.sprite.getWidth();
      for(var j = 0; j < enemies.length;j++){
        if(enemies[j].dead)continue;
        var x1 = getX(enemies[j]) -35,x2 = getX(enemies[j])+30;
        if(t>x1 && t<x2){
          enemies[j].die();
        }
      }
    }else{
      var x1 = tmp -30,x2 = tmp+30;
      if(getX(attacking[i],0.7)>x1 && getX(attacking[i],0.7)<x2){
        player.die();
      }
    }
  }
  attacking = [];
  var temp = 30*Math.pow(Math.sin((k++)/12),2)||0;
  ship.setY(temp);
  ship.batchDraw();
  people.setY(temp);
  main.setY(temp+getYofFloor(tmp-20));
}
var k = 0;<commit_msg>fixed height<commit_after>var player, enemies = [], attacking=[], currentlevel, interval;
function Entity(sprite,ai){
  this.sprite = sprite;
  this.ai = ai;
  this.direction = 1;
  this.dead = false;
  this.setDirection = function(d){
    if(d === this.direction)
      return;
    this.sprite.setX(this.sprite.getX()-0.65*d*this.sprite.getWidth());
    this.sprite.setScaleX(d);
    this.direction = d;
  };
  this.die = function(){
    this.sprite.setAnimation('death');
    this.dead = true;
    var self = this;
    this.sprite.afterFrame(self.sprite.getAnimations().death.length - 1,function(){
      self.sprite.setAnimation('death_stay');
    });
  };
  this.attack = function(){
    this.sprite.setAnimation('attack');
    var self = this;
    this.sprite.afterFrame(self.sprite.getAnimations().attack.length - 1,function(){
      attacking.push(self);
      self.sprite.setAnimation('idle');
    });
  };
}
function makeEnemy(){
  var i = Math.floor(Math.random()*400);
  var frame = Math.floor(Math.random()*pirateanimation.walk.length);
  var sprite = new Kinetic.Sprite({
    x: i,
    y: 200,
    image: piratesheet,
    animation: 'walk',
    animations: pirateanimation,
    frameRate: 8,
    index: frame,
    width: 128,
    height:128
  });
  var temp =new Entity(sprite,enemyAI);
  temp.speed =  Math.random()*2+3;
  temp.setDirection((i%2)?1:-1);
  return temp;
}
function enemyAI(){
  if(this.sprite.getAnimation()==='walk'){
    this.sprite.setX(this.sprite.getX()+this.speed*this.direction);
    var temp = this.sprite.getX()+this.direction*this.sprite.getWidth();
    if(temp>1.1*stage.getWidth() || temp< -0.1*stage.getWidth())
      this.setDirection(-this.direction);
    this.sprite.setY(getYofFloor(this.sprite.getX()+0.45*this.direction*this.sprite.getWidth()-20));
  }
}
function getYofFloor(x){
  if(x > 945)
    return 160;
  else if(x > 900)
    return -(x-900)+205;
  else if(x > 133)
    return 205;
  else if(x > 69)
    return (x-69)+155;
  else
    return 160;
}
function init_game(){
  stage.add(background);
  stage.add(ship);
  stage.add(people);
  stage.add(main);
  pirateship = new Kinetic.Image({
          x: -500,
          y: -450,
          image: shipsheet,
          width: shipsheet.width,
          height: shipsheet.height
        });
  ship.add(pirateship);
  ship.batchDraw();
  back= new Kinetic.Image({
          x: 0,
          y: -125,
          image: backsheet,
          width: backsheet.width,
          height: backsheet.height
        });
  background.add(back);
  background.batchDraw();
  for(var i = 0; i < 8; i++){
    enemies[i] = makeEnemy();
  }
  red = new Kinetic.Sprite({
    x: 0,
    y: 0,
    image: redsheet,
    animation: 'idle',
    animations: redanimation,
    frameRate: 16,
    index: 0,
    width: 128,
    height:128,
    scale:1
  });
  orange = new Kinetic.Sprite({
    x: 10,
    y: -75,
    image: orangesheet,
    animation: 'idle',
    animations: orangeanimation,
    frameRate: 8,
    index: 0,
    width: 64,
    height:64
  });
  main.add(red);
  main.add(orange);
  main.setY(200);
  main.setX(400);
  for(i = 0; i < 8; i++){
    people.add(enemies[i].sprite);
  }
  red.start();
  orange.start();
  enemies[0].sprite.start();
  for(i = 0; i < 8; i++){
    enemies[i].sprite.start();
  }
  player = new Entity(red,function(){
    if(this.sprite.getAnimation()==='walk'){
      people.setX(people.getX()-8*this.direction);
      ship.setX(ship.getX()-8*this.direction);
    }
  });
  currentlevel={"env":{}};
  init_bindings();
  interval = window.setInterval(loop,100);
}
function getX(sprite,d){
  return sprite.sprite.getX()+(d||0.45)*sprite.direction*sprite.sprite.getWidth();
}
function loop(){
  if(!player.dead)player.ai();
  for(var i = 0; i < 8; i++){
    if(!enemies[i].dead)enemies[i].ai();
  }
  var tmp = main.getX()-ship.getX()+getX(player);
  for(i = 0; i < attacking.length; i++){
    if(attacking[i]===player){
      console.log('atc');
      var t = tmp + player.direction*0.55*player.sprite.getWidth();
      for(var j = 0; j < enemies.length;j++){
        if(enemies[j].dead)continue;
        var x1 = getX(enemies[j]) -35,x2 = getX(enemies[j])+30;
        if(t>x1 && t<x2){
          enemies[j].die();
        }
      }
    }else{
      var x1 = tmp -30,x2 = tmp+30;
      if(getX(attacking[i],0.7)>x1 && getX(attacking[i],0.7)<x2){
        player.die();
      }
    }
  }
  attacking = [];
  var temp = 30*Math.pow(Math.sin((k++)/12),2)||0;
  ship.setY(temp);
  ship.batchDraw();
  people.setY(temp);
  main.setY(temp+getYofFloor(tmp-20));
}
var k = 0;<|endoftext|>


<commit_before>module.exports = (function (){

    // The width & height of the screen
    SCREEN_WIDTH = 1280;
    SCREEN_HEIGHT = 720;

    // Module variables
    var Hero = require('./hero.js'),
        Monster = require('./monster.js');
        EntityManager = require('./entity_manager.js');

    var load = function(sm) {
      EntityManager.initialize();
        //TODO Menu/game state
        //TODO start game loop
    };

    var update = function(elapsedTime) {
        //TODO
    };

    var render = function() {
        //TODO
    };

    return {
      load: load,
      update: update,
      render: render,
    };

})();
<commit_msg>added constructors and redid structure<commit_after>window.onload = function()
{

    // The width & height of the screen
    SCREEN_WIDTH = 1280;
    SCREEN_HEIGHT = 720;

    // Module variables
    var Hero = require('./hero.js'),
        Monster = require('./monster.js');
        EntityManager = require('./entity_manager.js');
    ShopManager = require('./ShopManager.js');
    StatsManager = require('./StatsManager.js');

    var load = function(sm) {
      EntityManager.initialize();
        //TODO Menu/game state
        //TODO start game loop
    };

    var update = function(elapsedTime) {
        //TODO
    };

    var render = function() {
        //TODO
    };

}
<|endoftext|>


<commit_before>/*
 * gpub
 * https://github.com/goliatone/gpub
 *
 * Copyright (c) 2013 goliatone
 * Licensed under the MIT license.
 */
/*global define:true*/
/* jshint strict: false */
define('gpub', ['jquery'], function($) {

    var Gpub = function(config){
        console.log('Gpub: Constructor!');
    };

    Gpub.prototype.init = function(){
        console.log('Gpub: Init!');
        return 'This is just a stub!';
    };

    return Gpub;
});<commit_msg>WIP implementation.<commit_after>/*
 * gpub
 * https://github.com/goliatone/gpub
 *
 * Copyright (c) 2013 goliatone
 * Licensed under the MIT license.
 */
/*global define:true*/
/* jshint strict: false */
define('gpub', function($) {

    var options = {
        methodMapping:{
            publish:'publish',
            subscribe:'subscribe',
            unsubscribe:'unsubscribe'
        }
    };

    var Gpub = function(config){

    };

    Gpub.prototype.simple = function($, src, map){
        var o = $({});
        src = src || {};
        map = map || options.methodMapping;
        src[map['publish']] = function() { o.trigger.apply(o, arguments);};
        src[map['subscribe']] = function() { o.on.apply(o, arguments);};
        src[map['unsubscribe']] = function() { o.off.apply(o, arguments);};
    };

    return Gpub;
});<|endoftext|>


<commit_before>// TODO: Generic version, more useful returns
// TODO: Put inside module once tidied up
var getProperty = function(arr, key, keyField, valueField) {
  for(var i = 0; i < arr.length; i++) {
    if(arr[i][keyField] === key) {
      return arr[i][valueField];
    }
  }
  return null;
};

(function(window, document, undefined) {
  "use strict";

  var HQML = window.HQML || (window.HQML = {});

  var initQueue = [];

  var QObjects = {};

  QObjects.create = function(config) {
    var type = config.type,
        attr = config.attributes,
        children = config.children || [];

    if(!(type in QObjects)) {
      throw new TypeError(type + ' is not a valid QML Object');
    }

    // Inherit or create new
    var obj;
    if(QObjects[type].inherits) {
      obj = QObjects.create({
        type: QObjects[type].inherits,
        attributes: attr
      });
      for(var func in QObjects[type]) {
        obj[func] = QObjects[type][func];
      }
    }
    else {
      obj = Object.create(QObjects[type]);
    }

    QObjects.addProperties(obj, QObjects[type].defaultProperties, attr);

    // Make 'update' a self-observer
    // TODO: Just implement this same as other QML expressions
    if(typeof QObjects[type].update === 'function') {
      obj.update = ko.computed({
        read: QObjects[type].update,
        owner: obj,
        deferEvaluation: true
      });
    }

    // Create children, attach and put at front of init queue
    obj.children = []
    for(var i = 0; i < children.length; i++) {
      var child = QObjects.create(children[i]);
      child.parent = obj;
      obj.children.push(child);
      initQueue.unshift(child);
    }

    return obj;
  }

  QObjects.addProperties = function(obj, propList, attr, prefix) {
    if(!prefix) prefix = '';

    // Add observable properties to object
    // Public access by name, private implementer on _
    if(!obj._) {
      Object.defineProperty(obj, '_', { value: {} });
    }

    for(var prop in propList) {
      // Handle properties with '.' in the name by created nested object
      if(typeof propList[prop] === 'object') {
        obj[prop] = {};
        QObjects.addProperties(obj[prop], propList[prop], attr, prefix + prop + '.');
        continue;
      }

      // TODO: When building AST, make bare references point to this /
      //       alternately combine AST in this stage to make sure references are valid

      // Create a computed if attribute type is an expression
      var isExpression = getProperty(attr, prefix + prop, 'name', 'type') === 'Expression',
          value = getProperty(attr, prefix + prop, 'name', 'value');
      if(isExpression) {
        (function(propName) {
          obj._[propName] = ko.computed({
            // TODO: Smarter generation of read
            read: new Function("return " + value),
            // Write function kills this computed and replaces it with an observable
            // TODO: Adding computed expressions at runtime must be done via Qt.binding
            write: function(v) {
              var oldExpr = this._[propName];
              this._[propName] = ko.observable(v);
              Object.defineProperty(this, propName, {
                get: this._[propName],
                set: this._[propName]
              });

              // Use the old computed to force subscribers to rebind on new observable
              oldExpr.notifySubscribers(v);
              oldExpr.dispose();
            },
            owner: obj,
            deferEvaluation: true
          });
        })(prop);
      }
      else {
        obj._[prop] = ko.observable(value !== null ? value : propList[prop]);
      }

      Object.defineProperty(obj, prop, {
        enumerable: true,
        configurable: true,
        get: obj._[prop],
        set: obj._[prop]
      });
    }
  }

  // ---------------------- // TODO: Complete implementation / Document
  // QML Item
  QObjects.Item = {
    // TODO: Init function defining a layer, update which can move/resize it
  }

  Object.defineProperties(QObjects.Item, {
    defaultProperties: {
      value: {
        x: 0,
        y: 0,
        width: 100,
        height: 100
      }
    }
  });

  // ---------------------- // TODO: Complete implementation / Document
  // QML Rectangle
  QObjects.Rectangle = {
    init: function() {
      // TODO: Should this be group or layer? infer based on anim etc?
      this._.kNode = new Kinetic.Group();
      this._.kRect = new Kinetic.Rect();
      this._.kNode.add(this._.kRect);
      try {
        this.parent._.kNode.add(this._.kNode);
      }
      catch (e) {
        // Throw 'Rectangle cannot be child of parent.type'
      }
      this.update();
    },
    update: function() {
      // TODO: Maybe QObjects.create should automatically create subscribers for simple props?
      this._.kNode.setX(this.x);
      this._.kNode.setY(this.y);

      this._.kRect.setWidth(this.width);
      this._.kRect.setHeight(this.height);
      this._.kRect.setFill(this.color);
      this._.kRect.setCornerRadius(this.radius);

      this.draw();
    },
    draw: function() {
      this.parent.draw();
    }
  }

  Object.defineProperties(QObjects.Rectangle, {
    inherits: {
      value: 'Item'
    },
    defaultProperties: {
      value: {
        color: 'white',
        radius: 0
      }
    }
  });

  // ---------------------- // TODO: Complete implementation / Document
  // QML Text
  QObjects.Text = {
    init: function() {
      this._.kText = new Kinetic.Text({});
      // TODO: Abstract out parent attachement with try/catch into own function
      this.parent._.kNode.add(this._.kText);

      this.update();
    },
    update: function() {
      this._.kText.setText(this.text);
      this._.kText.setFill(this.color);
      this._.kText.setFontFamily(this.font.family);
      this._.kText.setFontSize(this.font.pixelSize);

      var style = (this.font.bold ? 'bold ' : '')
                + (this.font.italic ? 'italic' : '');
      this._.kText.setFontStyle(style);

      this.draw();
    },
    draw: function() {
      this.parent.draw();
    }
  }

  Object.defineProperties(QObjects.Text, {
    inherits: {
      value: 'Item'
    },
    defaultProperties: {
      value: {
        color: 'black',
        text: '',
        font: {
          family: 'Arial, Helvetica',
          pixelSize: 12, // TODO: Custom setter for font.pointSize which writes correct pixelSize for device
          bold: false,
          italic: false
        }
      }
    }
  });

  // Exports
  HQML.load = function(ast) {
    // TODO: Move root definition into module, use init params for dimensions/name
    var root = {
      init: function() {
        // TODO: User definable name, width, height
        var stage = new Kinetic.Stage({
          container: 'container',
          width: 800,
          height: 600
        });
        this._ = { kNode: new Kinetic.Layer() };
        stage.add(this._.kNode);
      },
      draw: function() {
        this._.kNode.batchDraw();
      }
    }

    root.init();

    window.q = []; // TMP
    ast.objects.forEach(function(obj) {
      if(obj.type in QObjects) {

        var thisObj = QObjects.create(obj);

        thisObj.parent = root;
        initQueue.unshift(thisObj);
        // TODO: init/parent assignment should be done by QObjects.create at end of inheritance chain
      }
    });

    for(var i = 0; i < initQueue.length; i++) {
      initQueue[i].init();
      // TMP: Expose to outside world
      window.q.push(initQueue[i]);
    }
  }

})(window, document);

// TODO: onload
HQML.load(tree);
<commit_msg>Allow property expressions to reference other local properties and parents<commit_after>// TODO: Generic version, more useful returns
// TODO: Put inside module once tidied up
var getProperty = function(arr, key, keyField, valueField) {
  for(var i = 0; i < arr.length; i++) {
    if(arr[i][keyField] === key) {
      return arr[i][valueField];
    }
  }
  return null;
};

(function(window, document, undefined) {
  "use strict";

  var HQML = window.HQML || (window.HQML = {});

  var initQueue = [];

  var QObjects = {};

  QObjects.create = function(config) {
    var type = config.type,
        attr = config.attributes,
        children = config.children || [];

    if(!(type in QObjects)) {
      throw new TypeError(type + ' is not a valid QML Object');
    }

    // Inherit or create new
    var obj;
    if(QObjects[type].inherits) {
      obj = QObjects.create({
        type: QObjects[type].inherits,
        attributes: attr
      });
      for(var func in QObjects[type]) {
        obj[func] = QObjects[type][func];
      }
    }
    else {
      obj = Object.create(QObjects[type]);
    }

    QObjects.addProperties(obj, obj, QObjects[type].defaultProperties, attr);

    // Make 'update' a self-observer
    // TODO: Just implement this same as other QML expressions
    if(typeof QObjects[type].update === 'function') {
      obj.update = ko.computed({
        read: QObjects[type].update,
        owner: obj,
        deferEvaluation: true
      });
    }

    // Create children, attach and put at front of init queue
    obj.children = []
    for(var i = 0; i < children.length; i++) {
      var child = QObjects.create(children[i]);
      child.parent = obj;
      obj.children.push(child);
      initQueue.unshift(child);
    }

    return obj;
  }

  QObjects.addProperties = function(context, obj, propList, attr, prefix) {
    if(!prefix) prefix = '';

    // Add observable properties to object
    // Public access by name, private implementer on _
    if(!obj._) {
      Object.defineProperty(obj, '_', { value: {} });
    }

    for(var prop in propList) {
      // Handle properties with '.' in the name by created nested object
      if(typeof propList[prop] === 'object') {
        obj[prop] = {};
        QObjects.addProperties(context, obj[prop], propList[prop], attr, prefix + prop + '.');
        continue;
      }

      // TODO: When building AST, make bare references point to this /
      //       alternately combine AST in this stage to make sure references are valid

      // Create a computed if attribute type is an expression
      var isExpression = getProperty(attr, prefix + prop, 'name', 'type') === 'Expression',
          value = getProperty(attr, prefix + prop, 'name', 'value');
      if(isExpression) {
        (function(propName) {
          obj._[propName] = ko.computed({
            // Provide the owning object as both 'this' and make its properties available through 'with'
            read: (new Function("_context", "with(_context){return " + value + "}")).bind(context, context),
            // Write function kills this computed and replaces it with an observable
            // TODO: Adding computed expressions at runtime must be done via Qt.binding
            write: function(v) {
              var oldExpr = this._[propName];
              this._[propName] = ko.observable(v);
              Object.defineProperty(this, propName, {
                get: this._[propName],
                set: this._[propName]
              });

              // Use the old computed to force subscribers to rebind on new observable
              oldExpr.notifySubscribers(v);
              oldExpr.dispose();
            },
            owner: obj,
            deferEvaluation: true
          });
        })(prop);
      }
      else {
        obj._[prop] = ko.observable(value !== null ? value : propList[prop]);
      }

      Object.defineProperty(obj, prop, {
        enumerable: true,
        configurable: true,
        get: obj._[prop],
        set: obj._[prop]
      });
    }
  }

  // ---------------------- // TODO: Complete implementation / Document
  // QML Item
  QObjects.Item = {
    // TODO: Init function defining a layer, update which can move/resize it
  }

  Object.defineProperties(QObjects.Item, {
    defaultProperties: {
      value: {
        x: 0,
        y: 0,
        width: 100,
        height: 100
      }
    }
  });

  // ---------------------- // TODO: Complete implementation / Document
  // QML Rectangle
  QObjects.Rectangle = {
    init: function() {
      // TODO: Should this be group or layer? infer based on anim etc?
      this._.kNode = new Kinetic.Group();
      this._.kRect = new Kinetic.Rect();
      this._.kNode.add(this._.kRect);
      try {
        this.parent._.kNode.add(this._.kNode);
      }
      catch (e) {
        // Throw 'Rectangle cannot be child of parent.type'
      }
      this.update();
    },
    update: function() {
      // TODO: Maybe QObjects.create should automatically create subscribers for simple props?
      this._.kNode.setX(this.x);
      this._.kNode.setY(this.y);

      this._.kRect.setWidth(this.width);
      this._.kRect.setHeight(this.height);
      this._.kRect.setFill(this.color);
      this._.kRect.setCornerRadius(this.radius);

      this.draw();
    },
    draw: function() {
      this.parent.draw();
    }
  }

  Object.defineProperties(QObjects.Rectangle, {
    inherits: {
      value: 'Item'
    },
    defaultProperties: {
      value: {
        color: 'white',
        radius: 0
      }
    }
  });

  // ---------------------- // TODO: Complete implementation / Document
  // QML Text
  QObjects.Text = {
    init: function() {
      this._.kText = new Kinetic.Text({});
      // TODO: Abstract out parent attachement with try/catch into own function
      this.parent._.kNode.add(this._.kText);

      this.update();
    },
    update: function() {
      this._.kText.setText(this.text);
      this._.kText.setFill(this.color);
      this._.kText.setFontFamily(this.font.family);
      this._.kText.setFontSize(this.font.pixelSize);

      var style = (this.font.bold ? 'bold ' : '')
                + (this.font.italic ? 'italic' : '');
      this._.kText.setFontStyle(style);

      this.draw();
    },
    draw: function() {
      this.parent.draw();
    }
  }

  Object.defineProperties(QObjects.Text, {
    inherits: {
      value: 'Item'
    },
    defaultProperties: {
      value: {
        color: 'black',
        text: '',
        font: {
          family: 'Arial, Helvetica',
          pixelSize: 12, // TODO: Custom setter for font.pointSize which writes correct pixelSize for device
          bold: false,
          italic: false
        }
      }
    }
  });

  // Exports
  HQML.load = function(ast) {
    // TODO: Move root definition into module, use init params for dimensions/name
    var root = {
      init: function() {
        // TODO: User definable name, width, height
        var stage = new Kinetic.Stage({
          container: 'container',
          width: 800,
          height: 600
        });
        this._ = { kNode: new Kinetic.Layer() };
        stage.add(this._.kNode);
      },
      draw: function() {
        this._.kNode.batchDraw();
      }
    }

    root.init();

    window.q = []; // TMP
    ast.objects.forEach(function(obj) {
      if(obj.type in QObjects) {

        var thisObj = QObjects.create(obj);

        thisObj.parent = root;
        initQueue.unshift(thisObj);
        // TODO: init/parent assignment should be done by QObjects.create at end of inheritance chain
      }
    });

    for(var i = 0; i < initQueue.length; i++) {
      initQueue[i].init();
      // TMP: Expose to outside world
      window.q.push(initQueue[i]);
    }
  }

})(window, document);

// TODO: onload
HQML.load(tree);
<|endoftext|>


<commit_before>
/*
 * statistics for disk devices
 */
function disk() {
  this.curr = initrow();
  this.prev = initrow();
  this.data = initrow();
}

function initrow() {
  return {
    total: initdisk()
  };
}

function initdisk() {
  return {
    read: {
      count: 0,
      sector: 0,
      time: 0
    },
    write: {
      count: 0,
      sector: 0,
      time: 0
    }
  };
}

function isDisk(label) {
  return /^(dm-\d+|md\d+|[hsv]d[a-z]+\d+)$/.test(label);
}

var diskPattern = /([a-z]+[0-9]*) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/;

function getDisk(row, name) {
  var data = row[name];
  if (data) {
    return data;
  }
  return row[name] = initdisk();
}

function diff(value1, value2) {
  if (value1 === 0 || value2 === 0) {
    return 0;
  } else {
    return Math.abs(value1 - value2);
  }
}

disk.prototype.get = function(nstat, callback) {

  var self = this;
  var curr = self.curr;
  var prev = self.prev;
  var data = self.data;
  var total = initdisk();

  nstat.lines(
    '/proc/diskstats',
    function (line) {

      var match = diskPattern.exec(line);
      if (!match) {
        return;
      }

      var devname = match[1];

      if (isDisk(devname)) {
        var currdisk = getDisk(curr, devname);
        var prevdisk = getDisk(prev, devname);
        var datadisk = getDisk(data, devname);

        // set current value
        currdisk.read.count = Number(match[2]);
        currdisk.read.sector = Number(match[4]);
        currdisk.read.time = Number(match[5]);
        currdisk.write.count = Number(match[6]);
        currdisk.write.sector = Number(match[8]);
        currdisk.write.time = Number(match[9]);

        // get difference
        datadisk.read.count = diff(prevdisk.read.count, currdisk.read.count);
        datadisk.read.sector = diff(prevdisk.read.sector, currdisk.read.sector);
        datadisk.read.time = diff(prevdisk.read.time, currdisk.read.time);
        datadisk.write.count = diff(prevdisk.write.count, currdisk.write.count);
        datadisk.write.sector = diff(prevdisk.write.sector, currdisk.write.sector);
        datadisk.write.time = diff(prevdisk.write.time, currdisk.write.time);

        total.read.count += datadisk.read.count;
        total.read.sector += datadisk.read.sector;
        total.read.time += datadisk.read.time;
        total.write.count += datadisk.write.count;
        total.write.sector += datadisk.write.sector;
        total.write.time += datadisk.write.time;
      }
    },
    function (err) {
      self.prev = self.curr;
      self.curr = initrow();
      self.data.total = total;

      if (err) {

        callback(err);

      } else {

        nstat.exec('df',['-klP'], function(err, data) {
          if (err) {
            callback(err);
          } else {
            var lines = data.split('\n');
            for (var i = 1; i < lines.length; i++) {
              var line = lines[i].split(/\s+/);
              var devname = line[0];
              if (devname.indexOf('/dev/') === 0) {
                devname = devname.substring(5);
              }
              var disk = self.data[devname];
              if (disk) {
                disk.usage = {
                  total: parseInt(line[1]),
                  used: parseInt(line[2]),
                  available: parseInt(line[3])
                };
              }
            }

            // remove disks which has no usage
            for (var name in self.data) {
              if (!('usage' in self.data[name])) {
                delete self.data[name];
              }
            }

            callback(null, self.data);
          }
        });

      }
      self.data.total = initdisk();
    }
  );
};

module.exports = new disk();

<commit_msg>Improve disk check<commit_after>
/*
 * statistics for disk devices
 */
function disk() {
  this.curr = initrow();
  this.prev = initrow();
  this.data = initrow();
}

function initrow() {
  return {
    total: initdisk()
  };
}

function initdisk() {
  return {
    read: {
      count: 0,
      sector: 0,
      time: 0
    },
    write: {
      count: 0,
      sector: 0,
      time: 0
    }
  };
}

function isDisk(label) {
  return (/^(dm-\d+|md\d+|x?[hsv]d[a-z]+\d+)$/).test(label);
}

var diskPattern = /([a-z]+[\-0-9]*) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/;

function getDisk(row, name) {
  var data = row[name];
  if (data) {
    return data;
  }
  return row[name] = initdisk();
}

function diff(value1, value2) {
  if (value1 === 0 || value2 === 0) {
    return 0;
  } else {
    return Math.abs(value1 - value2);
  }
}

disk.prototype.get = function(nstat, callback) {

  var self = this;
  var curr = self.curr;
  var prev = self.prev;
  var data = self.data;
  var total = initdisk();

  nstat.lines(
    '/proc/diskstats',
    function (line) {

      var match = diskPattern.exec(line);
      if (!match) {
        return;
      }

      var devname = match[1];

      if (isDisk(devname)) {
        var currdisk = getDisk(curr, devname);
        var prevdisk = getDisk(prev, devname);
        var datadisk = getDisk(data, devname);

        // set current value
        currdisk.read.count = Number(match[2]);
        currdisk.read.sector = Number(match[4]);
        currdisk.read.time = Number(match[5]);
        currdisk.write.count = Number(match[6]);
        currdisk.write.sector = Number(match[8]);
        currdisk.write.time = Number(match[9]);

        // get difference
        datadisk.read.count = diff(prevdisk.read.count, currdisk.read.count);
        datadisk.read.sector = diff(prevdisk.read.sector, currdisk.read.sector);
        datadisk.read.time = diff(prevdisk.read.time, currdisk.read.time);
        datadisk.write.count = diff(prevdisk.write.count, currdisk.write.count);
        datadisk.write.sector = diff(prevdisk.write.sector, currdisk.write.sector);
        datadisk.write.time = diff(prevdisk.write.time, currdisk.write.time);

        total.read.count += datadisk.read.count;
        total.read.sector += datadisk.read.sector;
        total.read.time += datadisk.read.time;
        total.write.count += datadisk.write.count;
        total.write.sector += datadisk.write.sector;
        total.write.time += datadisk.write.time;
      }
    },
    function (err) {
      self.prev = self.curr;
      self.curr = initrow();
      self.data.total = total;

      if (err) {

        callback(err);

      } else {

        nstat.exec('df',['-klP'], function(err, data) {
          if (err) {
            callback(err);
          } else {
            var lines = data.split('\n');
            for (var i = 1; i < lines.length; i++) {
              var line = lines[i].split(/\s+/);
              var devname = line[0];
              if (devname.indexOf('/dev/') === 0) {
                devname = devname.substring(5);
              }
              var disk = self.data[devname];
              if (disk) {
                disk.usage = {
                  total: parseInt(line[1]),
                  used: parseInt(line[2]),
                  available: parseInt(line[3])
                };
              }
            }

            // remove disks which has no usage
            for (var name in self.data) {
              if (!('usage' in self.data[name])) {
                delete self.data[name];
              }
            }

            callback(null, self.data);
          }
        });

      }
      self.data.total = initdisk();
    }
  );
};

module.exports = new disk();

<|endoftext|>


<commit_before>var counter = require("counter");
var db = require("examples/db");

exports.handle = function (req) {
    var tokens = req.uri.split("/");
    tokens.shift();
    tokens.shift();
    var operator = tokens.shift();
    switch (operator) {
        case "counter":
            return new Response('Hello ' + req.uri + ' ' + counter.count());
        case "insert":
            db.insert(tokens[0], tokens[1]);
            break;
        case "find":
            db.find.apply(db.find, tokens);
            break;
        case "findOne":
            db.findOne.apply(db.findOne, tokens);
            break;
        default:
            break;
    }
    return new Response("");
}
<commit_msg>Change the default messsage of main.js to "Hello World".<commit_after>var counter = require("counter");
var db = require("examples/db");

exports.handle = function (req) {
    var tokens = req.uri.split("/");
    tokens.shift();
    tokens.shift();
    var operator = tokens.shift();
    switch (operator) {
        case "counter":
            return new Response('Hello ' + req.uri + ' ' + counter.count());
        case "insert":
            db.insert(tokens[0], tokens[1]);
            break;
        case "find":
            db.find.apply(db.find, tokens);
            break;
        case "findOne":
            db.findOne.apply(db.findOne, tokens);
            break;
        default:
            break;
    }
    return new Response("Hello World");
}
<|endoftext|>


<commit_before>/**
 * @author Adam Meadows [@job13er](https://github.com/job13er)
 * @copyright 2015 Cyan, Inc. All rights reserved
 */

'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var changeCase = require('change-case');
var config = require('./config');
var utils = require('./utils');

// 'Constants' to store some info so we con't calculate it more than once
var CWD = process.cwd();
var FILES_DIR = path.join(__dirname, '../files/project-templates');

/** @exports init */
var ns = {};

/**
 * Take a name like 'cy-foo-bar-baz-ui' and convert to
 * foo-bar-baz, if it follows the pattern. Otherwise return
 * the string 'NON-APP'
 * @param {String} projectName - name of the project
 * @returns {String} - name without cruft
 */
ns.cleanupCruft = function (projectName) {
    var match = projectName.match(/^cy\-(.+)\-ui$/);

    if (match === null) {
        return 'NON-APP';
    }

    return match[1];
};

/**
 * Actual functionality of the 'init' command
 * @param {Ojbect} argv - the minimist arguments object
 * @returns {Number} 0 on success, 1 on error
*/
ns.command = function (argv) {
    var _config = config.load(CWD);
    if (!_config) {
        console.error('beaker.json missing');
        console.info('To create a default beaker.json file run the following command: beaker newConfig');
        return 1;
    }

    // get today's year for copyright headers, etc.
    var today = new Date();
    var year = today.getFullYear();
    var projectName = utils.projectName;
    var cruftlessName = ns.cleanupCruft(projectName);
    var projectType = argv.type;
    var templateData = {
        author: _config.author,
        company: _config.company,
        year: year,
        projectName: projectName,
        projectType: projectType,
        camelProjectName: changeCase.camel(projectName),
        githubHost: _config.github.host,
        githubUser: _config.github.user,
        npmRegistry: _config.npm.registry,
        beakerVersion: utils.pkg.version,
        cruftlessName: cruftlessName,
        templateDir: _config.templateDir || FILES_DIR,
    };

    utils.copyDir('common', CWD, templateData);
    utils.copyDir(projectType, CWD, templateData);

    // clean up symlinks, if they exist
    _.forEach(['src', 'spec', 'node-spec'], function (pathElement) {
        var fullPath = path.join(CWD, pathElement, 'project-name');
        if (fs.existsSync(fullPath)) {
            fs.unlink(fullPath);
        }
    });

    return 0;
};

module.exports = ns;
<commit_msg>Adding back whitespace<commit_after>/**
 * @author Adam Meadows [@job13er](https://github.com/job13er)
 * @copyright 2015 Cyan, Inc. All rights reserved
 */

'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var changeCase = require('change-case');
var config = require('./config');
var utils = require('./utils');

// 'Constants' to store some info so we con't calculate it more than once
var CWD = process.cwd();
var FILES_DIR = path.join(__dirname, '../files/project-templates');

/** @exports init */
var ns = {};

/**
 * Take a name like 'cy-foo-bar-baz-ui' and convert to
 * foo-bar-baz, if it follows the pattern. Otherwise return
 * the string 'NON-APP'
 * @param {String} projectName - name of the project
 * @returns {String} - name without cruft
 */
ns.cleanupCruft = function (projectName) {
    var match = projectName.match(/^cy\-(.+)\-ui$/);

    if (match === null) {
        return 'NON-APP';
    }

    return match[1];
};

/**
 * Actual functionality of the 'init' command
 * @param {Ojbect} argv - the minimist arguments object
 * @returns {Number} 0 on success, 1 on error
*/
ns.command = function (argv) {
    var _config = config.load(CWD);

    if (!_config) {
        console.error('beaker.json missing');
        console.info('To create a default beaker.json file run the following command: beaker newConfig');
        return 1;
    }

    // get today's year for copyright headers, etc.
    var today = new Date();
    var year = today.getFullYear();
    var projectName = utils.projectName;
    var cruftlessName = ns.cleanupCruft(projectName);
    var projectType = argv.type;
    var templateData = {
        author: _config.author,
        company: _config.company,
        year: year,
        projectName: projectName,
        projectType: projectType,
        camelProjectName: changeCase.camel(projectName),
        githubHost: _config.github.host,
        githubUser: _config.github.user,
        npmRegistry: _config.npm.registry,
        beakerVersion: utils.pkg.version,
        cruftlessName: cruftlessName,
        templateDir: _config.templateDir || FILES_DIR,
    };

    utils.copyDir('common', CWD, templateData);
    utils.copyDir(projectType, CWD, templateData);

    // clean up symlinks, if they exist
    _.forEach(['src', 'spec', 'node-spec'], function (pathElement) {
        var fullPath = path.join(CWD, pathElement, 'project-name');
        if (fs.existsSync(fullPath)) {
            fs.unlink(fullPath);
        }
    });

    return 0;
};

module.exports = ns;
<|endoftext|>


<commit_before>function VotePlugin(bot) {
	var self = this;
	self.name = "vote";
	self.help = "Vote plugin";
	self.depend = ["cmd", "auth"];

	self.votes = {};
	self.regex = /^\s*([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*)[\s,:]*(\+\+||--)\s*$/i

	self.voteend = function(to) {
		var vote = self.votes[to];
		bot.say(to, "Vote by " + vote.by + " over: " + vote.question);
		bot.say(to, "Agreed: " + vote.agree.length + ", disagreed: " + vote.disagree.length);
		clearTimeout(vote.timeout);
		delete self.votes[to];
	};

	self.activity = function(to) {
		var vote = self.votes[to];
		if (vote.timeout !== null)
			clearTimeout(vote.timeout);

		vote.timeout = setTimeout(function() {
			self.voteend(to);
		}, 5 * 60 * 1000);
	};

	self.events = {
		"cmd#votestart": function(nick, to, args) {
			if (!(to in self.votes)) {
				if (args[0] === undefined || args[0].trim() == "") {
					bot.notice(nick, "Vote must have a question");
					return;
				}

				var vote = self.votes[to] = {
					by: nick,
					question: args[0].trim(),
					agree: [],
					disagree: [],
					timeout: null
				};
				bot.say(to, "Vote by " + vote.by + " started: " + vote.question);
				bot.say(to, "Write `" + bot.nick + ": ++` to agree, `" + bot.nick + ": --` to disagree");
				self.activity(to);
			}
			else {
				bot.notice(nick, "Already ongoing vote in " + to + " by " + self.votes[to].by);
			}
		},

		"cmd#voteend": function(nick, to, args, message) {
			if ((to in self.votes) && (nick == self.votes[to].by || bot.plugins.auth.check(5, message))) {
				self.voteend(to);
			}
			else {
				bot.notice(nick, "You can only stop your own ongoing vote");
			}
		},

		"cmd#vote": function(nick, to) {
			if (to in self.votes) {
				var vote = self.votes[to];
				bot.say(to, "Vote by " + vote.by + ": " + vote.question);
				bot.say(to, "Agreed: " + vote.agree.length + ", disagreed: " + vote.disagree.length);
			}
		},

		"message#": function(nick, to, text) {
			if (to in self.votes) {
				var vote = self.votes[to];
				var m = text.match(self.regex);
				if (m && (m[1].toLowerCase() == bot.nick.toLowerCase())) {
					if (m[2] == "++") {
						var i = vote.disagree.indexOf(nick);
						if (i != -1)
							vote.disagree.splice(i, 1);
						if (vote.agree.indexOf(nick) == -1) {
							vote.agree.push(nick);
							bot.notice(nick, "vote for '" + vote.question + "' in " + to + " counted");
						}
					}
					else if (m[2] == "--") {
						var i = vote.agree.indexOf(nick);
						if (i != -1)
							vote.agree.splice(i, 1);
						if (vote.disagree.indexOf(nick) == -1) {
							vote.disagree.push(nick);
							bot.notice(nick, "vote against '" + vote.question + "' in " + to + " counted");
						}
					}
					self.activity(to);
				}
			}
		},
	}
}

module.exports = VotePlugin;
<commit_msg>Use '' for vote<commit_after>function VotePlugin(bot) {
	var self = this;
	self.name = "vote";
	self.help = "Vote plugin";
	self.depend = ["cmd", "auth"];

	self.votes = {};
	self.regex = /^\s*([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*)[\s,:]*(\+\+||--)\s*$/i

	self.voteend = function(to) {
		var vote = self.votes[to];
		bot.say(to, "Vote by " + vote.by + " over: " + vote.question);
		bot.say(to, "Agreed: " + vote.agree.length + ", disagreed: " + vote.disagree.length);
		clearTimeout(vote.timeout);
		delete self.votes[to];
	};

	self.activity = function(to) {
		var vote = self.votes[to];
		if (vote.timeout !== null)
			clearTimeout(vote.timeout);

		vote.timeout = setTimeout(function() {
			self.voteend(to);
		}, 5 * 60 * 1000);
	};

	self.events = {
		"cmd#votestart": function(nick, to, args) {
			if (!(to in self.votes)) {
				if (args[0] === undefined || args[0].trim() == "") {
					bot.notice(nick, "Vote must have a question");
					return;
				}

				var vote = self.votes[to] = {
					by: nick,
					question: args[0].trim(),
					agree: [],
					disagree: [],
					timeout: null
				};
				bot.say(to, "Vote by " + vote.by + " started: " + vote.question);
				bot.say(to, "Write '" + bot.nick + ": ++' to agree, '" + bot.nick + ": --' to disagree");
				self.activity(to);
			}
			else {
				bot.notice(nick, "Already ongoing vote in " + to + " by " + self.votes[to].by);
			}
		},

		"cmd#voteend": function(nick, to, args, message) {
			if ((to in self.votes) && (nick == self.votes[to].by || bot.plugins.auth.check(5, message))) {
				self.voteend(to);
			}
			else {
				bot.notice(nick, "You can only stop your own ongoing vote");
			}
		},

		"cmd#vote": function(nick, to) {
			if (to in self.votes) {
				var vote = self.votes[to];
				bot.say(to, "Vote by " + vote.by + ": " + vote.question);
				bot.say(to, "Agreed: " + vote.agree.length + ", disagreed: " + vote.disagree.length);
			}
		},

		"message#": function(nick, to, text) {
			if (to in self.votes) {
				var vote = self.votes[to];
				var m = text.match(self.regex);
				if (m && (m[1].toLowerCase() == bot.nick.toLowerCase())) {
					if (m[2] == "++") {
						var i = vote.disagree.indexOf(nick);
						if (i != -1)
							vote.disagree.splice(i, 1);
						if (vote.agree.indexOf(nick) == -1) {
							vote.agree.push(nick);
							bot.notice(nick, "vote for '" + vote.question + "' in " + to + " counted");
						}
					}
					else if (m[2] == "--") {
						var i = vote.agree.indexOf(nick);
						if (i != -1)
							vote.agree.splice(i, 1);
						if (vote.disagree.indexOf(nick) == -1) {
							vote.disagree.push(nick);
							bot.notice(nick, "vote against '" + vote.question + "' in " + to + " counted");
						}
					}
					self.activity(to);
				}
			}
		},
	}
}

module.exports = VotePlugin;
<|endoftext|>


<commit_before>'use strict';

let squad           = require('squad');
let currify         = require('currify/legacy');

let interpret       = require('./interpret');
let parenthesize    = require('./parenthesize');
let tokenize        = require('./tokenize');
let bracketsCheck   = require('./brackets-check');
let check           = require('./check');

let checkString     = currify(check, 'string');
let checkExpression = checkString('expression');

let lisp            = squad(
    interpret,
    parenthesize,
    bracketsCheck,
    tokenize,
    checkExpression
);

module.exports      = lisp;
<commit_msg>refactor(lisp) let -> const<commit_after>'use strict';

const squad = require('squad');
const currify = require('currify/legacy');

const interpret = require('./interpret');
const parenthesize = require('./parenthesize');
const tokenize = require('./tokenize');
const bracketsCheck = require('./brackets-check');
const check = require('./check');

const checkString = currify(check, 'string');
const checkExpression = checkString('expression');

const lisp = squad(
    interpret,
    parenthesize,
    bracketsCheck,
    tokenize,
    checkExpression
);

module.exports = lisp;
<|endoftext|>


<commit_before>/* eslint prefer-reflect: "off" */

import { select } from 'd3';
import { Observer } from '@scola/d3-model';
import Item from './item';

export default class List extends Observer {
  constructor() {
    super();

    this._gesture = null;
    this._items = new Set();
    this._rootMedia = null;
    this._bodyMedia = null;
    this._inset = false;
    this._item = null;
    this._message = null;
    this._prepare = null;
    this._title = null;
    this._comment = null;

    this._root = select('body')
      .append('div')
      .remove()
      .classed('scola list', true)
      .styles({
        'box-sizing': 'content-box',
        'margin-bottom': '2em',
        'overflow': 'hidden'
      });

    this._title = this._root
      .append('div')
      .classed('scola title', true)
      .styles({
        'color': '#AAA',
        'display': 'none',
        'font-size': '0.9em',
        'justify-content': 'space-between',
        'padding': '0 1.111em 0.555em',
        'text-transform': 'uppercase'
      });

    this._titleText = this._title
      .append('span')
      .classed('scola text', true)
      .styles({
        'font-size': 'inherit'
      });

    this._titleIcon = this._title
      .append('span')
      .classed('scola icon ion-ios-arrow-down', true)
      .styles({
        'display': 'none',
        'font-size': 'inherit',
        'height': '1em',
        'text-align': 'center',
        'width': '1em'
      });

    this._body = this._root
      .append('div')
      .classed('scola body', true)
      .styles({
        'border-bottom': '1px solid #CCC',
        'border-top': '1px solid #CCC',
        'overflow': 'hidden'
      });

    this._comment = this._root
      .append('div')
      .classed('scola comment', true)
      .styles({
        'color': '#AAA',
        'display': 'none',
        'font-size': '0.9em',
        'line-height': '1.5em',
        'padding': '0.75em 1.1em 0'
      });

    this._bindBody();
  }

  destroy() {
    super.destroy();

    this._unbindBody();
    this._unbindTitle();
    this._deleteInset();

    this._items.forEach((item) => {
      item.destroy();
    });

    this._items.clear();

    this._root.dispatch('destroy');
    this._root.remove();
    this._root = null;
  }

  root() {
    return this._root;
  }

  body() {
    return this._body;
  }

  items() {
    return this._items;
  }

  filled() {
    return this._items.size > 0;
  }

  prepare(value = null) {
    if (value === null) {
      return this._prepare;
    }

    this._prepare = value;
    return this;
  }

  item(value = null) {
    if (value === null) {
      return this._item;
    }

    this._item = value;
    return this;
  }

  model(value = null) {
    value = super.model(value);

    if (value === null) {
      return value;
    }

    if (this._model.get(this._name) === false) {
      this._root.styles({
        'height': '1.5em',
        'border-bottom': '1px solid #CCC'
      });
    }

    this._titleIcon
      .style('display', null);

    this._bindTitle();
    return this;
  }

  inset(width = '48em') {
    if (width === null) {
      return this._inset;
    }

    if (width === false) {
      this._deleteInset();
    }

    if (this._rootMedia === null) {
      this._insertInset(width);
    }

    return this;
  }

  title(value = null) {
    if (value === null) {
      return this._title;
    }

    if (value === false) {
      return this._hideTitle();
    }

    return this._showTitle(value);
  }

  comment(value = null) {
    if (value === null) {
      return this._comment;
    }

    if (value === false) {
      return this._hideComment();
    }

    return this._showComment(value);
  }

  append(item, action = true) {
    if (action === false) {
      return this._deleteItem(item);
    }

    return this._insertItem(item);
  }

  clear() {
    this._items.forEach((item) => {
      item.destroy();
    });

    this._items.clear();
    return this;
  }

  disabled(value) {
    this._items.forEach((item) => {
      item.disabled(value);
    });

    return this;
  }

  message(value = null) {
    if (value === null) {
      return this._message;
    }

    if (value === false) {
      return this._deleteMessage();
    }

    if (this._message) {
      return this._updateMessage(value);
    }

    return this._insertMessage(value);
  }

  render(data) {
    if (this._prepare) {
      this._prepare(data, this);
    }

    if (this._items.size > 0) {
      this.clear();
    }

    data.forEach((datum, index) => {
      this.append(this._item(datum, index));
    });

    return this;
  }

  _bindBody() {
    this._gesture = this._body
      .gesture()
      .on('panstart', (e) => e.stopPropagation())
      .on('panright', (e) => e.stopPropagation())
      .on('panleft', (e) => e.stopPropagation())
      .on('panend', (e) => e.stopPropagation())
      .on('swiperight', (e) => e.stopPropagation())
      .on('swipeleft', (e) => e.stopPropagation())
      .on('tap', (e) => e.stopPropagation());
  }

  _unbindBody() {
    if (this._gesture) {
      this._gesture.destroy();
      this._gesture = null;
    }
  }

  _insertInset(width) {
    this._rootMedia = this._root
      .media(`not all and (min-width: ${width})`)
      .call(() => { this._inset = false; })
      .media(`(min-width: ${width})`)
      .call(() => { this._inset = true; })
      .styles({
        'margin-left': '1em',
        'margin-right': '1em'
      })
      .start();

    this._bodyMedia = this._body
      .media(`(min-width: ${width})`)
      .styles({
        'border-bottom': 'none',
        'border-radius': '0.5em',
        'border-top': 'none'
      })
      .start();

    return this;
  }

  _deleteInset() {
    if (this._rootMedia) {
      this._rootMedia.destroy();
      this._rootMedia = null;
    }

    if (this._bodyMedia) {
      this._bodyMedia.destroy();
      this._bodyMedia = null;
    }

    return this;
  }

  _deleteMessage() {
    if (this._message) {
      this.append(this._message, false);
      this._message.destroy();
      this._message = null;
    }

    return this;
  }

  _insertMessage(text) {
    this._message = this
      .append(new Item());

    this._message
      .text(text)
      .primary();

    return this;
  }

  _updateMessage(text) {
    this._message
      .part(0)
      .text(text);

    return this;
  }

  _showTitle(title) {
    this._title
      .style('display', 'flex');

    this._titleText
      .text(title);

    return this;
  }

  _hideTitle() {
    this._title
      .style('display', 'none');

    return this;
  }

  _showComment(comment) {
    this._comment
      .style('display', 'block')
      .text(comment);

    return this;
  }

  _hideComment() {
    this._comment
      .style('display', 'none');

    return this;
  }

  _insertItem(item) {
    item.first(this._items.size === 0);

    this._items.add(item);
    this._body.append(() => item.root().node());

    return item;
  }

  _deleteItem(item) {
    this._items.delete(item);
    item.root().remove();

    return item;
  }

  _bindTitle() {
    if (this._title) {
      this._title
        .classed('click', true)
        .style('cursor', 'pointer')
        .on('click.scola-list', () => this._click());
    }
  }

  _unbindTitle() {
    if (this._title) {
      this._title
        .classed('click', false)
        .style('cursor', null)
        .on('click.scola-list', null);
    }
  }

  _click() {
    if (this._model) {
      const value = this._model.get(this._name);
      this._model.set(this._name, value === false ? true : false);
    }
  }

  _set(setEvent) {
    if (setEvent.name !== this._name) {
      return;
    }

    const bodyHeight = this._body.boundingRect('height');
    const commentHeight = this._comment.boundingRect('height');
    const titleHeight = this._title.boundingRect('height');

    if (setEvent.value === true) {
      this._root.style('border', 0);
    }

    this._root
      .transition()
      .style('height', () => {
        return setEvent.value !== false ? (
          titleHeight +
          bodyHeight +
          commentHeight
        ) + 'px' : titleHeight + 'px';
      })
      .on('end', () => {
        if (this._root === null) {
          return;
        }

        if (setEvent.value !== false) {
          this._root.style('height', null);
        } else {
          this._root.style('border-bottom', '1px solid #CCC');
        }
      });

    this._titleIcon
      .transition()
      .style('transform', () => {
        return setEvent.value !== false ?
          'rotate(0deg)' :
          'rotate(-90deg)';
      });
  }
}
<commit_msg>Unset message when clearing<commit_after>/* eslint prefer-reflect: "off" */

import { select } from 'd3';
import { Observer } from '@scola/d3-model';
import Item from './item';

export default class List extends Observer {
  constructor() {
    super();

    this._gesture = null;
    this._items = new Set();
    this._rootMedia = null;
    this._bodyMedia = null;
    this._inset = false;
    this._item = null;
    this._message = null;
    this._prepare = null;
    this._title = null;
    this._comment = null;

    this._root = select('body')
      .append('div')
      .remove()
      .classed('scola list', true)
      .styles({
        'box-sizing': 'content-box',
        'margin-bottom': '2em',
        'overflow': 'hidden'
      });

    this._title = this._root
      .append('div')
      .classed('scola title', true)
      .styles({
        'color': '#AAA',
        'display': 'none',
        'font-size': '0.9em',
        'justify-content': 'space-between',
        'padding': '0 1.111em 0.555em',
        'text-transform': 'uppercase'
      });

    this._titleText = this._title
      .append('span')
      .classed('scola text', true)
      .styles({
        'font-size': 'inherit'
      });

    this._titleIcon = this._title
      .append('span')
      .classed('scola icon ion-ios-arrow-down', true)
      .styles({
        'display': 'none',
        'font-size': 'inherit',
        'height': '1em',
        'text-align': 'center',
        'width': '1em'
      });

    this._body = this._root
      .append('div')
      .classed('scola body', true)
      .styles({
        'border-bottom': '1px solid #CCC',
        'border-top': '1px solid #CCC',
        'overflow': 'hidden'
      });

    this._comment = this._root
      .append('div')
      .classed('scola comment', true)
      .styles({
        'color': '#AAA',
        'display': 'none',
        'font-size': '0.9em',
        'line-height': '1.5em',
        'padding': '0.75em 1.1em 0'
      });

    this._bindBody();
  }

  destroy() {
    super.destroy();

    this._unbindBody();
    this._unbindTitle();
    this._deleteInset();

    this._items.forEach((item) => {
      item.destroy();
    });

    this._items.clear();

    this._root.dispatch('destroy');
    this._root.remove();
    this._root = null;
  }

  root() {
    return this._root;
  }

  body() {
    return this._body;
  }

  items() {
    return this._items;
  }

  filled() {
    return this._items.size > 0;
  }

  prepare(value = null) {
    if (value === null) {
      return this._prepare;
    }

    this._prepare = value;
    return this;
  }

  item(value = null) {
    if (value === null) {
      return this._item;
    }

    this._item = value;
    return this;
  }

  model(value = null) {
    value = super.model(value);

    if (value === null) {
      return value;
    }

    if (this._model.get(this._name) === false) {
      this._root.styles({
        'height': '1.5em',
        'border-bottom': '1px solid #CCC'
      });
    }

    this._titleIcon
      .style('display', null);

    this._bindTitle();
    return this;
  }

  inset(width = '48em') {
    if (width === null) {
      return this._inset;
    }

    if (width === false) {
      this._deleteInset();
    }

    if (this._rootMedia === null) {
      this._insertInset(width);
    }

    return this;
  }

  title(value = null) {
    if (value === null) {
      return this._title;
    }

    if (value === false) {
      return this._hideTitle();
    }

    return this._showTitle(value);
  }

  comment(value = null) {
    if (value === null) {
      return this._comment;
    }

    if (value === false) {
      return this._hideComment();
    }

    return this._showComment(value);
  }

  append(item, action = true) {
    if (action === false) {
      return this._deleteItem(item);
    }

    return this._insertItem(item);
  }

  clear() {
    this._items.forEach((item) => {
      item.destroy();
    });

    this._items.clear();
    this._message = null;

    return this;
  }

  disabled(value) {
    this._items.forEach((item) => {
      item.disabled(value);
    });

    return this;
  }

  message(value = null) {
    if (value === null) {
      return this._message;
    }

    if (value === false) {
      return this._deleteMessage();
    }

    if (this._message) {
      return this._updateMessage(value);
    }

    return this._insertMessage(value);
  }

  render(data) {
    if (this._prepare) {
      this._prepare(data, this);
    }

    if (this._items.size > 0) {
      this.clear();
    }

    data.forEach((datum, index) => {
      this.append(this._item(datum, index));
    });

    return this;
  }

  _bindBody() {
    this._gesture = this._body
      .gesture()
      .on('panstart', (e) => e.stopPropagation())
      .on('panright', (e) => e.stopPropagation())
      .on('panleft', (e) => e.stopPropagation())
      .on('panend', (e) => e.stopPropagation())
      .on('swiperight', (e) => e.stopPropagation())
      .on('swipeleft', (e) => e.stopPropagation())
      .on('tap', (e) => e.stopPropagation());
  }

  _unbindBody() {
    if (this._gesture) {
      this._gesture.destroy();
      this._gesture = null;
    }
  }

  _insertInset(width) {
    this._rootMedia = this._root
      .media(`not all and (min-width: ${width})`)
      .call(() => { this._inset = false; })
      .media(`(min-width: ${width})`)
      .call(() => { this._inset = true; })
      .styles({
        'margin-left': '1em',
        'margin-right': '1em'
      })
      .start();

    this._bodyMedia = this._body
      .media(`(min-width: ${width})`)
      .styles({
        'border-bottom': 'none',
        'border-radius': '0.5em',
        'border-top': 'none'
      })
      .start();

    return this;
  }

  _deleteInset() {
    if (this._rootMedia) {
      this._rootMedia.destroy();
      this._rootMedia = null;
    }

    if (this._bodyMedia) {
      this._bodyMedia.destroy();
      this._bodyMedia = null;
    }

    return this;
  }

  _deleteMessage() {
    if (this._message) {
      this.append(this._message, false);
      this._message.destroy();
      this._message = null;
    }

    return this;
  }

  _insertMessage(text) {
    this._message = this
      .append(new Item());

    this._message
      .text(text)
      .primary();

    return this;
  }

  _updateMessage(text) {
    this._message
      .part(0)
      .text(text);

    return this;
  }

  _showTitle(title) {
    this._title
      .style('display', 'flex');

    this._titleText
      .text(title);

    return this;
  }

  _hideTitle() {
    this._title
      .style('display', 'none');

    return this;
  }

  _showComment(comment) {
    this._comment
      .style('display', 'block')
      .text(comment);

    return this;
  }

  _hideComment() {
    this._comment
      .style('display', 'none');

    return this;
  }

  _insertItem(item) {
    item.first(this._items.size === 0);

    this._items.add(item);
    this._body.append(() => item.root().node());

    return item;
  }

  _deleteItem(item) {
    this._items.delete(item);
    item.root().remove();

    return item;
  }

  _bindTitle() {
    if (this._title) {
      this._title
        .classed('click', true)
        .style('cursor', 'pointer')
        .on('click.scola-list', () => this._click());
    }
  }

  _unbindTitle() {
    if (this._title) {
      this._title
        .classed('click', false)
        .style('cursor', null)
        .on('click.scola-list', null);
    }
  }

  _click() {
    if (this._model) {
      const value = this._model.get(this._name);
      this._model.set(this._name, value === false ? true : false);
    }
  }

  _set(setEvent) {
    if (setEvent.name !== this._name) {
      return;
    }

    const bodyHeight = this._body.boundingRect('height');
    const commentHeight = this._comment.boundingRect('height');
    const titleHeight = this._title.boundingRect('height');

    if (setEvent.value === true) {
      this._root.style('border', 0);
    }

    this._root
      .transition()
      .style('height', () => {
        return setEvent.value !== false ? (
          titleHeight +
          bodyHeight +
          commentHeight
        ) + 'px' : titleHeight + 'px';
      })
      .on('end', () => {
        if (this._root === null) {
          return;
        }

        if (setEvent.value !== false) {
          this._root.style('height', null);
        } else {
          this._root.style('border-bottom', '1px solid #CCC');
        }
      });

    this._titleIcon
      .transition()
      .style('transform', () => {
        return setEvent.value !== false ?
          'rotate(0deg)' :
          'rotate(-90deg)';
      });
  }
}
<|endoftext|>


<commit_before>/* eslint-disable space-before-blocks */
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueLazyload from 'vue-lazyload'

import router from './router'
import store from './store'
import App from './App.vue'

import Ads from 'vue-google-adsense'
import Simplert from 'vue2-simplert-plugin'

Vue.use(require('vue-script2'))

Vue.use(Ads.Adsense)
Vue.use(Ads.InArticleAdsense)
Vue.use(Ads.InFeedAdsense)

Vue.use(Simplert)

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'assets/images/brand.png',
  loading: 'assets/images/loading.gif',
  attempt: 1
})
if (process.env.NODE_ENV === "production") {
  require("./pwa");
} else {
  Vue.config.devtools = true
}

require("octicons/build/build.css")

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  store,
  components: {App}
})
<commit_msg>remove 404 image<commit_after>/* eslint-disable space-before-blocks */
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueLazyload from 'vue-lazyload'

import router from './router'
import store from './store'
import App from './App.vue'

import Ads from 'vue-google-adsense'
import Simplert from 'vue2-simplert-plugin'

Vue.use(require('vue-script2'))

Vue.use(Ads.Adsense)
Vue.use(Ads.InArticleAdsense)
Vue.use(Ads.InFeedAdsense)

Vue.use(Simplert)

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'assets/icons/android-icon-36x36.png',
  loading: 'assets/images/loading.gif',
  attempt: 1
})
if (process.env.NODE_ENV === "production") {
  require("./pwa");
} else {
  Vue.config.devtools = true
}

require("octicons/build/build.css")

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  store,
  components: {App}
})
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
var https = require('https');
var express = require("express");
var bodyParser = require("body-parser");
var session = require("express-session");

const databox = require('node-databox');

var twitter = require('./twitter.js');

var DATABOX_STORE_BLOB_ENDPOINT = process.env.DATABOX_DRIVER_TWITTER_STREAM_DATABOX_STORE_BLOB_ENDPOINT;

var HASH_TAGS_TO_TRACK = ['#raspberrypi', '#mozfest', '#databox', '#iot', '#NobelPrize'];
var TWITER_USER = 'databox_mozfest';

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    res.header('Content-Type', 'application/json');
    next();
};

var app = express();
app.use(session({resave: false, saveUninitialized: false,  secret: 'databox'}));
app.use(express.static('src/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(allowCrossDomain);

app.get("/status", function(req, res) {
    res.send("active");
});

app.get("/connect", twitter.connect);

app.get("/callback", twitter.auth);
app.get("/databox-driver-twitter-stream/callback", twitter.auth); //fake endpoint for debugging outside of databox

app.get("/is-signed-in", function(req, res) {
    res.end('' + twitter.isSignedIn());
});

var T = null;

var vendor = "databox";

  databox.waitForStoreStatus(DATABOX_STORE_BLOB_ENDPOINT,'active',10)
  .then(() => {

    proms = [
      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter user timeline data',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterUserTimeLine',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter hashtag data',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterHashTagStream',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter users direct messages',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterDirectMessage',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter users retweets',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterRetweet',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter users favorite tweets',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterFavorite',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Test Actuator',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'TestActuator',
        storeType: 'databox-store-blob',
        isActuator:true
      })
    ];

    return Promise.all(proms);
  })
  .then(()=>{
    console.log("[Creating server] and twitter Auth");
    https.createServer(credentials, app).listen(8080);
    return twitter.waitForTwitterAuth();
  })
  .then(()=>{

    T = twitter.Twit();
    var HashtagStream = T.stream('statuses/filter', { track: HASH_TAGS_TO_TRACK , language:'en'});
    HashtagStream.on('tweet', function (tweet) {
      save('twitterHashTagStream', tweet);
    });

    var UserStream = T.stream('user', { stringify_friend_ids: true, with: 'followings', replies:'all' });

    UserStream.on('tweet', function (event) {
      save('twitterUserTimeLine',event);
    });

    UserStream.on('favorite', function (event) {
      save('twitterFavorite',event);
    });

    UserStream.on('quoted_tweet', function (event) {
      save('twitterRetweet',event);
    });

    UserStream.on('retweeted_retweet', function (event) {
      save('twitterRetweet',event);
    });

    UserStream.on('direct_message', function (event) {
      save('twitterDirectMessage',event);
    });

  })
  .catch((err) => {
    console.log(err);
  });

module.exports = app;

function save(datasourceid,data) {
      console.log("Saving data::", datasourceid, data.text);

      databox.timeseries.write(DATABOX_STORE_BLOB_ENDPOINT, datasourceid, {'data': data})
      .catch((error)=>{
        console.log("[Error writing to store]" + error);
      });
    }<commit_msg> time series write is already wrapped in a {data: data}<commit_after>/*jshint esversion: 6 */
var https = require('https');
var express = require("express");
var bodyParser = require("body-parser");
var session = require("express-session");

const databox = require('node-databox');

var twitter = require('./twitter.js');

var DATABOX_STORE_BLOB_ENDPOINT = process.env.DATABOX_DRIVER_TWITTER_STREAM_DATABOX_STORE_BLOB_ENDPOINT;

var HASH_TAGS_TO_TRACK = ['#raspberrypi', '#mozfest', '#databox', '#iot', '#NobelPrize'];
var TWITER_USER = 'databox_mozfest';

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    res.header('Content-Type', 'application/json');
    next();
};

var app = express();
app.use(session({resave: false, saveUninitialized: false,  secret: 'databox'}));
app.use(express.static('src/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(allowCrossDomain);

app.get("/status", function(req, res) {
    res.send("active");
});

app.get("/connect", twitter.connect);

app.get("/callback", twitter.auth);
app.get("/databox-driver-twitter-stream/callback", twitter.auth); //fake endpoint for debugging outside of databox

app.get("/is-signed-in", function(req, res) {
    res.end('' + twitter.isSignedIn());
});

var T = null;

var vendor = "databox";

  databox.waitForStoreStatus(DATABOX_STORE_BLOB_ENDPOINT,'active',10)
  .then(() => {

    proms = [
      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter user timeline data',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterUserTimeLine',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter hashtag data',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterHashTagStream',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter users direct messages',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterDirectMessage',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter users retweets',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterRetweet',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Twitter users favorite tweets',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'twitterFavorite',
        storeType: 'databox-store-blob'
      }),

      databox.catalog.registerDatasource(DATABOX_STORE_BLOB_ENDPOINT, {
        description: 'Test Actuator',
        contentType: 'text/json',
        vendor: 'Databox Inc.',
        type: 'Test',
        datasourceid: 'TestActuator',
        storeType: 'databox-store-blob',
        isActuator:true
      })
    ];

    return Promise.all(proms);
  })
  .then(()=>{
    console.log("[Creating server] and twitter Auth");
    https.createServer(credentials, app).listen(8080);
    return twitter.waitForTwitterAuth();
  })
  .then(()=>{

    T = twitter.Twit();
    var HashtagStream = T.stream('statuses/filter', { track: HASH_TAGS_TO_TRACK , language:'en'});
    HashtagStream.on('tweet', function (tweet) {
      save('twitterHashTagStream', tweet);
    });

    var UserStream = T.stream('user', { stringify_friend_ids: true, with: 'followings', replies:'all' });

    UserStream.on('tweet', function (event) {
      save('twitterUserTimeLine',event);
    });

    UserStream.on('favorite', function (event) {
      save('twitterFavorite',event);
    });

    UserStream.on('quoted_tweet', function (event) {
      save('twitterRetweet',event);
    });

    UserStream.on('retweeted_retweet', function (event) {
      save('twitterRetweet',event);
    });

    UserStream.on('direct_message', function (event) {
      save('twitterDirectMessage',event);
    });

  })
  .catch((err) => {
    console.log(err);
  });

module.exports = app;

function save(datasourceid,data) {
      console.log("Saving data::", datasourceid, data.text);

      databox.timeseries.write(DATABOX_STORE_BLOB_ENDPOINT, datasourceid, data)
      .catch((error)=>{
        console.log("[Error writing to store]" + error);
      });
    }<|endoftext|>


<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
import store from './store'
import router from './router'
import * as Api from './api'
import EazyPush from './plugins/easyPush'
import ImgPreview from './plugins/imgPreview'
import Utils from './plugins/utils'
Vue.use(EazyPush, '')
Vue.use(ImgPreview)
Vue.use(Utils)
/*三方库*/

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
Vue.use(ElementUI)

import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
  error: require('./assets/img/img_empty.png'),
  loading: require('./assets/img/img_empty.png'),
  attempt: 1,
  adapter: {
    loading (listener, Init) {
      if (listener.src && listener.src.indexOf('upload') === 0) {
        listener.src = Api.config.imgHost + listener.src;
      }
    }
  }
})

import ECharts from 'vue-echarts'
Vue.component('chart', ECharts)

import 'vue-awesome/icons'
import Icon from 'vue-awesome/components/Icon'
Vue.component('icon', Icon)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
});
<commit_msg>Update main.js<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
import store from './store'
import router from './router'
import * as Api from './api'
//import EazyPush from './plugins/easyPush'
import ImgPreview from './plugins/imgPreview'
import Utils from './plugins/utils'
//Vue.use(EazyPush, '')
Vue.use(ImgPreview)
Vue.use(Utils)
/*三方库*/

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
Vue.use(ElementUI)

import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
  error: require('./assets/img/img_empty.png'),
  loading: require('./assets/img/img_empty.png'),
  attempt: 1,
  adapter: {
    loading (listener, Init) {
      if (listener.src && listener.src.indexOf('upload') === 0) {
        listener.src = Api.config.imgHost + listener.src;
      }
    }
  }
})

import ECharts from 'vue-echarts'
Vue.component('chart', ECharts)

import 'vue-awesome/icons'
import Icon from 'vue-awesome/components/Icon'
Vue.component('icon', Icon)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
});
<|endoftext|>


<commit_before>'use strict';

var mongodb = require('mongodb');
var Promise = require('bluebird');
var request = require('request');
var MongoClient = mongodb.MongoClient;
var Collection = mongodb.Collection;

Promise.promisifyAll(MongoClient);
Promise.promisifyAll(Collection.prototype);
Promise.promisifyAll(request);

module.exports = function (context, callback) {
  var mongoUrl = context.data.MONGO_URL;
  var gitHubToken = context.data.GITHUB_TOKEN;
  var body = context.body;
  var action = body.action;
  var repository = body.repository.full_name;
  var issue = body.issue;
  var user = body.comment && body.comment.user.login;
  var comment = body.comment && body.comment.body;
  var db;

  new Promise.resolve()
    .then(connect)
    .then(function () {
      if (action === 'opened') {
        return insertIssue({ issue: issue.number, repository: repository, body: issue.body });
      }
      else if (action === 'created' && /^(\+1)/.test(comment)) {
        return addUser({ issue: issue.number, repository: repository, user: user });
      }
      else if (action === 'created' && /^(-1)/.test(comment)) {
        return removeUser({ issue: issue.number, repository: repository, user: user });
      }
      else if (body.hook) {
        return;
      }
      else {
        throw new Error('invalid payload');
      }
    })
    .then(function () {
      db.close();
      callback();
    })
    .catch(function (err) {
      callback(err);
    });

  function connect() {
    return MongoClient.connectAsync(mongoUrl)
      .then(function (_db) {
        db = _db;
      });
  }

  function insertIssue(obj) {
    return db
      .collection('issues')
      .insertAsync(
        { issue: obj.issue, repository: obj.repository, body: obj.body, users: [] }
      );
  }

  function addUser(obj) {
    return db
      .collection('issues')
      .updateAsync(
        { issue: obj.issue, repository: obj.repository },
        { '$addToSet': { users: obj.user } }
      ).then(function () {
        return updateBody(obj);
      });

  }

  function removeUser(obj) {
    return db
      .collection('issues')
      .updateAsync(
        { issue: obj.issue, repository: obj.repository },
        { '$unset': { users: obj.user } }
      ).then(function () {
        return updateBody(obj);
      });
  }

  function updateBody(obj) {
    return db
      .collection('issues')
      .findOneAsync(
        { issue: obj.issue, repository: obj.repository }
      ).then(function (dbObj) {
        var usersList = (dbObj.users || [])
          .map(function (user) { return '- @' + user; })
          .join('\n');
        var usersLength = (dbObj.users || []).length;

        requestAsync(
          {
            url: 'https://api.github.com/repos/' + obj.repository + '/issues/' + obj.issue,
            headers: {
              'Content-type': 'application/json',
              'Authorization': 'token ' + gitHubToken,
              'User-Agent': 'GH-List-App'
            },
            method: 'PATCH',
            json: {
              body: dbObj.body + '\n\n' + usersLength + ' *user' + (usersLength > 1 ? 's' : '') + '*:\n' + usersList
            }
          }
        );
      });
  }

  function requestAsync(payload) {
    return new Promise(function (resolve, reject) {
      request(payload, function (err, response) {
        if (err) {
          reject(err);
          return;
        }

        resolve();
      });
    });
  }
};
<commit_msg>return the promise<commit_after>'use strict';

var mongodb = require('mongodb');
var Promise = require('bluebird');
var request = require('request');
var MongoClient = mongodb.MongoClient;
var Collection = mongodb.Collection;

Promise.promisifyAll(MongoClient);
Promise.promisifyAll(Collection.prototype);
Promise.promisifyAll(request);

module.exports = function (context, callback) {
  var mongoUrl = context.data.MONGO_URL;
  var gitHubToken = context.data.GITHUB_TOKEN;
  var body = context.body;
  var action = body.action;
  var repository = body.repository.full_name;
  var issue = body.issue;
  var user = body.comment && body.comment.user.login;
  var comment = body.comment && body.comment.body;
  var db;

  new Promise.resolve()
    .then(connect)
    .then(function () {
      if (action === 'opened') {
        return insertIssue({ issue: issue.number, repository: repository, body: issue.body });
      }
      else if (action === 'created' && /^(\+1)/.test(comment)) {
        return addUser({ issue: issue.number, repository: repository, user: user });
      }
      else if (action === 'created' && /^(-1)/.test(comment)) {
        return removeUser({ issue: issue.number, repository: repository, user: user });
      }
      else if (body.hook) {
        return;
      }
      else {
        throw new Error('invalid payload');
      }
    })
    .then(function () {
      db.close();
      callback();
    })
    .catch(function (err) {
      callback(err);
    });

  function connect() {
    return MongoClient.connectAsync(mongoUrl)
      .then(function (_db) {
        db = _db;
      });
  }

  function insertIssue(obj) {
    return db
      .collection('issues')
      .insertAsync(
        { issue: obj.issue, repository: obj.repository, body: obj.body, users: [] }
      );
  }

  function addUser(obj) {
    return db
      .collection('issues')
      .updateAsync(
        { issue: obj.issue, repository: obj.repository },
        { '$addToSet': { users: obj.user } }
      ).then(function () {
        return updateBody(obj);
      });

  }

  function removeUser(obj) {
    return db
      .collection('issues')
      .updateAsync(
        { issue: obj.issue, repository: obj.repository },
        { '$unset': { users: obj.user } }
      ).then(function () {
        return updateBody(obj);
      });
  }

  function updateBody(obj) {
    return db
      .collection('issues')
      .findOneAsync(
        { issue: obj.issue, repository: obj.repository }
      ).then(function (dbObj) {
        var usersList = (dbObj.users || [])
          .map(function (user) { return '- @' + user; })
          .join('\n');
        var usersLength = (dbObj.users || []).length;

        return requestAsync(
          {
            url: 'https://api.github.com/repos/' + obj.repository + '/issues/' + obj.issue,
            headers: {
              'Content-type': 'application/json',
              'Authorization': 'token ' + gitHubToken,
              'User-Agent': 'GH-List-App'
            },
            method: 'PATCH',
            json: {
              body: dbObj.body + '\n\n' + usersLength + ' *user' + (usersLength > 1 ? 's' : '') + '*:\n' + usersList
            }
          }
        );
      });
  }

  function requestAsync(payload) {
    return new Promise(function (resolve, reject) {
      request(payload, function (err, response) {
        if (err) {
          reject(err);
          return;
        }

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


<commit_before>// CUSTOMIZING: replace with your username and branch after forking
// Default branch is MASTER
var URL = rawGitUrl("audibleblink", null);

function rawGitUrl(ghHandle, branchName){
    branchName = branchName || "master"
    return "//rawgit.com/" + ghHandle + "/boom/" + branchName + "/lib/boom.js";
}

var js = document.createElement('script');
js.src = URL;
document.head.appendChild(js);
<commit_msg>make editing easier to see/use<commit_after>var YOUR_GH_HANDLE, GIT_BRANCH

// CUSTOMIZING: replace with your username and branch after forking
// Default branch is MASTER
YOUR_GH_HANDLE = "audibleblink";
GIT_BRANCH = null;

function rawGitUrl(ghHandle, branchName){
    branchName = branchName || "master"
    return "//rawgit.com/" + ghHandle + "/boom/" + branchName + "/lib/boom.js";
}

var js = document.createElement('script');
js.src = rawGitUrl(YOUR_GH_HANDLE, GIT_BRANCH);
document.head.appendChild(js);
<|endoftext|>