<commit_before>var fs = require('fs')
var domify = require('domify')
var tpl = fs.readFileSync(__dirname + '/dialog.html', 'utf8')
var classie = require('classie')
var oneBtn = fs.readFileSync(__dirname + '/one_button.html', 'utf8')
var twoBtn = fs.readFileSync(__dirname + '/two_button.html', 'utf8')
var key = require('keymaster')
var animEvent = require('animevent')

var Wagon = require('wagon')

module.exports = Wagon.extend({

  events: {
    'click .dialog-continue': 'continueAction',
    'click .dialog-close': 'closeAction',

    one: {
      'animationend': 'tab'
    }
  },

  initialize: function(){
    this.options.close = this.options.close || 'Cancel'
    this.render()
    this.bindKeyboardEvents()
  },

  bindKeyboardEvents: function(){
    key('tab', this.tab.bind(this))
    key('enter', this.continueAction.bind(this))
    key('esc', this.closeAction.bind(this))
  },

  remove: function(){
    key.unbind('tab, enter, esc')
    Wagon.prototype.remove.apply(this, arguments)
  },

  show: function(){
    document.body.appendChild(this.el)
    return this
  },

  tab: function(event){
    if (event){ event.preventDefault() }

    if(document.activeElement != this.closeButton) {
      this.closeButton.focus()
    } else {
      this.continueButton.focus()
    }
  },

  closeAction: function(event){
    if (event){ event.preventDefault() }
    this.closeButton.focus()
    classie.add(this.closeButton, 'active')

    this.close(function(){
      if (this.options.onDismiss) {
        this.options.onDismiss()
      }
    }.bind(this))
  },

  continueAction: function(event){
    if (event){ event.preventDefault() }

    this.continueButton.focus()
    classie.add(this.continueButton, 'active')

    this.close(function(){
      if (this.options.submit) {
        if(this.options.submit.nodeType) {
          this.options.submit.submit()
        } else {
          document.querySelector(this.options.submit).submit()
        }
      } else if (this.options.follow) {
        window.location.pathname = this.options.follow
      } if (this.options.onConfirm) {
        this.options.onConfirm()
      }
    }.bind(this))
  },

  close: function(callback){
    classie.add( this.el, 'dismiss' )
    animEvent.one(this.el, 'end', function(event) {
      if (callback) { callback() }
      this.remove()
    }.bind(this))
  },

  render: function(){
    var el = domify(tpl)

    if (this.options.continue) {
      el.querySelector('.dialog-actions').innerHTML = twoBtn
      this.continueButton = el.querySelector('.dialog-continue')

      this.continueButton.textContent = this.options.continue

      if (this.options.destructive) {
        classie.remove(this.continueButton, 'primary-btn')
        classie.add(this.continueButton, 'primary-destroy-btn')
      }
    } else {
      el.querySelector('.dialog-actions').innerHTML = oneBtn
    }

    this.closeButton = el.querySelector('.dialog-close')

    el.querySelector('.dialog-close').textContent = this.options.close

    var message = el.querySelector('.dialog-message')

    if (this.options.messageHTML) {
      message.innerHTML = this.options.messageHTML
    } else {
      if (this.options.title) {
        message.innerHTML += "
" + this.options.title + "
"
      }
      if (this.options.message) {
        message.innerHTML += "
" + this.options.message + "
"
      }
    }

    this.el = el
    return this
  }

}, {

  docEvents: {
    'click [data-trigger=dialog]': 'instantiate'
  },
  instantiate: function(event){
    event.preventDefault()
    this.show(event.target.dataset)
  },
  show: function(options){
    new this(options).show()
  }

})
<commit_msg>Added full names for wagon and animevent<commit_after>var fs = require('fs')
var domify = require('domify')
var tpl = fs.readFileSync(__dirname + '/dialog.html', 'utf8')
var classie = require('classie')
var oneBtn = fs.readFileSync(__dirname + '/one_button.html', 'utf8')
var twoBtn = fs.readFileSync(__dirname + '/two_button.html', 'utf8')
var key = require('keymaster')
var animEvent = require('compose-animevent')

var Wagon = require('compose-wagon')

module.exports = Wagon.extend({

  events: {
    'click .dialog-continue': 'continueAction',
    'click .dialog-close': 'closeAction',

    one: {
      'animationend': 'tab'
    }
  },

  initialize: function(){
    this.options.close = this.options.close || 'Cancel'
    this.render()
    this.bindKeyboardEvents()
  },

  bindKeyboardEvents: function(){
    key('tab', this.tab.bind(this))
    key('enter', this.continueAction.bind(this))
    key('esc', this.closeAction.bind(this))
  },

  remove: function(){
    key.unbind('tab, enter, esc')
    Wagon.prototype.remove.apply(this, arguments)
  },

  show: function(){
    document.body.appendChild(this.el)
    return this
  },

  tab: function(event){
    if (event){ event.preventDefault() }

    if(document.activeElement != this.closeButton) {
      this.closeButton.focus()
    } else {
      this.continueButton.focus()
    }
  },

  closeAction: function(event){
    if (event){ event.preventDefault() }
    this.closeButton.focus()
    classie.add(this.closeButton, 'active')

    this.close(function(){
      if (this.options.onDismiss) {
        this.options.onDismiss()
      }
    }.bind(this))
  },

  continueAction: function(event){
    if (event){ event.preventDefault() }

    this.continueButton.focus()
    classie.add(this.continueButton, 'active')

    this.close(function(){
      if (this.options.submit) {
        if(this.options.submit.nodeType) {
          this.options.submit.submit()
        } else {
          document.querySelector(this.options.submit).submit()
        }
      } else if (this.options.follow) {
        window.location.pathname = this.options.follow
      } if (this.options.onConfirm) {
        this.options.onConfirm()
      }
    }.bind(this))
  },

  close: function(callback){
    classie.add( this.el, 'dismiss' )
    animEvent.one(this.el, 'end', function(event) {
      if (callback) { callback() }
      this.remove()
    }.bind(this))
  },

  render: function(){
    var el = domify(tpl)

    if (this.options.continue) {
      el.querySelector('.dialog-actions').innerHTML = twoBtn
      this.continueButton = el.querySelector('.dialog-continue')

      this.continueButton.textContent = this.options.continue

      if (this.options.destructive) {
        classie.remove(this.continueButton, 'primary-btn')
        classie.add(this.continueButton, 'primary-destroy-btn')
      }
    } else {
      el.querySelector('.dialog-actions').innerHTML = oneBtn
    }

    this.closeButton = el.querySelector('.dialog-close')

    el.querySelector('.dialog-close').textContent = this.options.close

    var message = el.querySelector('.dialog-message')

    if (this.options.messageHTML) {
      message.innerHTML = this.options.messageHTML
    } else {
      if (this.options.title) {
        message.innerHTML += "
" + this.options.title + "
"
      }
      if (this.options.message) {
        message.innerHTML += "
" + this.options.message + "
"
      }
    }

    this.el = el
    return this
  }

}, {

  docEvents: {
    'click [data-trigger=dialog]': 'instantiate'
  },
  instantiate: function(event){
    event.preventDefault()
    this.show(event.target.dataset)
  },
  show: function(options){
    new this(options).show()
  }

})
<|endoftext|>


<commit_before>'use strict';

const glob = require('glob-all');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const BbPromise = require('bluebird');

const globOpts = {
  nodir: true
};

class Assets {
  constructor (serverless, options) {
    this.serverless = serverless;
    this.options = options;
    this.provider = this.serverless.getProvider('aws');

    let config = this.serverless.service.custom.assets;
    if(Array.isArray(config)) {
      config = {targets: config};
    }

    this.config = Object.assign({}, {
      auto: false,
      targets: [],
    }, config);

    this.commands = {
      s3deploy: {
        usage: 'Deploy assets to S3 bucket',
        lifecycleEvents: [
          'deploy'
        ],
        options: {
          verbose: {
            usage: 'Increase verbosity',
            shortcut: 'v'
          },
          bucket: {
            usage: 'Limit the deploy to a specific bucket',
            shortcut: 'b'
          }
        }
      }
    };

    this.hooks = {
      's3deploy:deploy': () => Promise.resolve().then(this.deployS3.bind(this)),
      'after:deploy:finalize': () => Promise.resolve().then(this.afterDeploy.bind(this))
    };
  }

  /*
   * Handy method for logging (when `verbose` is set)
   * Also log on the default serverless SLS_DEBUG env
   */
  log(message) {
    if(this.options.verbose || process.env.SLS_DEBUG) {
      this.serverless.cli.log(message);
    }
  }

  afterDeploy() {
    if(this.config.auto) {
      this.deployS3();
    }
  }

  listStackResources(resources, nextToken) {
    resources = resources || [];
    return this.provider.request('CloudFormation', 'listStackResources', { StackName: this.provider.naming.getStackName(), NextToken: nextToken })
    .then(response => {
      resources.push.apply(resources, response.StackResourceSummaries);
      if (response.NextToken) {
        // Query next page
        return this.listStackResources(resources, response.NextToken);
      }
    })
    .return(resources);
  }

  resolveBucket(resources, value) {
    if (typeof value === 'string') {
      return BbPromise.resolve(value);
    }
    else if (value && value.Ref) {
      let resolved;
      resources.forEach(resource => {
        if (resource && resource.LogicalResourceId === value.Ref) {
          resolved = resource.PhysicalResourceId;
        }
      });

      if (!resolved) {
        this.serverless.cli.log(`WARNING: Failed to resolve reference ${value.Ref}`);
      }
      return BbPromise.resolve(resolved);
    }
    else {
      return BbPromise.reject(new Error(`Invalid bucket name ${value}`));
    }
  }

  emptyBucket(bucket, dir) {
    const listParams = {
      Bucket: bucket,
      Prefix: dir
    };

    return this.provider.request('S3', 'listObjectsV2', listParams)
      .then((listedObjects) => {
        if (listedObjects.Contents.length === 0) return

        const deleteParams = {
          Bucket: bucket,
          Delete: { Objects: [] }
        };

        listedObjects.Contents.forEach(({ Key }) => {
          deleteParams.Delete.Objects.push({ Key })
        });
        return this.provider.request('S3', 'deleteObjects', deleteParams)
          .then(() => {
            if (listedObjects.Contents.IsTruncated) {
              this.log(`Is not finished. Rerun emptyBucket`)
              return this.emptyBucket(bucket, dir)
            }
          })
      });
  }

  deployS3() {
    let assetSets = this.config.targets;

    // Read existing stack resources so we can resolve references if necessary
    return this.listStackResources()
    .then(resources => {
      // Process asset sets in parallel (up to 3)
      return BbPromise.map(assetSets, assets => {
          const prefix = assets.prefix || '';
          // Try to resolve the bucket name
          return this.resolveBucket(resources, assets.bucket)
          .then((bucket) => {
            if(assets.empty) {
              this.log(`Emptying bucket`)
              return this.emptyBucket(bucket, prefix)
                .then(() => bucket)
            }
            return Promise.resolve(bucket)
          }).then(bucket => {
            // Process files serially to not overload the network
            return BbPromise.each(assets.files, (opt) => {
              this.log(`Bucket: ${bucket}:${prefix}`)

              if (this.options.bucket && this.options.bucket !== bucket) {
                this.log('Skipping')
                return
              }

              this.log(`Path: ${opt.source}`)

              const cfg = Object.assign({}, globOpts, { cwd: opt.source })
              glob.sync(opt.globs, cfg).forEach((filename) => {
                const body = fs.readFileSync(path.join(opt.source, filename))
                const type = mime.lookup(filename) || opt.defaultContentType || 'application/octet-stream'

                this.log(`\tFile:  ${filename} (${type})`);

                // when using windows path join resolves to backslashes, but s3 is expecting a slash
                // therefore replace all backslashes with slashes
                const key = path
                  .join(prefix, filename)
                  .replace(/\\/g, '/');

                const details = Object.assign(
                  {
                    ACL: assets.acl || 'public-read',
                    Body: body,
                    Bucket: bucket,
                    Key: key,
                    ContentType: type
                  },
                  opt.headers || {}
                );

                return this.provider.request('S3', 'putObject', details)
              })
            })
          })
        },
        { concurrency: 3 }
      )
    })
  }
}

module.exports = Assets;
<commit_msg>serverless quits before uploading assets (#33)<commit_after>'use strict';

const glob = require('glob-all');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const BbPromise = require('bluebird');

const globOpts = {
  nodir: true
};

class Assets {
  constructor (serverless, options) {
    this.serverless = serverless;
    this.options = options;
    this.provider = this.serverless.getProvider('aws');

    let config = this.serverless.service.custom.assets;
    if(Array.isArray(config)) {
      config = {targets: config};
    }

    this.config = Object.assign({}, {
      auto: false,
      targets: [],
    }, config);

    this.commands = {
      s3deploy: {
        usage: 'Deploy assets to S3 bucket',
        lifecycleEvents: [
          'deploy'
        ],
        options: {
          verbose: {
            usage: 'Increase verbosity',
            shortcut: 'v'
          },
          bucket: {
            usage: 'Limit the deploy to a specific bucket',
            shortcut: 'b'
          }
        }
      }
    };

    this.hooks = {
      's3deploy:deploy': () => Promise.resolve().then(this.deployS3.bind(this)),
      'after:deploy:finalize': () => Promise.resolve().then(this.afterDeploy.bind(this))
    };
  }

  /*
   * Handy method for logging (when `verbose` is set)
   * Also log on the default serverless SLS_DEBUG env
   */
  log(message) {
    if(this.options.verbose || process.env.SLS_DEBUG) {
      this.serverless.cli.log(message);
    }
  }

  afterDeploy() {
    if(this.config.auto) {
      this.deployS3();
    }
  }

  listStackResources(resources, nextToken) {
    resources = resources || [];
    return this.provider.request('CloudFormation', 'listStackResources', { StackName: this.provider.naming.getStackName(), NextToken: nextToken })
    .then(response => {
      resources.push.apply(resources, response.StackResourceSummaries);
      if (response.NextToken) {
        // Query next page
        return this.listStackResources(resources, response.NextToken);
      }
    })
    .return(resources);
  }

  resolveBucket(resources, value) {
    if (typeof value === 'string') {
      return BbPromise.resolve(value);
    }
    else if (value && value.Ref) {
      let resolved;
      resources.forEach(resource => {
        if (resource && resource.LogicalResourceId === value.Ref) {
          resolved = resource.PhysicalResourceId;
        }
      });

      if (!resolved) {
        this.serverless.cli.log(`WARNING: Failed to resolve reference ${value.Ref}`);
      }
      return BbPromise.resolve(resolved);
    }
    else {
      return BbPromise.reject(new Error(`Invalid bucket name ${value}`));
    }
  }

  emptyBucket(bucket, dir) {
    const listParams = {
      Bucket: bucket,
      Prefix: dir
    };

    return this.provider.request('S3', 'listObjectsV2', listParams)
      .then((listedObjects) => {
        if (listedObjects.Contents.length === 0) return

        const deleteParams = {
          Bucket: bucket,
          Delete: { Objects: [] }
        };

        listedObjects.Contents.forEach(({ Key }) => {
          deleteParams.Delete.Objects.push({ Key })
        });
        return this.provider.request('S3', 'deleteObjects', deleteParams)
          .then(() => {
            if (listedObjects.Contents.IsTruncated) {
              this.log(`Is not finished. Rerun emptyBucket`)
              return this.emptyBucket(bucket, dir)
            }
          })
      });
  }

  deployS3() {
    let assetSets = this.config.targets;

    // Read existing stack resources so we can resolve references if necessary
    return this.listStackResources()
    .then(resources => {
      // Process asset sets in parallel (up to 3)
      return BbPromise.map(assetSets, assets => {
          const prefix = assets.prefix || '';
          // Try to resolve the bucket name
          return this.resolveBucket(resources, assets.bucket)
          .then((bucket) => {
            if(assets.empty) {
              this.log(`Emptying bucket`)
              return this.emptyBucket(bucket, prefix)
                .then(() => bucket)
            }
            return Promise.resolve(bucket)
          }).then(bucket => {
            // Process files serially to not overload the network
            return BbPromise.each(assets.files, (opt) => {
              this.log(`Bucket: ${bucket}:${prefix}`)

              if (this.options.bucket && this.options.bucket !== bucket) {
                this.log('Skipping')
                return
              }

              this.log(`Path: ${opt.source}`)

              const cfg = Object.assign({}, globOpts, { cwd: opt.source })
              const filenames = glob.sync(opt.globs, cfg);
              return BbPromise.each(filenames, (filename) => {
                const body = fs.readFileSync(path.join(opt.source, filename))
                const type = mime.lookup(filename) || opt.defaultContentType || 'application/octet-stream'

                this.log(`\tFile:  ${filename} (${type})`);

                // when using windows path join resolves to backslashes, but s3 is expecting a slash
                // therefore replace all backslashes with slashes
                const key = path
                  .join(prefix, filename)
                  .replace(/\\/g, '/');

                const details = Object.assign(
                  {
                    ACL: assets.acl || 'public-read',
                    Body: body,
                    Bucket: bucket,
                    Key: key,
                    ContentType: type
                  },
                  opt.headers || {}
                );

                return this.provider.request('S3', 'putObject', details);
              })
            })
          })
        },
        { concurrency: 3 }
      )
    })
  }
}

module.exports = Assets;
<|endoftext|>


<commit_before>"use strict";

var _ = require('underscore');
var Article = require('substance-article');

// A contains method has been added to Strings in Javascript 1.8.6:
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/contains
if (typeof String.prototype.contains === 'undefined') {
  String.prototype.contains = function(ch) {
    return this.indexOf(ch) != -1;
  };
}

// Substance.Converter
// -------------------
//
// Converts Pandoc Input to a Substance Article

var Converter = function(input, doc_id) {
  this.input = input;
  this.doc_id = doc_id || "foo_doc";
};

Converter.Prototype = function() {

  this.output = function() {
    var doc = this.input;
    var nodesList = doc.get("content").nodes;
    var content = [];
    var offset = 0;
    var punctuations = ',.;:"';

    function getAnnotations(id){
      var anns = _.filter(doc.nodes,function(node){
      	if(_.isUndefined(node.path)){
      	  return false;
      	} else {
      	  return node.path[0] == id;
      	}
      })
      if (_.isEmpty(anns)) return false;
      return anns;
    }

    // Process nodes
    function process(node) {
      var nodeType = node.properties.type;
      if(node.properties.content){
        offset += node.properties.content.length;
      }

      function makeId(node) {
        return node.replace(/['";:,.\/?\\-]/g, '').split(' ').join('-').toLowerCase();
      }

      function processNode(node) {
        var result = [],
            annotations = getAnnotations(node.properties.id),
            currentWord = 0,
            annWord = 0;

        function processAnn(contents,type) {
          var ann = [];
          _.each(contents.split(''), function(ch, index) {
          	if(punctuations.contains(ch)) {
            	ann.push({"Str":ch});
            	annWord++
          	}
          	else if(ch == ' ') {
            	ann.push('Space');
            	annWord++
          	}
          	else {
            	if(!ann[annWord]) ann[annWord] = {'Str':''};
            	ann[annWord].Str += ch;
            	if(contents[index+1] == ' ' || punctuations.contains(contents[index + 1])) annWord++;
          	}
		    	});
		    	switch (type) {
		    	  case 'strong':
		    	    break;
		    	  case 'emphasis':
		    	    break;
		    	  default:
		    	    break;
		    	}
		    	annWord = 0;
		    	return ann;
        }

        var ranges = _.flatten(_.pluck(annotations,'range'))
        var annCounter = 0;
        var currentRange = null;
        _.each(node.properties.content.split(''), function(ch, index) {
          if(ranges.indexOf(index) != -1) {
            var ann = annotations[annCounter];
            var annContent = node.properties.content.substr(ann.range[0],ann.range[1]-ann.range[0]);
            var type = ann.type;
            var annObj = processAnn(annContent,type);
            ranges.splice(0,2);
            annCounter++;
            index += annContent.length;
            currentRange = ann.range[1];
            result.push({"Emph":annObj});
            currentWord++;
          } else {
            if(_.isNull(currentRange) || (index>=currentRange)){
              if(punctuations.contains(ch)) {
                result.push({"Str":ch});
                currentWord++;
              }
              else if(ch == ' ') {
                result.push('Space');
                currentWord++;
              }
              else {
                if(!result[currentWord]) result[currentWord] = {'Str':''};
                result[currentWord].Str += ch;
                if(node.properties.content[index+1] == ' ' || punctuations.contains(node.properties.content[index + 1]) || ranges.indexOf(index + 1) != -1) currentWord++;
              }
            }
          }
		    });
		    return result;
      }

      switch (nodeType) {
        case 'paragraph':
          var atomic = processNode(node);
          content.push({"Para":atomic});
          break;
        case 'heading':
          var atomic = processNode(node);
          var id = makeId(node.content);
          content.push({"Header":[node.properties.level,[id,[],[]],atomic]});
          break;
        case 'codeblock':
          var atomic = processNode(node);
          content.push({"Para":atomic});
          break;
        case 'image':
          break;
        case 'emphasis':
          break;
        case 'strong':
          break;
        default:
          break;
      };

    };

    _.each(nodesList, function(nodeid){
    	var node = doc.get(nodeid);
      process(node);
    });

    content = [{
      "docTitle": [],
      "docAuthors": [],
      "docDate": []
    },content];

    return content;
  };

  // Do the actual conversion
  this.convert = function() {
    var json = this.input;

    console.log('CONVERTING....', json);
    var doc_id = this.doc_id;

    // The resulting Substance Doc
    var doc = new Article({"id": this.doc_id});

    var lastid = 0,
        lastpid = 0,
        offset = 0;

    function getId() {
      lastid += 1;
      return lastid;
    }

    function getPId() {
      lastpid += 1;
      return lastpid;
    }

    var elements = json[1];
    var fragments = [];
    var offset = 0;

    var annotations = {
      "annotations": [],
      "strong": [],
      "emphasis": [],
      "inline-code": [],
      "link": [],
      "idea": [],
      "error": [],
      "question": []
    };

    // Process nodes
    function process(node) {
      var nodeType = '';
      var lastNodeId;

      // inspect element
      if(typeof node === 'object'){
        if(Array.isArray(node)) {
          _.each(node, function (subNode){
            process(subNode);
          });
        } else {
          nodeType = _.first(Object.keys(node));
        }
      } else {
        nodeType = node;
      }

      // Shared internal actions
      function processAtomic (str){
        offset += str.length;
        for (var ann in annotations) {
          annotations[ann].push(str);
        }
        fragments.push(str);
      }

      function processInline (type){
        annotations[type] = []; // reset
        var start = offset;
        var val = process(node[nodeType]);
        return val['annotations'][type];
      }

      function processBlock (item, ins) {
        fragments = []; // reset
        var res = process(item);
        return res['text'].join('');
      }

      function processSimple (item) {
        fragments = [];
        offset += item.length;
        fragments.push(item);
        return item;
      }

      function processList (type) {
        var list = '';
        _.each(node[nodeType], function (li){
          fragments = [];
          switch (type) {
            case 'bl':
              res = process(li[0]['Plain']);
              list += '* ' + res['text'].join('') + '\n';
              console.log(res['text'].join(''))
              break;

            case 'ol':
        			if(!_.isUndefined(li[0][0])){
        				res = process(li[0][0]['Plain']);
        				list += res['text'].join('') + '\n';
        			}
              break;

            case 'ul':
              res = process(li[0]['Plain']);
              list += '* ' + res['text'].join('') + '\n';
              break;
          }
        });
        return list;
      }

      // Insert node into document
      function insert (type, data, target) {
        if(type == 'paragraph') {
          var id = type+'_'+getPId();
        } else {
          var id = type+'_'+getId();
        }
        lastNodeId = id;
        // insert a new node
        var node = _.extend({
          id: id,
          type: type
        }, data);

        doc.create(node);
        doc.position("content", [id], -1);
      }

      // Proceed processing
      switch (nodeType) {

        // Atomic content
        case 'Str':
          var str = node['Str'];
          processAtomic(str);
          break;

        case 'Space':
          var str = ' ';
          processAtomic(str);
          break;

        case 'LineBreak':
          var str = '\n';
          processAtomic(str);
          break;

        // Inline content
        case 'Emph':
          var annType = 'emphasis';
          var start = offset;
          var txt = processInline(annType);
          var len = txt.length;
          insert(annType,{
          	"node": 'paragraph_' + (lastpid + 1),
            "property": "content",
            "range": [start, start + len]
          });
          break;

        case 'Strong':
          var annType = 'strong';
          var start = offset;
          var txt = processInline(annType);
          var len = txt.length;
          insert(annType,{
          	"node": 'paragraph_' + (lastpid + 1),
            "property": "content",
            "range": [start, start + len]
          });
          break;

        case 'Code':
          /*var annType = 'inline-code';
          processInline(annType);*/
          processAtomic(node[nodeType][1])
          break;

        case 'Link':
          var annType = 'link';
          var start = offset;
          var txt = processInline(annType);
          var len = txt.length;
          var url = node["Link"][1][0];
          insert(annType,{
          	"node": 'paragraph_' + (lastpid + 1),
            "property": "content",
            "range": [start, start + len],
            "url": url
          });
          break;

        // Block content
        case 'Header':
          insert ('heading', {
            "level": node[nodeType][0],
            "content": processBlock(node[nodeType][2])
          });

          break;

        case 'Para':
        case 'Plain':
          insert ('paragraph', {
            "content": processBlock(node[nodeType])
          });
          break;

        case 'OrderedList':
          insert ('paragraph', {
            "subtype": "ol",
            "content": processList('ol')
          });
          break;

        case 'UnorderedList':
          insert ('paragraph', {
            "subtype": "ul",
            "content": processList('ul')
          });
          break;

        case 'BulletList':
          insert ('paragraph', {
            "subtype": "bl",
            "content": processList('bl')
          });
          break;

        case 'RawBlock':
        case 'CodeBlock':
          insert ('codeblock', {
            "lang": node[nodeType][0][1][0],
            "content": processSimple(node[nodeType][1])
          }, ["figures", "back"]);
          break;

        case 'BlockQuote':
          // Find out why Para and if it always appears or further functionalities for BlockQuotes
          // Needs nodetype in the Document
          // insert ('codeblock', {
          //   "subtype": "blocQuote",
          //   "content": processBlock(node[nodeType][0]['Para'])
          // });
          break;

        case 'HorizontalRule':
          // for now we fake HR
          // should we skip it all the way?
          // offset += 1;
          // insert ('text', {
          //   "content": '------'
          // });
          break;

        case 'Image':
          // var alt = process(node[nodeType][0]);
          fragments = []; // reset
          var res = process(node[nodeType][0]);
          var alt = res['text'].join('');
          var url = node[nodeType][1][0];
          var title = node[nodeType][1][1];

          insert('image', {
                    "alt": alt,
                    "title": title,
                    "url": url
          });
          break;

        default:
          // if(nodeType.length > 1)
          break;

      }
      return {"text": fragments, "annotations": annotations};
    }

    _.each(elements, function (n) {
      process(n);
    });

    return doc;
  };
};

Converter.prototype = new Converter.Prototype();

module.exports = Converter;<commit_msg>CodeBlock added<commit_after>"use strict";

var _ = require('underscore');
var Article = require('substance-article');

// A contains method has been added to Strings in Javascript 1.8.6:
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/contains
if (typeof String.prototype.contains === 'undefined') {
  String.prototype.contains = function(ch) {
    return this.indexOf(ch) != -1;
  };
}

// Substance.Converter
// -------------------
//
// Converts Pandoc Input to a Substance Article

var Converter = function(input, doc_id) {
  this.input = input;
  this.doc_id = doc_id || "foo_doc";
};

Converter.Prototype = function() {

  this.output = function() {
    var doc = this.input;
    var nodesList = doc.get("content").nodes;
    var content = [];
    var offset = 0;
    var punctuations = ',.;:"';

    function getAnnotations(id){
      var anns = _.filter(doc.nodes,function(node){
      	if(_.isUndefined(node.path)){
      	  return false;
      	} else {
      	  return node.path[0] == id;
      	}
      })
      if (_.isEmpty(anns)) return false;
      return anns;
    }

    // Process nodes
    function process(node) {
      var nodeType = node.properties.type;
      if(node.properties.content){
        offset += node.properties.content.length;
      }

      function makeId(node) {
        return node.replace(/['";:,.\/?\\-]/g, '').split(' ').join('-').toLowerCase();
      }

      function processNode(node) {
        var result = [],
            annotations = getAnnotations(node.properties.id),
            currentWord = 0,
            annWord = 0;

        function processAnn(contents,type) {
          var ann = [];
          _.each(contents.split(''), function(ch, index) {
          	if(punctuations.contains(ch)) {
            	ann.push({"Str":ch});
            	annWord++
          	}
          	else if(ch == ' ') {
            	ann.push('Space');
            	annWord++
          	}
          	else {
            	if(!ann[annWord]) ann[annWord] = {'Str':''};
            	ann[annWord].Str += ch;
            	if(contents[index+1] == ' ' || punctuations.contains(contents[index + 1])) annWord++;
          	}
		    	});
		    	switch (type) {
		    	  case 'strong':
		    	    break;
		    	  case 'emphasis':
		    	    break;
		    	  default:
		    	    break;
		    	}
		    	annWord = 0;
		    	return ann;
        }

        var ranges = _.flatten(_.pluck(annotations,'range'))
        var annCounter = 0;
        var currentRange = null;
        _.each(node.properties.content.split(''), function(ch, index) {
          if(ranges.indexOf(index) != -1) {
            var ann = annotations[annCounter];
            var annContent = node.properties.content.substr(ann.range[0],ann.range[1]-ann.range[0]);
            var type = ann.type;
            var annObj = processAnn(annContent,type);
            ranges.splice(0,2);
            annCounter++;
            index += annContent.length;
            currentRange = ann.range[1];
            result.push({"Emph":annObj});
            currentWord++;
          } else {
            if(_.isNull(currentRange) || (index>=currentRange)){
              if(punctuations.contains(ch)) {
                result.push({"Str":ch});
                currentWord++;
              }
              else if(ch == ' ') {
                result.push('Space');
                currentWord++;
              }
              else {
                if(!result[currentWord]) result[currentWord] = {'Str':''};
                result[currentWord].Str += ch;
                if(node.properties.content[index+1] == ' ' || punctuations.contains(node.properties.content[index + 1]) || ranges.indexOf(index + 1) != -1) currentWord++;
              }
            }
          }
		    });
		    return result;
      }

      switch (nodeType) {
        case 'paragraph':
          var atomic = processNode(node);
          content.push({"Para":atomic});
          break;
        case 'heading':
          var atomic = processNode(node);
          var id = makeId(node.content);
          content.push({"Header":[node.properties.level,[id,[],[]],atomic]});
          break;
        case 'codeblock':
          var atomic = processNode(node);
          content.push({"CodeBlock":[["",[],[]],node.properties.content]});
          break;
        case 'image':
          break;
        case 'emphasis':
          break;
        case 'strong':
          break;
        default:
          break;
      };

    };

    _.each(nodesList, function(nodeid){
    	var node = doc.get(nodeid);
      process(node);
    });

    content = [{
      "docTitle": [],
      "docAuthors": [],
      "docDate": []
    },content];

    return content;
  };

  // Do the actual conversion
  this.convert = function() {
    var json = this.input;

    console.log('CONVERTING....', json);
    var doc_id = this.doc_id;

    // The resulting Substance Doc
    var doc = new Article({"id": this.doc_id});

    var lastid = 0,
        lastpid = 0,
        offset = 0;

    function getId() {
      lastid += 1;
      return lastid;
    }

    function getPId() {
      lastpid += 1;
      return lastpid;
    }

    var elements = json[1];
    var fragments = [];
    var offset = 0;

    var annotations = {
      "annotations": [],
      "strong": [],
      "emphasis": [],
      "inline-code": [],
      "link": [],
      "idea": [],
      "error": [],
      "question": []
    };

    // Process nodes
    function process(node) {
      var nodeType = '';
      var lastNodeId;

      // inspect element
      if(typeof node === 'object'){
        if(Array.isArray(node)) {
          _.each(node, function (subNode){
            process(subNode);
          });
        } else {
          nodeType = _.first(Object.keys(node));
        }
      } else {
        nodeType = node;
      }

      // Shared internal actions
      function processAtomic (str){
        offset += str.length;
        for (var ann in annotations) {
          annotations[ann].push(str);
        }
        fragments.push(str);
      }

      function processInline (type){
        annotations[type] = []; // reset
        var start = offset;
        var val = process(node[nodeType]);
        return val['annotations'][type];
      }

      function processBlock (item, ins) {
        fragments = []; // reset
        var res = process(item);
        return res['text'].join('');
      }

      function processSimple (item) {
        fragments = [];
        offset += item.length;
        fragments.push(item);
        return item;
      }

      function processList (type) {
        var list = '';
        _.each(node[nodeType], function (li){
          fragments = [];
          switch (type) {
            case 'bl':
              res = process(li[0]['Plain']);
              list += '* ' + res['text'].join('') + '\n';
              console.log(res['text'].join(''))
              break;

            case 'ol':
        			if(!_.isUndefined(li[0][0])){
        				res = process(li[0][0]['Plain']);
        				list += res['text'].join('') + '\n';
        			}
              break;

            case 'ul':
              res = process(li[0]['Plain']);
              list += '* ' + res['text'].join('') + '\n';
              break;
          }
        });
        return list;
      }

      // Insert node into document
      function insert (type, data, target) {
        if(type == 'paragraph') {
          var id = type+'_'+getPId();
        } else {
          var id = type+'_'+getId();
        }
        lastNodeId = id;
        // insert a new node
        var node = _.extend({
          id: id,
          type: type
        }, data);

        doc.create(node);
        doc.position("content", [id], -1);
      }

      // Proceed processing
      switch (nodeType) {

        // Atomic content
        case 'Str':
          var str = node['Str'];
          processAtomic(str);
          break;

        case 'Space':
          var str = ' ';
          processAtomic(str);
          break;

        case 'LineBreak':
          var str = '\n';
          processAtomic(str);
          break;

        // Inline content
        case 'Emph':
          var annType = 'emphasis';
          var start = offset;
          var txt = processInline(annType);
          var len = txt.length;
          insert(annType,{
          	"node": 'paragraph_' + (lastpid + 1),
            "property": "content",
            "range": [start, start + len]
          });
          break;

        case 'Strong':
          var annType = 'strong';
          var start = offset;
          var txt = processInline(annType);
          var len = txt.length;
          insert(annType,{
          	"node": 'paragraph_' + (lastpid + 1),
            "property": "content",
            "range": [start, start + len]
          });
          break;

        case 'Code':
          /*var annType = 'inline-code';
          processInline(annType);*/
          processAtomic(node[nodeType][1])
          break;

        case 'Link':
          var annType = 'link';
          var start = offset;
          var txt = processInline(annType);
          var len = txt.length;
          var url = node["Link"][1][0];
          insert(annType,{
          	"node": 'paragraph_' + (lastpid + 1),
            "property": "content",
            "range": [start, start + len],
            "url": url
          });
          break;

        // Block content
        case 'Header':
          insert ('heading', {
            "level": node[nodeType][0],
            "content": processBlock(node[nodeType][2])
          });

          break;

        case 'Para':
        case 'Plain':
          insert ('paragraph', {
            "content": processBlock(node[nodeType])
          });
          break;

        case 'OrderedList':
          insert ('paragraph', {
            "subtype": "ol",
            "content": processList('ol')
          });
          break;

        case 'UnorderedList':
          insert ('paragraph', {
            "subtype": "ul",
            "content": processList('ul')
          });
          break;

        case 'BulletList':
          insert ('paragraph', {
            "subtype": "bl",
            "content": processList('bl')
          });
          break;

        case 'RawBlock':
        case 'CodeBlock':
          insert ('codeblock', {
            "lang": node[nodeType][0][1][0],
            "content": processSimple(node[nodeType][1])
          }, ["figures", "back"]);
          break;

        case 'BlockQuote':
          // Find out why Para and if it always appears or further functionalities for BlockQuotes
          // Needs nodetype in the Document
          // insert ('codeblock', {
          //   "subtype": "blocQuote",
          //   "content": processBlock(node[nodeType][0]['Para'])
          // });
          break;

        case 'HorizontalRule':
          // for now we fake HR
          // should we skip it all the way?
          // offset += 1;
          // insert ('text', {
          //   "content": '------'
          // });
          break;

        case 'Image':
          // var alt = process(node[nodeType][0]);
          fragments = []; // reset
          var res = process(node[nodeType][0]);
          var alt = res['text'].join('');
          var url = node[nodeType][1][0];
          var title = node[nodeType][1][1];

          insert('image', {
                    "alt": alt,
                    "title": title,
                    "url": url
          });
          break;

        default:
          // if(nodeType.length > 1)
          break;

      }
      return {"text": fragments, "annotations": annotations};
    }

    _.each(elements, function (n) {
      process(n);
    });

    return doc;
  };
};

Converter.prototype = new Converter.Prototype();

module.exports = Converter;<|endoftext|>


<commit_before>'use strict';

var util = require('./lib/util');

exports = module.exports = Parth;

function Parth(){
  if(this instanceof Parth){
    this.regex = [];
    this.store = {children: {}};
    this.regex.master = /(?:[])/;
    return this;
  }
  return new Parth();
}

// ## parth.add(path)
// > path to regex classification
// > TODO: give support for regexp input
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// returns
//  - null for non-supported types
//  - regular expression from the path
//
var paramRE = /(^|\W)\:([^(?#/.: ]+)(\([^)]*?\)+)?/g;

Parth.prototype.add = function(path, opt){
  var o = util.boil(path, opt); if(!o){ return null; }

  if(this.store.children[o.path]){
    return this.store.children[o.path].regex;
  }

  var sep, def = 0, parsed = '^' +
    o.path.replace(/\S+/g, function(stem){
      sep = (stem.match(/\//) || stem.match(/\./) || ' ')[0].trim();
      return stem.replace(paramRE, function($0, $1, $2, $3){
        if(!$3){ def++; }
        return $1 + ($3 || '([^'+sep+' ]+)');
      });
      // now escape separation tokens outside parens
    }).replace(/(.*?)(?:\(.+?\)+|$)/g, function($0, $1){
      return $0.replace($1, util.escapeRegExp);
    }) + '(?:[ ]|$)';

  parsed = new RegExp(parsed);
  // attach some metadata before pushing
  parsed.path = o.path;
  parsed.depth = util.boil.argv(o.path).length;
  parsed.def = def;
  parsed.cus = (o.path.match(/\(.*?\)+/g) || []).length;

  this.regex.push(parsed);

  // ## order regexes according to
  // - raw paths (no params) go first
  // - custom regexes before defaults
  //
  // NOTE: if the diff results 0
  // paths are compared by their length
  // taking into account the number of custom regexes

  this.regex.sort(function(x, y){
    var depthDiff = y.depth - x.depth;
    if(depthDiff){ return depthDiff; }
    return (x.def + x.cus - y.def - y.cus) || (y.path.length - x.path.length);
  });

  // ## sum up all learned
  // - void groups all groups first
  // - make a giant regex

  this.regex.master = new RegExp(
    '(' + this.regex.map(util.voidRE).join(')|(') + ')'
  );

  this.store.children[o.path] = o;
  Object.defineProperty(o, 'regex', {value: parsed});
  return parsed;
};

// ## parth.match(path[, options])
// > take a string or array, return the matching path
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// return
//  - null for non-supported types or not matching path
//  - regex with for the matching path
//
Parth.prototype.match = function(path, opt){
  var o = util.boil(path, opt); if(!o){ return null; }

  o.notFound = true;
  var found = this.regex.master.exec(o.path);
  if(!found){ return null; }

  o.match = found[0].trim();
  var regex = this.regex[found.indexOf(found.shift())];
  if(!opt){ return regex; }

  var index = -1;
  o.params = {_: o.path.match(regex).slice(1)};
  regex.path.replace(paramRE, function($0, $1, $2){
    o.params[$2] = o.params._[++index];
    o.params._[index] = $2;
  });

  o.notFound = o.path.replace(o.match, '') || false;
  return regex;
};
<commit_msg>define the store first<commit_after>'use strict';

var util = require('./lib/util');

exports = module.exports = Parth;

function Parth(){
  if(this instanceof Parth){
    this.store = {children: {}};
    this.regex = []; this.regex.master = /(?:[])/;
    return this;
  }
  return new Parth();
}

// ## parth.add(path)
// > path to regex classification
// > TODO: give support for regexp input
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// returns
//  - null for non-supported types
//  - regular expression from the path
//
var paramRE = /(^|\W)\:([^(?#/.: ]+)(\([^)]*?\)+)?/g;

Parth.prototype.add = function(path, opt){
  var o = util.boil(path, opt); if(!o){ return null; }

  if(this.store.children[o.path]){
    return this.store.children[o.path].regex;
  }

  var sep, def = 0, parsed = '^' +
    o.path.replace(/\S+/g, function(stem){
      sep = (stem.match(/\//) || stem.match(/\./) || ' ')[0].trim();
      return stem.replace(paramRE, function($0, $1, $2, $3){
        if(!$3){ def++; }
        return $1 + ($3 || '([^'+sep+' ]+)');
      });
      // now escape separation tokens outside parens
    }).replace(/(.*?)(?:\(.+?\)+|$)/g, function($0, $1){
      return $0.replace($1, util.escapeRegExp);
    }) + '(?:[ ]|$)';

  parsed = new RegExp(parsed);
  // attach some metadata before pushing
  parsed.path = o.path;
  parsed.depth = util.boil.argv(o.path).length;
  parsed.def = def;
  parsed.cus = (o.path.match(/\(.*?\)+/g) || []).length;

  this.regex.push(parsed);

  // ## order regexes according to
  // - raw paths (no params) go first
  // - custom regexes before defaults
  //
  // NOTE: if the diff results 0
  // paths are compared by their length
  // taking into account the number of custom regexes

  this.regex.sort(function(x, y){
    var depthDiff = y.depth - x.depth;
    if(depthDiff){ return depthDiff; }
    return (x.def + x.cus - y.def - y.cus) || (y.path.length - x.path.length);
  });

  // ## sum up all learned
  // - void groups all groups first
  // - make a giant regex

  this.regex.master = new RegExp(
    '(' + this.regex.map(util.voidRE).join(')|(') + ')'
  );

  this.store.children[o.path] = o;
  Object.defineProperty(o, 'regex', {value: parsed});
  return parsed;
};

// ## parth.match(path[, options])
// > take a string or array, return the matching path
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// return
//  - null for non-supported types or not matching path
//  - regex with for the matching path
//
Parth.prototype.match = function(path, opt){
  var o = util.boil(path, opt); if(!o){ return null; }

  o.notFound = true;
  var found = this.regex.master.exec(o.path);
  if(!found){ return null; }

  o.match = found[0].trim();
  var regex = this.regex[found.indexOf(found.shift())];
  if(!opt){ return regex; }

  var index = -1;
  o.params = {_: o.path.match(regex).slice(1)};
  regex.path.replace(paramRE, function($0, $1, $2){
    o.params[$2] = o.params._[++index];
    o.params._[index] = $2;
  });

  o.notFound = o.path.replace(o.match, '') || false;
  return regex;
};
<|endoftext|>


<commit_before><commit_msg>Export SocketModel class as package entry.<commit_after>/* jshint node:true */

'use strict';

module.exports = require('./lib/socket.model');
<|endoftext|>


<commit_before>/**
 * @author bhouston / http://exocortex.com
 */

THREE.Box3 = function ( min, max ) {

	if( min == undefined && max === undefined ) {

		this.min = new THREE.Vector3();
		this.max = new THREE.Vector3();
		this.min.x = this.min.y = this.min.z = Infinity;
		this.max.x = this.max.y = this.max.z = -Infinity;
		console.log( this );

	} else {

		this.min = min || new THREE.Vector3();
		this.max = max || new THREE.Vector3().copy( this.min ); // This is done on purpose so you can make a box using a single point and then expand it.
	}
};

THREE.Box3.prototype = {

	constructor: THREE.Box3,

	set: function ( min, max ) {

		this.min = min;
		this.max = max;

		return this;

	},

	setFromPoints: function ( points ) {

		if ( points.length > 0 ) {

			var p = points[ 0 ];

			this.min.copy( p );
			this.max.copy( p );

			for ( var i = 1, il = points.length; i < il; i ++ ) {

				p = points[ i ];

				if ( p.x < this.min.x ) {

					this.min.x = p.x;

				} else if ( p.x > this.max.x ) {

					this.max.x = p.x;

				}

				if ( p.y < this.min.y ) {

					this.min.y = p.y;

				} else if ( p.y > this.max.y ) {

					this.max.y = p.y;

				}

				if ( p.z < this.min.z ) {

					this.min.z = p.z;

				} else if ( p.z > this.max.z ) {

					this.max.z = p.z;

				}

			}

		} else {

			this.makeEmpty();

		}

		return this;
	},

	setFromCenterAndSize: function ( center, size ) {

		var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );

		this.min.copy( center ).subSelf( halfSize );
		this.max.copy( center ).addSelf( halfSize );

		return this;

	},

	copy: function ( box ) {

		this.min.copy( box.min );
		this.max.copy( box.max );

		return this;

	},

	makeEmpty: function () {

		this.min.x = this.min.y = this.min.z = Infinity;
		this.max.x = this.max.y = this.max.z = -Infinity;

		return this;

	},

	empty: function () {

		// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
		return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );

	},

	volume: function () {

		return ( this.max.x - this.min.x ) * ( this.max.y - this.min.y ) * ( this.max.z - this.min.z );

	},

	center: function () {

		return new THREE.Vector3().add( this.min, this.max ).multiplyScalar( 0.5 );

	},

	size: function () {

		return new THREE.Vector3().sub( this.max, this.min );

	},

	expandByPoint: function ( point ) {

		this.min.minSelf( point );
		this.max.maxSelf( point );

		return this;

	},

	expandByVector: function ( vector ) {

		this.min.subSelf( vector );
		this.max.addSelf( vector );

		return this;

	},

	expandByScalar: function ( scalar ) {

		this.min.addScalar( -scalar );
		this.max.addScalar( scalar );

		return this;

	},

	containsPoint: function ( point ) {

		if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
			( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
			( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {

			return true;

		}

		return false;

	},

	containsBox: function ( box ) {

		if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
			( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
			( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {

			return true;

		}

		return false;

	},

	getParameter: function ( point ) {

		// This can potentially have a divide by zero if the box
		// has a size dimension of 0.
		return new THREE.Vector3(
			( point.x - this.min.x ) / ( this.max.x - this.min.x ),
			( point.y - this.min.y ) / ( this.max.y - this.min.y ),
			( point.z - this.min.z ) / ( this.max.z - this.min.z )
		);

	},

	isIntersection: function ( box ) {

		// using 6 splitting planes to rule out intersections.

		if ( ( this.max.x < box.min.x ) || ( box.min.x > this.max.x ) ||
			( this.max.y < box.min.y ) || ( box.min.y > this.max.y ) ||
			( this.max.z < box.min.z ) || ( box.min.z > this.max.z ) ) {

			return false;

		}

		return true;

	},

	clampPoint: function ( point ) {

		return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );

	},

	distanceToPoint: function ( point ) {

		return this.clampPoint( point ).subSelf( point ).length();

	},

	intersect: function ( box ) {

		this.min.maxSelf( box.min );
		this.max.minSelf( box.max );

		return this;

	},

	union: function ( box ) {

		this.min.minSelf( box.min );
		this.max.maxSelf( box.max );

		return this;

	},

	translate: function ( offset ) {

		this.min.addSelf( offset );
		this.max.addSelf( offset );

		return this;

	},

	scale: function ( factor ) {

		var sizeDeltaHalf = this.size().multiplyScalar( ( 1 - factor )  * 0.5 );
		this.expandByVector( sizeDeltaHalf );

		return this;

	},

	equals: function ( box ) {

		return box.min.equals( this.min ) && box.max.equals( this.max );

	},

	clone: function () {

		return new THREE.Box3().copy( this );

	}

};

THREE.Box3.__v1 = new THREE.Vector3();
<commit_msg>Merging with @bhouston branch.<commit_after>/**
 * @author bhouston / http://exocortex.com
 */

THREE.Box3 = function ( min, max ) {

	if( ! min && ! max ) {
		this.min = new THREE.Vector3();
		this.max = new THREE.Vector3();
		this.makeEmpty();
	}
	else {
		this.min = min || new THREE.Vector3();
		this.max = max || new THREE.Vector3().copy( this.min );		// This is done on purpose so you can make a box using a single point and then expand it.
	}
};

THREE.Box3.prototype = {

	constructor: THREE.Box3,

	set: function ( min, max ) {

		this.min = min;
		this.max = max;

		return this;
	},

	setFromPoints: function ( points ) {

		if( points.length > 0 ) {

			var p = points[0];
			this.min.copy( p );
			this.max.copy( p );

			for( var i = 1, numPoints = points.length; i < numPoints; i ++ ) {

				p = points[ v ];

				if ( p.x < this.min.x ) {
					this.min.x = p.x;
				}
				else if ( p.x > this.max.x ) {
					this.max.x = p.x;
				}

				if ( p.y < this.min.y ) {
					this.min.y = p.y;
				}
				else if ( p.y > this.max.y ) {
					this.max.y = p.y;
				}

				if ( p.z < this.min.z ) {
					this.min.z = p.z;
				}
				else if ( p.z > this.max.z ) {
					this.max.z = p.z;
				}
			}
		}
		else {
			this.makeEmpty();
		}

		return this;
	},

	setFromCenterAndSize: function ( center, size ) {

		var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
		this.min.copy( center ).subSelf( halfSize );
		this.max.copy( center ).addSelf( halfSize );

		return box;
	},

	copy: function ( box ) {

		this.min.copy( box.min );
		this.max.copy( box.max );

		return this;
	},

	makeEmpty: function () {

		this.min.x = this.min.y = this.min.z = Infinity;
		this.max.x = this.max.y = this.max.z = -Infinity;

		return this;
	},

	empty: function () {

		// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
		return
			( this.max.x < this.min.x ) ||
			( this.max.y < this.min.y ) ||
			( this.max.z < this.min.z );
	},

	volume: function () {

		return
			( this.max.x - this.min.x ) *
			( this.max.y - this.min.y ) *
			( this.max.z - this.min.z );
	},

	center: function () {

		return new THREE.Vector3().add( this.min, this.max ).multiplyScalar( 0.5 );
	},

	size: function () {

		return new THREE.Vector3().sub( this.max, this.min );
	},

	expandByPoint: function ( point ) {

		this.min.minSelf( point );
		this.max.maxSelf( point );

		return this;
	},

	expandByVector: function ( vector ) {

		this.min.subSelf( vector );
		this.max.addSelf( vector );

		return this;
	},

	expandByScalar: function ( scalar ) {

		this.min.addScalar( -scalar );
		this.max.addScalar( scalar );

		return this;
	},

	containsPoint: function ( point ) {
		if(
			( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
			( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
			( this.min.z <= point.z ) && ( point.z <= this.max.z )
			) {
			return true;
		}
		return false;
	},

	containsBox: function ( box ) {
		if(
			( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
			( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
			( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z )
			) {
			return true;
		}
		return false;
	},

	getParameter: function ( point ) {
		// This can potentially have a divide by zero if the box
		// has a size dimension of 0.
		return new THREE.Vector3(
			( point.x - this.min.x ) / ( this.max.x - this.min.x ),
			( point.y - this.min.y ) / ( this.max.y - this.min.y ),
			( point.z - this.min.z ) / ( this.max.z - this.min.z )
			);
	},

	clampPoint: function ( point ) {

		return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );
	},

	distanceToPoint: function ( point ) {

		return this.clampPoint( point ).subSelf( point ).length();
	},

	isIntersection: function ( box ) {
		// using 6 splitting planes to rule out intersections.
		if(
			( this.max.x < box.min.x ) || ( box.min.x > this.max.x ) ||
			( this.max.y < box.min.y ) || ( box.min.y > this.max.y ) ||
			( this.max.z < box.min.z ) || ( box.min.z > this.max.z )
			) {
			return false;
		}
		return true;
	},

	intersect: function ( box ) {

		this.min.maxSelf( box.min );
		this.max.minSelf( box.max );

		return this;
	},

	union: function ( box ) {

		this.min.minSelf( box.min );
		this.max.maxSelf( box.max );

		return this;
	},

	translate: function ( offset ) {

		this.min.addSelf( offset );
		this.max.addSelf( offset );

		return this;
	},

	scale: function ( factor ) {

		var sizeDeltaHalf = this.size().multiplyScalar( ( 1 - factor )  * 0.5 );
		this.expandByVector( sizeDeltaHalf );

		return this;
	},

	equals: function ( box ) {

		return box.min.equals( this.min ) && box.max.equals( this.max );

	},

	clone: function () {

		return new THREE.Box3().copy( this );

	}

};

THREE.Box3.__v1 = new THREE.Vector3();<|endoftext|>


<commit_before>'use strict';
var got = require('got');
var objectAssign = require('object-assign');

function ghGot(path, opts, cb) {
	if (!path) {
		throw new Error('path required');
	}

	if (typeof opts !== 'object') {
		cb = opts;
		opts = {};
	}

	cb = cb || function () {};
	opts = objectAssign({}, opts, {json: true});

	opts.headers = objectAssign({
		'accept': 'application/vnd.github.v3+json',
		'content-length': 0,
		'user-agent': 'https://github.com/sindresorhus/gh-got'
	}, opts.headers);

	var env = process.env;
	var token = env.GITHUB_TOKEN || opts.token;

	if (token) {
		opts.headers['authorization'] = 'token ' + token;
	}

	var endpoint = env.GITHUB_ENDPOINT ? env.GITHUB_ENDPOINT.replace(/[^/]$/, '$&/') : 'https://api.github.com/';
	var url = endpoint + path;

	return got(url, opts, cb);
};

[
	'get',
	'post',
	'put',
	'patch',
	'head',
	'delete'
].forEach(function (el) {
	ghGot[el] = function (url, opts, cb) {
		return ghGot(url, objectAssign({}, opts, {method: el.toUpperCase()}), cb);
	};
});

module.exports = ghGot;
<commit_msg>add opts.endpoint option<commit_after>'use strict';
var got = require('got');
var objectAssign = require('object-assign');

function ghGot(path, opts, cb) {
	if (!path) {
		throw new Error('path required');
	}

	if (typeof opts !== 'object') {
		cb = opts;
		opts = {};
	}

	cb = cb || function () {};
	opts = objectAssign({}, opts, {json: true});

	opts.headers = objectAssign({
		'accept': 'application/vnd.github.v3+json',
		'content-length': 0,
		'user-agent': 'https://github.com/sindresorhus/gh-got'
	}, opts.headers);

	var env = process.env;
	var token = env.GITHUB_TOKEN || opts.token;

	if (token) {
		opts.headers['authorization'] = 'token ' + token;
	}

	var endpoint = env.GITHUB_ENDPOINT ? env.GITHUB_ENDPOINT.replace(/[^/]$/, '$&/') : opts.endpoint;
	var url = (endpoint ? endpoint : 'https://api.github.com/') + path;

	return got(url, opts, cb);
};

[
	'get',
	'post',
	'put',
	'patch',
	'head',
	'delete'
].forEach(function (el) {
	ghGot[el] = function (url, opts, cb) {
		return ghGot(url, objectAssign({}, opts, {method: el.toUpperCase()}), cb);
	};
});

module.exports = ghGot;
<|endoftext|>


<commit_before>// Inizializziamo i componenti dell'applicazione
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
var mongodb = require('mongodb');

// Wit
var Wit = require('node-wit').Wit;
var log = require('node-wit').log;
var WIT_ACCESS_TOKEN = process.env.WIT_ACCESS_TOKEN;

// Connettiamoci a MongoDB.
var MongoClient = mongodb.MongoClient;

// URL precedentemente salvato dal plugin mlab.
var url = process.env.MONGODB_URI;

// Connessione al server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Impossibile connettersi. Errore:', err);
  } else {
    // Siamo connessi! :)
    console.log('Connessione stabilita con: ', url);

    // Qui eseguiremo il nostro codice...

    db.close();
  }
});

// La cartella per i file statici
app.use(express.static('public'));

// Impostiamo bodyparser che ci permetterà di interpretare messaggi e confezionare payload
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// L'applicazione sarà in ascolto sulla porta 3000 o su una porta predefinita dal server
app.listen((process.env.PORT || 3000));

// Homepage
app.get('/', function (req, res) {
    res.send('
Questo è hotelbot
');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'ciao_io_programmo_sono_hotelbot') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Token non valido');
    }
});

// Gestione degli eventi
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {
            sendMessageToWit(event.sender.id, event);
            //evaluateCommand(event.sender.id, event.message.text);
        } else if (event.postback) {
            // Abbiamo ricevuto una postback
        } else if (event.message && event.message.attachments) {
            // Gestione degli allegati
            sendTextMessage(event.sender.id, "Mi spiace, non posso gestire allegati!");
        }
    }
    res.sendStatus(200);
});

// Invia un messaggio di testo
function sendTextMessage(recipientId, text) {
    var msg = {
        "text": text
    };
    sendMessage(recipientId, msg)
}

// Invia messaggio multimediale
function sendMultimediaMessage(recipientId, type, url) {
    var msg = {
        "attachment": {
            "type": type,
            "payload": {
                "url": url
            }
        }
    };

    sendMessage(recipientId, msg);
}

// Invia un messaggio generico
function sendMessage(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.7/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Errore nella spedizione del messaggio: ', error);
        } else if (response.body.error) {
            console.log('Errore: ', response.body.error);
        }
    });
};

// Gestione dei comandi
function evaluateCommand(recipientId, text) {
    command = text.toLowerCase();
    console.log("Comando ricevuto: " + command);
}

// Codice per wit.ai
function sendMessageToWit(recipientId, event) {

  const sessionId = findOrCreateSession(recipientId);
  const {
      text,
      attachments
  } = event.message;

  // Inviamo i messaggi a Wit.ai
  // Eseguiamo le azioni fino a quando non abbiamo più niente da eseguire
  wit.runActions(
      sessionId, // sessione utente
      text, // messaggio
      sessions[sessionId].context // context sessione utente
  ).then((context) => {
        console.log('Azioni...');
        // Ok, abbiamo fatto tutto.
        // Aspettiamo nuovi messaggi.
        console.log('Aspettiamo nuovi messaggi...');

        // Updating the user's current session state
        sessions[sessionId].context = context;
      })
      .catch((err) => {
        var reply = "Mi spiace, non riesco a capirti... :-(";
        sendTextMessage(recipientId, reply);
        console.error('Oops! C\'è stato un problema! ', err.stack || err);
      })

}

const sessions = {};

const findOrCreateSession = (fbid) => {
    let sessionId;
    // Controlliamo se abbiamo una sessione utente
    Object.keys(sessions).forEach(k => {
        if (sessions[k].fbid === fbid) {
        // Eccolo
        sessionId = k;
    }
});
if (!sessionId) {
    // Sessione non trovata, ne creiamo una nuova
    sessionId = new Date().toISOString();
    sessions[sessionId] = {
        fbid: fbid,
        context: {}
    };
}
return sessionId;
};

// Le azioni del nostro bot
const actions = {
    send({
        sessionId
    }, {
        text
    }) {
    // Il nostro bot ha qualcosa da dire!
    // Recuperiamo l'id utente dalla sessione
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
        // Utente trovato, inviamo il messaggio all'utente dopo l'esecuzione delle azioni
        return new Promise(function(resolve, reject) {
            sendTextMessage(recipientId, text);
            return resolve();
        });
    } else {
        console.error('Oops! Non ho trovato:', sessionId);
        // Giving the wheel back to our bot
        return Promise.resolve()
    }
},
// Salutiamo, perché il bot è educato
getHello({
    context,
    entities
}) {
    return new Promise(function(resolve, reject) {

        var saluto = firstEntityValue(entities, 'saluti');

        if(saluto) {
            context.greetings = "Ciao, come posso aiutarti?";
        } else {
            delete context.greetings;
        }

        console.log("CONTEXT " + context);
        return resolve(context);
    });
},
bookRoom({
    context,
    entities
}) {
    return new Promise(function(resolve, reject) {

        var numberOfRooms = firstEntityValue(entities, 'wit/number');

        if(numberOfRooms) {
            context.rooms = numberOfRooms;
        } else {
            context.rooms = 0;
        }

        console.log("CONTEXT " + context);
        return resolve(context);
    });
},
};

// Setup del bot
const wit = new Wit({
    accessToken: WIT_ACCESS_TOKEN,
    actions,
    logger: new log.Logger(log.INFO)
});

// Controllo entità
const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

<commit_msg>Changing entity<commit_after>// Inizializziamo i componenti dell'applicazione
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
var mongodb = require('mongodb');

// Wit
var Wit = require('node-wit').Wit;
var log = require('node-wit').log;
var WIT_ACCESS_TOKEN = process.env.WIT_ACCESS_TOKEN;

// Connettiamoci a MongoDB.
var MongoClient = mongodb.MongoClient;

// URL precedentemente salvato dal plugin mlab.
var url = process.env.MONGODB_URI;

// Connessione al server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Impossibile connettersi. Errore:', err);
  } else {
    // Siamo connessi! :)
    console.log('Connessione stabilita con: ', url);

    // Qui eseguiremo il nostro codice...

    db.close();
  }
});

// La cartella per i file statici
app.use(express.static('public'));

// Impostiamo bodyparser che ci permetterà di interpretare messaggi e confezionare payload
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// L'applicazione sarà in ascolto sulla porta 3000 o su una porta predefinita dal server
app.listen((process.env.PORT || 3000));

// Homepage
app.get('/', function (req, res) {
    res.send('
Questo è hotelbot
');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'ciao_io_programmo_sono_hotelbot') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Token non valido');
    }
});

// Gestione degli eventi
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {
            sendMessageToWit(event.sender.id, event);
            //evaluateCommand(event.sender.id, event.message.text);
        } else if (event.postback) {
            // Abbiamo ricevuto una postback
        } else if (event.message && event.message.attachments) {
            // Gestione degli allegati
            sendTextMessage(event.sender.id, "Mi spiace, non posso gestire allegati!");
        }
    }
    res.sendStatus(200);
});

// Invia un messaggio di testo
function sendTextMessage(recipientId, text) {
    var msg = {
        "text": text
    };
    sendMessage(recipientId, msg)
}

// Invia messaggio multimediale
function sendMultimediaMessage(recipientId, type, url) {
    var msg = {
        "attachment": {
            "type": type,
            "payload": {
                "url": url
            }
        }
    };

    sendMessage(recipientId, msg);
}

// Invia un messaggio generico
function sendMessage(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.7/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Errore nella spedizione del messaggio: ', error);
        } else if (response.body.error) {
            console.log('Errore: ', response.body.error);
        }
    });
};

// Gestione dei comandi
function evaluateCommand(recipientId, text) {
    command = text.toLowerCase();
    console.log("Comando ricevuto: " + command);
}

// Codice per wit.ai
function sendMessageToWit(recipientId, event) {

  const sessionId = findOrCreateSession(recipientId);
  const {
      text,
      attachments
  } = event.message;

  // Inviamo i messaggi a Wit.ai
  // Eseguiamo le azioni fino a quando non abbiamo più niente da eseguire
  wit.runActions(
      sessionId, // sessione utente
      text, // messaggio
      sessions[sessionId].context // context sessione utente
  ).then((context) => {
        console.log('Azioni...');
        // Ok, abbiamo fatto tutto.
        // Aspettiamo nuovi messaggi.
        console.log('Aspettiamo nuovi messaggi...');

        // Updating the user's current session state
        sessions[sessionId].context = context;
      })
      .catch((err) => {
        var reply = "Mi spiace, non riesco a capirti... :-(";
        sendTextMessage(recipientId, reply);
        console.error('Oops! C\'è stato un problema! ', err.stack || err);
      })

}

const sessions = {};

const findOrCreateSession = (fbid) => {
    let sessionId;
    // Controlliamo se abbiamo una sessione utente
    Object.keys(sessions).forEach(k => {
        if (sessions[k].fbid === fbid) {
        // Eccolo
        sessionId = k;
    }
});
if (!sessionId) {
    // Sessione non trovata, ne creiamo una nuova
    sessionId = new Date().toISOString();
    sessions[sessionId] = {
        fbid: fbid,
        context: {}
    };
}
return sessionId;
};

// Le azioni del nostro bot
const actions = {
    send({
        sessionId
    }, {
        text
    }) {
    // Il nostro bot ha qualcosa da dire!
    // Recuperiamo l'id utente dalla sessione
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
        // Utente trovato, inviamo il messaggio all'utente dopo l'esecuzione delle azioni
        return new Promise(function(resolve, reject) {
            sendTextMessage(recipientId, text);
            return resolve();
        });
    } else {
        console.error('Oops! Non ho trovato:', sessionId);
        // Giving the wheel back to our bot
        return Promise.resolve()
    }
},
// Salutiamo, perché il bot è educato
getHello({
    context,
    entities
}) {
    return new Promise(function(resolve, reject) {

        var saluto = firstEntityValue(entities, 'saluti');

        if(saluto) {
            context.greetings = "Ciao, come posso aiutarti?";
        } else {
            delete context.greetings;
        }

        console.log("CONTEXT " + context);
        return resolve(context);
    });
},
bookRoom({
    context,
    entities
}) {
    return new Promise(function(resolve, reject) {

        var numberOfRooms = firstEntityValue(entities, 'number');

        if(numberOfRooms) {
            context.rooms = numberOfRooms;
        } else {
            context.rooms = 0;
        }

        console.log("CONTEXT " + context);
        return resolve(context);
    });
},
};

// Setup del bot
const wit = new Wit({
    accessToken: WIT_ACCESS_TOKEN,
    actions,
    logger: new log.Logger(log.INFO)
});

// Controllo entità
const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

<|endoftext|>


<commit_before>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence Sematext Agent for OS Metrics is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
'use strict'
var SpmAgent = require('spm-agent')
var Agent = SpmAgent.Agent
var config = SpmAgent.Config
var os = require('os')
var cluster = require('cluster')
var diskfree = require('node-df')
var logger = SpmAgent.Logger
/**
 * This module generates OS Metrics. Names are compatible with collectd. SpmSender uses collectd format
 * @returns {Agent}
 */
module.exports = function () {
  if (os.platform() === 'linux') {
    try {
      var LinuxAgent = require('./linuxAgent.js')
      var lAgent = new LinuxAgent()
      return lAgent
    } catch (err) {
      SpmAgent.Logger.error('Cannot initialize linux agent:' + err)
    }
  }
  var osAgent = new Agent(
    {
      diskFree: function (agent) {
        if (os.platform() !== 'darwin') {
          return
        }
        diskfree(function dfMetrics (err, data) {
          if (err) {
            return logger.error('Error in df() for disk-usage metrics:' + err)
          }
          if (data && data.length > 0) {
            data.forEach(function (disk) {
              if (/\/dev\/.+/i.test(disk.filesystem)) {
                var dev = disk.filesystem.split('/')[2]
                var usedName = 'collectd5-disk-space-used\tdf-' + dev + '/df_complex-used'
                var usedValue = disk.used * 1024
                var freeName = 'collectd5-disk-space-free\tdf-' + dev + '/df_complex-free'
                var freeValue = disk.available * 1024
                agent.addMetrics({
                  ts: Date.now(),
                  name: usedName,
                  value: usedValue,
                  sct: 'OS'
                })
                agent.addMetrics({
                  ts: Date.now(),
                  name: freeName,
                  value: freeValue,
                  sct: 'OS'
                })
              }
            })
          }
        })
      },
      start: function (agent) {
        this.agent = agent
        var cpuLastValues = {}
        os.cpus().forEach(function (cpu, i) {
          cpuLastValues[i] = {idle: 0, user: 0, sys: 0, irq: 0, nice: 0}
        })
        var cpuProperties = ['user', 'nice', 'irq', 'sys', 'idle']
        if (cluster.isMaster || process.env.NODE_APP_INSTANCE === 0 || process.env.SPM_MASTER_MODE === 1) {
          var timerId = setInterval(function () {
            var time = new Date().getTime()
            var metrics = {}
            this.diskFree(agent)
            metrics['collectd-sys-load'] = os.loadavg()
            metrics['collectd-mem-free'] = os.freemem()
            metrics['collectd-mem-used'] = os.totalmem() - os.freemem()
            os.cpus().forEach(function (cpu, i) {
              var cpuTotal = 0
              cpuProperties.forEach(function (property) {
                cpuLastValues[i][property] = cpu.times[property] - cpuLastValues[i][property]
                cpuTotal = cpuTotal + cpuLastValues[i][property]
              })
              metrics['collectd-cpu-usr\tcpu-' + i + '/cpu-user'] = (cpuLastValues[i].user / cpuTotal) * 100
              metrics['collectd-cpu-nic\tcpu-' + i + '/cpu-nice'] = (cpuLastValues[i].nice / cpuTotal) * 100
              metrics['collectd-cpu-sys\tcpu-' + i + '/cpu-system'] = (cpuLastValues[i].sys / cpuTotal) * 100
              metrics['collectd-cpu-idl\tcpu-' + i + '/cpu-idle'] = (cpuLastValues[i].idle / cpuTotal) * 100
              metrics['collectd-cpu-int\tcpu-' + i + '/cpu-interrupt'] = (cpuLastValues[i].irq / cpuTotal) * 100
              // We can't get this values from node.js standard API
              metrics['collectd-cpu-ste\tcpu-' + i + '/cpu-steal'] = 0.0001
              metrics['collectd-cpu-sir\tcpu-' + i + '/cpu-softirq'] = 0.0001
              metrics['collectd-cpu-wait\tcpu-' + i + '/cpu-wait'] = 0.0001
            })
            // setting "sct" parameter for spm-sender to use specific collectd format when transmitting to receiver.
            for (var x in metrics) {
              agent.addMetrics({ts: time, name: x, value: metrics[x], sct: 'OS'})
            }
          }.bind(this), config.collectionInterval || 30000)
          if (timerId.unref) {
            timerId.unref()
          }
        }
      }
    }
  )
  return osAgent
}
<commit_msg>Switch to disable OS monitoring -> use NODEJS_OS_MONITOR_ENABLED=false<commit_after>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence Sematext Agent for OS Metrics is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
'use strict'
var SpmAgent = require('spm-agent')
var Agent = SpmAgent.Agent
var config = SpmAgent.Config
var os = require('os')
var cluster = require('cluster')
var diskfree = require('node-df')
var logger = SpmAgent.Logger
/**
 * This module generates OS Metrics. Names are compatible with collectd. SpmSender uses collectd format
 * @returns {Agent}
 */
module.exports = function () {
  if (process.env.NODEJS_OS_MONITOR_ENABLED === 'false') {
    // in case SPM JAVA OS monitor is used,
    // node based agents don't need to collect OS Metrics
    return new Agent({
      start: function (agent) { this.agent = agent },
      stop: function () {}
    })
  }
  if (os.platform() === 'linux') {
    try {
      var LinuxAgent = require('./linuxAgent.js')
      var lAgent = new LinuxAgent()
      return lAgent
    } catch (err) {
      SpmAgent.Logger.error('Cannot initialize linux agent:' + err)
    }
  }
  var osAgent = new Agent(
    {
      diskFree: function (agent) {
        if (os.platform() !== 'darwin') {
          return
        }
        diskfree(function dfMetrics (err, data) {
          if (err) {
            return logger.error('Error in df() for disk-usage metrics:' + err)
          }
          if (data && data.length > 0) {
            data.forEach(function (disk) {
              if (/\/dev\/.+/i.test(disk.filesystem)) {
                var dev = disk.filesystem.split('/')[2]
                var usedName = 'collectd5-disk-space-used\tdf-' + dev + '/df_complex-used'
                var usedValue = disk.used * 1024
                var freeName = 'collectd5-disk-space-free\tdf-' + dev + '/df_complex-free'
                var freeValue = disk.available * 1024
                agent.addMetrics({
                  ts: Date.now(),
                  name: usedName,
                  value: usedValue,
                  sct: 'OS'
                })
                agent.addMetrics({
                  ts: Date.now(),
                  name: freeName,
                  value: freeValue,
                  sct: 'OS'
                })
              }
            })
          }
        })
      },
      start: function (agent) {
        this.agent = agent
        var cpuLastValues = {}
        os.cpus().forEach(function (cpu, i) {
          cpuLastValues[i] = {idle: 0, user: 0, sys: 0, irq: 0, nice: 0}
        })
        var cpuProperties = ['user', 'nice', 'irq', 'sys', 'idle']
        if (cluster.isMaster || process.env.NODE_APP_INSTANCE === 0 || process.env.SPM_MASTER_MODE === 1) {
          var timerId = setInterval(function () {
            var time = new Date().getTime()
            var metrics = {}
            this.diskFree(agent)
            metrics['collectd-sys-load'] = os.loadavg()
            metrics['collectd-mem-free'] = os.freemem()
            metrics['collectd-mem-used'] = os.totalmem() - os.freemem()
            os.cpus().forEach(function (cpu, i) {
              var cpuTotal = 0
              cpuProperties.forEach(function (property) {
                cpuLastValues[i][property] = cpu.times[property] - cpuLastValues[i][property]
                cpuTotal = cpuTotal + cpuLastValues[i][property]
              })
              metrics['collectd-cpu-usr\tcpu-' + i + '/cpu-user'] = (cpuLastValues[i].user / cpuTotal) * 100
              metrics['collectd-cpu-nic\tcpu-' + i + '/cpu-nice'] = (cpuLastValues[i].nice / cpuTotal) * 100
              metrics['collectd-cpu-sys\tcpu-' + i + '/cpu-system'] = (cpuLastValues[i].sys / cpuTotal) * 100
              metrics['collectd-cpu-idl\tcpu-' + i + '/cpu-idle'] = (cpuLastValues[i].idle / cpuTotal) * 100
              metrics['collectd-cpu-int\tcpu-' + i + '/cpu-interrupt'] = (cpuLastValues[i].irq / cpuTotal) * 100
              // We can't get this values from node.js standard API
              metrics['collectd-cpu-ste\tcpu-' + i + '/cpu-steal'] = 0.0001
              metrics['collectd-cpu-sir\tcpu-' + i + '/cpu-softirq'] = 0.0001
              metrics['collectd-cpu-wait\tcpu-' + i + '/cpu-wait'] = 0.0001
            })
            // setting "sct" parameter for spm-sender to use specific collectd format when transmitting to receiver.
            for (var x in metrics) {
              agent.addMetrics({ts: time, name: x, value: metrics[x], sct: 'OS'})
            }
          }.bind(this), config.collectionInterval || 30000)
          if (timerId.unref) {
            timerId.unref()
          }
        }
      }
    }
  )
  return osAgent
}
<|endoftext|>


<commit_before>'use strict';
//
// FastChat
// 2015
//

join = require('path').join;

module.exports = function() {
    return join(__dirname, 'app')
};<commit_msg>Whoops, that doesn't work in js<commit_after>'use strict';
//
// FastChat
// 2015
//

var join = require('path').join;

module.exports = function() {
    return join(__dirname, 'app')
};<|endoftext|>


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

'use strict';

var git = require('nodegit');
var program = require('commander');
var exec = require('child_process').exec;
var path = require('path');
var when = require('when');
var colors = require('colors');
var hookManager = require('./git_hooks/hookManager');

function _command (command, callback) {
  exec(command, { cwd: '.' }, function (err, stdout, stderr) {
    callback(stdout.split('\n').join(''))
  });
}

function getLocalRepositoryPath() {
  var def = when.defer();

  _command('git rev-parse --show-toplevel', function (result) {
    if (result !== '') {
      def.resolve(result);
    } else {
      def.reject('Not a git repository');
    }
  });

  return def.promise;
}

function openLocalRepository(path) {
  return git.Repository.open(path);
}

function handleError(error) {
  console.log(error);
}

function getRepoInformation() {
  var def = when.defer();

  getLocalRepositoryPath()
    .then(openLocalRepository)
    .catch(handleError)
    .done(function(repository) {
      var path = repository.path();

      repository.getCurrentBranch().then(function(reference) {
        var branch = reference.name();
        var repoList = [path, branch];
        def.resolve(repoList);
      })
    });

  return def.promise;
}

function addTask(task) {
  getRepoInformation().then(function(repoList) {
    hookManager.addNewTask(task.toString(), repoList[0], repoList[1]);
  });
}

function resolveTask(task_id) {
  getRepoInformation().then(function(repoList) {
    hookManager.resolveTask(task_id, repoList[0], repoList[1]);
  });
}

function listAllTasks() {
  getRepoInformation().then(function(repoList) {
    hookManager.listAllTasks(repoList[0], repoList[1]);
  });
}

/*
* Application commands
*/

program
  .version(require('./package.json').version)
  .option('add [task]', 'Add a new task', addTask)
  .option('resolve <n>', 'Resolve a task', resolveTask)
  .option('-l, --list', 'List open tasks', listAllTasks)
  .parse(process.argv);

module.exports = {
  getCurrentSituation: function(callback) {
    getRepoInformation().then(function(repoList) {
      hookManager.getStatus(repoList[0], repoList[1]).then(function(result) {
        callback(result);
      });
    });
  },

  listRemaining: function(amount) {
    var return_str = "You have " + amount + " tasks remaining. Finish them before commiting."
    console.log(return_str.red);
  },

  removeTaskFile: function(callback) {
    getRepoInformation().then(function(repoList) {
       hookManager.removeTaskFile(repoList[0], repoList[1]);
    });
  }
}
<commit_msg>Improve wording and instructions<commit_after>#!/usr/bin/env node

'use strict';

var git = require('nodegit');
var program = require('commander');
var exec = require('child_process').exec;
var path = require('path');
var when = require('when');
var colors = require('colors');
var hookManager = require('./git_hooks/hookManager');

function _command (command, callback) {
  exec(command, { cwd: '.' }, function (err, stdout, stderr) {
    callback(stdout.split('\n').join(''))
  });
}

function getLocalRepositoryPath() {
  var def = when.defer();

  _command('git rev-parse --show-toplevel', function (result) {
    if (result !== '') {
      def.resolve(result);
    } else {
      def.reject('Not a git repository');
    }
  });

  return def.promise;
}

function openLocalRepository(path) {
  return git.Repository.open(path);
}

function handleError(error) {
  console.log(error);
  process.exit(1);
}

function getRepoInformation() {
  var def = when.defer();

  getLocalRepositoryPath()
    .then(openLocalRepository)
    .catch(handleError)
    .done(function(repository) {
      var path = repository.path();

      repository.getCurrentBranch().then(function(reference) {
        var branch = reference.name();
        var repoList = [path, branch];
        def.resolve(repoList);
      })
    });

  return def.promise;
}

function addTask(task) {
  getRepoInformation().then(function(repoList) {
    hookManager.addNewTask(task.toString(), repoList[0], repoList[1]);
  });
}

function resolveTask(task_id) {
  getRepoInformation().then(function(repoList) {
    hookManager.resolveTask(task_id, repoList[0], repoList[1]);
  });
}

function listAllTasks() {
  getRepoInformation().then(function(repoList) {
    hookManager.listAllTasks(repoList[0], repoList[1]);
  });
}

/*
* Application commands
*/

program
  .version(require('./package.json').version)
  .option('add [task]', 'Add a new task', addTask)
  .option('resolve <id>', 'Resolve a task', resolveTask)
  .option('-l, --list', 'List open tasks', listAllTasks)
  .parse(process.argv);

module.exports = {
  getCurrentSituation: function(callback) {
    getRepoInformation().then(function(repoList) {
      hookManager.getStatus(repoList[0], repoList[1]).then(function(result) {
        callback(result);
      });
    });
  },

  listRemaining: function(amount) {
    if (amount !== 1) {
      var return_str = "You have " + amount + " tasks remaining. Finish them before commiting."
    } else {
      var return_str = "You have " + amount + " task remaining. Finish it before commiting."
    }
    console.log(return_str.red);
  },

  removeTaskFile: function(callback) {
    getRepoInformation().then(function(repoList) {
       hookManager.removeTaskFile(repoList[0], repoList[1]);
    });
  }
}
<|endoftext|>