<commit_before>/*!
 * vary
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * Module exports.
 */

module.exports = vary
module.exports.append = append

/**
 * RegExp to match field-name in RFC 7230 sec 3.2
 *
 * field-name    = token
 * token         = 1*tchar
 * tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
 *               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
 *               / DIGIT / ALPHA
 *               ; any VCHAR, except delimiters
 */

var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

/**
 * Append a field to a vary header.
 *
 * @param {String} header
 * @param {String|Array} field
 * @return {String}
 * @api public
 */

function append (header, field) {
  if (typeof header !== 'string') {
    throw new TypeError('header argument is required')
  }

  if (!field) {
    throw new TypeError('field argument is required')
  }

  // get fields array
  var fields = !Array.isArray(field)
    ? parse(String(field))
    : field

  // assert on invalid field names
  for (var j = 0; j < fields.length; j++) {
    if (!FIELD_NAME_REGEXP.test(fields[j])) {
      throw new TypeError('field argument contains an invalid header name')
    }
  }

  // existing, unspecified vary
  if (header === '*') {
    return header
  }

  // enumerate current values
  var val = header
  var vals = parse(header.toLowerCase())

  // unspecified vary
  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
    return '*'
  }

  for (var i = 0; i < fields.length; i++) {
    var fld = fields[i].toLowerCase()

    // append value (case-preserving)
    if (vals.indexOf(fld) === -1) {
      vals.push(fld)
      val = val
        ? val + ', ' + fields[i]
        : fields[i]
    }
  }

  return val
}

/**
 * Parse a vary header into an array.
 *
 * @param {String} header
 * @return {Array}
 * @api private
 */

function parse (header) {
  return header.trim().split(/ *, */)
}

/**
 * Mark that a request is varied on a header field.
 *
 * @param {Object} res
 * @param {String|Array} field
 * @api public
 */

function vary (res, field) {
  if (!res || !res.getHeader || !res.setHeader) {
    // quack quack
    throw new TypeError('res argument is required')
  }

  // get existing header
  var val = res.getHeader('Vary') || ''
  var header = Array.isArray(val)
    ? val.join(', ')
    : String(val)

  // set new header
  if ((val = append(header, field))) {
    res.setHeader('Vary', val)
  }
}
<commit_msg>docs: change the style for jsdoc @api<commit_after>/*!
 * vary
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * Module exports.
 */

module.exports = vary
module.exports.append = append

/**
 * RegExp to match field-name in RFC 7230 sec 3.2
 *
 * field-name    = token
 * token         = 1*tchar
 * tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
 *               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
 *               / DIGIT / ALPHA
 *               ; any VCHAR, except delimiters
 */

var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

/**
 * Append a field to a vary header.
 *
 * @param {String} header
 * @param {String|Array} field
 * @return {String}
 * @public
 */

function append (header, field) {
  if (typeof header !== 'string') {
    throw new TypeError('header argument is required')
  }

  if (!field) {
    throw new TypeError('field argument is required')
  }

  // get fields array
  var fields = !Array.isArray(field)
    ? parse(String(field))
    : field

  // assert on invalid field names
  for (var j = 0; j < fields.length; j++) {
    if (!FIELD_NAME_REGEXP.test(fields[j])) {
      throw new TypeError('field argument contains an invalid header name')
    }
  }

  // existing, unspecified vary
  if (header === '*') {
    return header
  }

  // enumerate current values
  var val = header
  var vals = parse(header.toLowerCase())

  // unspecified vary
  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
    return '*'
  }

  for (var i = 0; i < fields.length; i++) {
    var fld = fields[i].toLowerCase()

    // append value (case-preserving)
    if (vals.indexOf(fld) === -1) {
      vals.push(fld)
      val = val
        ? val + ', ' + fields[i]
        : fields[i]
    }
  }

  return val
}

/**
 * Parse a vary header into an array.
 *
 * @param {String} header
 * @return {Array}
 * @private
 */

function parse (header) {
  return header.trim().split(/ *, */)
}

/**
 * Mark that a request is varied on a header field.
 *
 * @param {Object} res
 * @param {String|Array} field
 * @public
 */

function vary (res, field) {
  if (!res || !res.getHeader || !res.setHeader) {
    // quack quack
    throw new TypeError('res argument is required')
  }

  // get existing header
  var val = res.getHeader('Vary') || ''
  var header = Array.isArray(val)
    ? val.join(', ')
    : String(val)

  // set new header
  if ((val = append(header, field))) {
    res.setHeader('Vary', val)
  }
}
<|endoftext|>


<commit_before>//http://en.wikipedia.org/wiki/Haversine_formula
//http://www.movable-type.co.uk/scripts/latlong.html

module.exports = function(point1, point2, units){
  var coordinates1 = point1.geometry.coordinates;
  var coordinates2 = point2.geometry.coordinates;

  var dLat = toRad(coordinates2[1] - coordinates1[1]);
  var dLon = toRad(coordinates2[0] - coordinates1[0]);
  var lat1 = toRad(coordinates1[1]);
  var lat2 = toRad(coordinates2[1]);
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  var R = 0;
  switch(units){
    case 'miles':
      R = 3960;
      break
    case 'kilometers':
      R = 6373;
      break
    case 'degrees':
      R = 57.2957795;
      break
    case 'radians':
      R = 1;
      break
  }
  var distance = R * c;
  return distance;
}

function toRad(degree){
  return degree * Math.PI / 180;
}
<commit_msg>Add JSDoc.<commit_after>//http://en.wikipedia.org/wiki/Haversine_formula
//http://www.movable-type.co.uk/scripts/latlong.html

/**
 * Calculates the distance between two {@link Point} features in degrees,
 * radians, miles, or kilometers. This uses the [haversine formula](http://en.wikipedia.org/wiki/Haversine_formula)
 * to account for global curvature.
 *
 * @module turf/distance
 * @param {Point} from
 * @param {Point} to
 * @param {string} units
 * @return {number} distance
 * @example
 * var point1 = turf.point(-75.343, 39.984)
 * var point2 = turf.point(-75.534, 39.123)
 * var units = 'miles' // or 'kilometers', 'degrees', 'radians'
 * var distance = turf.distance(point1, point2, units)
 */
module.exports = function(point1, point2, units){
  var coordinates1 = point1.geometry.coordinates;
  var coordinates2 = point2.geometry.coordinates;

  var dLat = toRad(coordinates2[1] - coordinates1[1]);
  var dLon = toRad(coordinates2[0] - coordinates1[0]);
  var lat1 = toRad(coordinates1[1]);
  var lat2 = toRad(coordinates2[1]);
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  var R = 0;
  switch(units){
    case 'miles':
      R = 3960;
      break;
    case 'kilometers':
      R = 6373;
      break;
    case 'degrees':
      R = 57.2957795;
      break;
    case 'radians':
      R = 1;
      break;
  }
  var distance = R * c;
  return distance;
}

function toRad(degree){
  return degree * Math.PI / 180;
}
<|endoftext|>


<commit_before>'use strict';

const Metalsmith   = require('metalsmith')
const jade         = require('metalsmith-jade')
const sass         = require('metalsmith-sass')
const browserSync  = require('metalsmith-browser-sync')
const markdown     = require('metalsmith-markdown')
const layouts      = require('metalsmith-layouts')
const permalinks   = require('metalsmith-permalinks')
const babel        = require('metalsmith-babel')
const bourbon      = require('node-bourbon')
const path         = require('path')
const postcss      = require('metalsmith-postcss')
const autoprefixer = require('autoprefixer')
const copy         = require('metalsmith-copy')
const each         = require('metalsmith-each')
const navigation   = require('metalsmith-navigation')
const modRewrite   = require('connect-modrewrite')
const uglify       = require('metalsmith-uglify')

// --- general build settings --- //
const docsVersions = ['1.7'];

const updatePaths = function(file, filename) {
  if (path.basename(filename) === "index.html" ) { return filename; }

  if (path.extname(filename) === '.html' &&
      path.extname(filename) !== '') {

    return filename.split(".html")[0] + "/index.html";
  }
  return filename;
};

// --------- figuring out the navigation ---------- //
const navConfig = {
    header: {
      includeDirs: true,
      pathProperty: 'nav_path',
      childrenProperty: 'nav_children',
      sortBy: function(file, node) {
        if (file !== undefined) {
          return file.menu_order
        } else if (node.type === 'dir') {
          // for directories find the index.html and grab its menu_order
          let indexFile = node.children.find((c) => c.name == 'index.html')
          if (indexFile !== undefined) {
            return indexFile.file.menu_order || 999
          }

        } else {
          return 0;
        }

      },
      sortByNameFirst: true
    }
}

let createDocsJSON = function(obj) {
  var newObj = {
    name: obj.type,
    path: obj.path
  };

  if(obj.file) {
    newObj.file = {
      post_title: obj.file.nav_title || obj.file.post_title,
      search_blurb: obj.file.search_blurb
    }
  }
  newObj.children = obj.children.map(createDocsJSON);

  return newObj;
}

const navSettings = {
  navListProperty: 'navs',
  permalinks: false,
  formatJSONfn: createDocsJSON
}

let nav = navigation(navConfig, navSettings);

// --------- Compiling the Markdown files to HTML --------//
let createDocs = function(version) {
  Metalsmith(path.join(__dirname, 'dcos-docs'))
    .source(version)
    .use(markdown({
      smartypants: true,
      gfm: true,
      tables: true
    }))
    .use(nav)
    .use(layouts({
      pattern: '**/*.html',
      engine: 'jade',
      directory: path.join('..', 'layouts'),
      default: 'docs.jade'
    }))
    .use(jade({
      pretty: true
    }))
    .clean(false)
    .use(each(updatePaths))
    .destination(path.join('..', 'build', 'docs', version))
    .build((err) => {
      if (err) throw err
    })
}

let allDocs = function() {
  for (let version of docsVersions) {
    createDocs(version)
  }
}

Metalsmith(__dirname)
  .use(markdown({
    smartypants: true,
    gfm: true,
    tables: true
  }))
  .use(jade({
    pretty: true
  }))
  .use(sass({
    outputStyle: 'expanded',
    includePaths: [
      '/node_modules/',
      path.join(__dirname, 'node_modules/support-for/sass')
     ].concat(bourbon.includePaths)
  }))
  .use(postcss([
    autoprefixer({ browsers: ['last 4 versions'] })
  ]))
  .use(babel({
    presets: ['es2015'],
    only: './src/scripts/**'
  }))
  .use(copy({
    pattern: 'assets/*',
    directory: 'assets'
  }))
  .use(each(updatePaths))
  .clean(false)
  .use(uglify({
    filter: 'scripts/**/*.js',
    concat: 'scripts/main.min.js',
    // sourceMap: !process.env.CI,
    // preserveComments: !process.env.CI,
    removeOriginal: process.env.CI,
    compress: process.env.CI
  }))
  .use((() => {
    if(!process.env.CI) {
      return browserSync({
        server: {
          baseDir: './build',
          middleware: [
            modRewrite([
              "^/docs/latest/(.*) /docs/" + docsVersions.slice(-1).pop() + "/$1"
            ]),
            function(req, res, next) {
              var file = `./build${req.originalUrl}.html`;
              require('fs').exists(file, function(exists) {
                if (exists) req.url += '.html';
                next();
              });
            }
          ]
        },
        files: ['./src/**/*', './dcos-docs/**/*', './layouts/**/*', './mixins/**/*']
      }, null, allDocs)
    }
  })())
  .build((err) => {
    if (err) throw err
  })

allDocs()
<commit_msg>*bump*<commit_after>'use strict';

const Metalsmith   = require('metalsmith')
const jade         = require('metalsmith-jade')
const sass         = require('metalsmith-sass')
const browserSync  = require('metalsmith-browser-sync')
const markdown     = require('metalsmith-markdown')
const layouts      = require('metalsmith-layouts')
const permalinks   = require('metalsmith-permalinks')
const babel        = require('metalsmith-babel')
const bourbon      = require('node-bourbon')
const path         = require('path')
const postcss      = require('metalsmith-postcss')
const autoprefixer = require('autoprefixer')
const copy         = require('metalsmith-copy')
const each         = require('metalsmith-each')
const navigation   = require('metalsmith-navigation')
const modRewrite   = require('connect-modrewrite')
const uglify       = require('metalsmith-uglify')

// --- general build settings --- //
const docsVersions = ['1.7'];

const updatePaths = function(file, filename) {
  if (path.basename(filename) === "index.html" ) { return filename; }

  if (path.extname(filename) === '.html' &&
      path.extname(filename) !== '') {

    return filename.split(".html")[0] + "/index.html";
  }
  return filename;
};

// --------- figuring out the navigation ---------- //
const navConfig = {
    header: {
      includeDirs: true,
      pathProperty: 'nav_path',
      childrenProperty: 'nav_children',
      sortBy: function(file, node) {
        if (file !== undefined) {
          return file.menu_order
        } else if (node.type === 'dir') {
          // for directories find the index.html and grab its menu_order
          let indexFile = node.children.find((c) => c.name == 'index.html')
          if (indexFile !== undefined) {
            return indexFile.file.menu_order || 999
          }

        } else {
          return 0;
        }

      },
      sortByNameFirst: true
    }
}

let createDocsJSON = function(obj) {
  var newObj = {
    name: obj.type,
    path: obj.path
  };

  if(obj.file) {
    newObj.file = {
      post_title: obj.file.nav_title || obj.file.post_title,
      search_blurb: obj.file.search_blurb
    }
  }
  newObj.children = obj.children.map(createDocsJSON);

  return newObj;
}

const navSettings = {
  navListProperty: 'navs',
  permalinks: false,
  formatJSONfn: createDocsJSON
}

let nav = navigation(navConfig, navSettings);

// --------- Compiling the Markdown files to HTML --------//
let createDocs = function(version) {
  Metalsmith(path.join(__dirname, 'dcos-docs'))
    .source(version)
    .use(markdown({
      smartypants: true,
      gfm: true,
      tables: true
    }))
    .use(nav)
    .use(layouts({
      pattern: '**/*.html',
      engine: 'jade',
      directory: path.join('..', 'layouts'),
      default: 'docs.jade'
    }))
    .use(jade({
      pretty: true
    }))
    .clean(false)
    .use(each(updatePaths))
    .destination(path.join('..', 'build', 'docs', version))
    .build((err) => {
      if (err) throw err
    })
}

let allDocs = function() {
  for (let version of docsVersions) {
    createDocs(version)
  }
}

Metalsmith(__dirname)
  .use(markdown({
    smartypants: true,
    gfm: true,
    tables: true
  }))
  .use(jade({
    pretty: true
  }))
  .use(sass({
    outputStyle: 'expanded',
    includePaths: [
      '/node_modules/',
      path.join(__dirname, 'node_modules/support-for/sass')
     ].concat(bourbon.includePaths)
  }))
  .use(postcss([
    autoprefixer({ browsers: ['last 4 versions'] })
  ]))
  .use(babel({
    presets: ['es2015'],
    only: './src/scripts/**'
  }))
  .use(copy({
    pattern: 'assets/*',
    directory: 'assets'
  }))
  .use(each(updatePaths))
  .clean(false)
  .use(uglify({
    filter: 'scripts/**/*.js',
    concat: 'scripts/main.min.js',
    // sourceMap: !process.env.CI,
    // preserveComments: !process.env.CI,
    // removeOriginal: process.env.CI,
    // compress: process.env.CI
  }))
  .use((() => {
    if(!process.env.CI) {
      return browserSync({
        server: {
          baseDir: './build',
          middleware: [
            modRewrite([
              "^/docs/latest/(.*) /docs/" + docsVersions.slice(-1).pop() + "/$1"
            ]),
            function(req, res, next) {
              var file = `./build${req.originalUrl}.html`;
              require('fs').exists(file, function(exists) {
                if (exists) req.url += '.html';
                next();
              });
            }
          ]
        },
        files: ['./src/**/*', './dcos-docs/**/*', './layouts/**/*', './mixins/**/*']
      }, null, allDocs)
    }
  })())
  .build((err) => {
    if (err) throw err
  })

allDocs()
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var StyleLinter = require('broccoli-stylelint');

module.exports = {
  name: 'ember-cli-stylelint',

  included: function(app) {
    if (!app.isTestingStyleLintAddon) {
      this._super.included(app);
    }

    //setup for testing
    this.project = {
      generateTestFile:function(){}
    }
    this.app = app;
    this.styleLintOptions = app.options.styleLint || {generateTests:true};
  },

  lintTree: function(type, tree) {
    var project = this.project;

    if (type === 'app') {
      this.styleLintOptions.testGenerator =  function(relativePath, errors) {
        var passed = null;
        var name = relativePath+' should pass style lint';
        if (errors) {
          passed = false;
          var assertions = [name];
          for(var i = 0; i < errors.warnings.length; i++){
            var warning = errors.warnings[i];
            assertions.push(this.escapeErrorString('line: '+warning.line+', col: '+warning.column+' '+warning.text+'.'));
          }
          errors = assertions.join('\\n');
        } else {
          passed = true;
          errors = "";
        }

        return project.generateTestFile(' Style Lint ', [{
          name: name,
          passed: !!passed,
          errorMessage: errors
        }]);
      };
      return new StyleLinter(this.app.trees.app, this.styleLintOptions);
    } else {
      return tree;
    }
  }
};
<commit_msg>Improve addon initialisation<commit_after>/* jshint node: true */
'use strict';

var StyleLinter = require('broccoli-stylelint');

module.exports = {
  name: 'ember-cli-stylelint',

  included: function(app) {
    //shared
    this.styleLintOptions = app.options.styleLint || {generateTests:true};
    this.styleLintOptions.console = console;

    //used in real app
    if (!app.isTestingStyleLintAddon) {
      this._super.included(app);
    }

    //Testing only
    this.app = app;
    this.project = {
      generateTestFile: function(){}
    }
  },

  lintTree: function(type, tree) {
    var project = this.project;

    if (type === 'app') {
      this.styleLintOptions.testGenerator =  function(relativePath, errors) {
        var passed = null;
        var name = relativePath+' should pass style lint';
        if (errors) {
          passed = false;
          var assertions = [name];
          for(var i = 0; i < errors.warnings.length; i++){
            var warning = errors.warnings[i];
            assertions.push(this.escapeErrorString('line: '+warning.line+', col: '+warning.column+' '+warning.text+'.'));
          }
          errors = assertions.join('\\n');
        } else {
          passed = true;
          errors = "";
        }

        return project.generateTestFile(' Style Lint ', [{
          name: name,
          passed: !!passed,
          errorMessage: errors
        }]);
      };
      return new StyleLinter(this.app.trees.app, this.styleLintOptions);
    } else {
      return tree;
    }
  }
};
<|endoftext|>


<commit_before>/**
 * Reddit as a commenting system backend.
 * @module reddit-comments
 */

/**
 * Module dependencies.
 */
var Reddit = require('reddit-api'),
    Emitter = require('emitter'),
    events = require('event'),
    classes = require('classes'),
    query = require('query'),
    render = require('./templates/comments'),
    cache = require('ls-cache'),
    extend = require('extend'),
    vagueTime = require('vague-time');

exports = module.exports = init;

var api = new Reddit();

/**
 * Module initialization function.
 *
 * @borrows RedditComments as init
 * @alias module:reddit-comments
 * @public
 */
function init(frame, options) {
    try {
        var rc = new RedditComments(frame, options);
    } catch (e) {
        console.log(e.toString());
        return;
    }
    rc.init();
    return rc;
}

/**
 * Generate a hash code from a string.
 *
 * @link http://stackoverflow.com/a/7616484
 * @return {number}
 */
String.prototype.hashCode = function(){
    var hash = 0, i, char;
    if (this.length == 0) return hash;
    for (i = 0, l = this.length; i < l; i++) {
        char  = this.charCodeAt(i);
        hash  = ((hash<<5)-hash)+char;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

/**
 * Main module object.
 *
 * @param {String} frame - A CSS selector of the element to be populated by comments.
 * @param {Object} options - Module configuration.
 * @param {String} options.subreddit - The subreddit name.
 * @param {String} [options.url=document.URL] - The URL to retrieve comments for.
 * @param {number} [options.commentsCacheExpiration=5] - Expiration time for
 *     retrieved comments in the `localStorage` cache.
 * @constructor
 * @private
 */
function RedditComments(frame, options) {
    var defaultOptions = {
        url: document.URL,
        commentsCacheExpiration: 5
    };
    if (!('subreddit' in (options || {}))) {
        throw new TypeError('Must specify a "subreddit"');
    }
    api.subreddit = options.subreddit;
    this.options = extend(defaultOptions, options);
    this.frame = query(frame);
    return this;
};

/**
 * Object initialization function.
 *
 * Displays retrieved comments.
 */
RedditComments.prototype.init = function() {
    var rc = this,
        frame = rc.frame;

    rc.getUrlId(rc.options.url).then(function(urlId) {
        return rc.getComments(urlId);
    }).then(function(comments) {
        frame.innerHTML = render({'comments': comments});
    });
};

/**
 * Logs in a Reddit user.
 *
 * @param {String} username
 * @param {String} password
 */
RedditComments.prototype.login = function(username, password) {
};

/**
 * Logs out a Reddit user.
 */
RedditComments.prototype.logout = function() {
};

/**
 * Posts a comment on the Reddit post.
 *
 * @param {String} body - The comment body.
 */
RedditComments.prototype.comment = function(body) {
};

/**
 * Get the comments associated with a URL.
 *
 * @param {String} urlId - Reddit's ID36 of a URL.
 */
RedditComments.prototype.getComments = function(urlId) {
    var rc = this,
        hash = urlId.hashCode().toString(),
        comments = cache.get(hash);

    if (comments != null) {
        // Fake Promise to match the API
        return {
            then: function(resolve, reject) {return resolve(comments);}
        }
    }

    return api.getComments(urlId).then(function(res) {
        var data = JSON.parse(res || {}),
            comments = rc.extractComments(data);
        cache.set(hash, comments, rc.options.commentsCacheExpiration);
        return comments;
    });
};

/**
 * Extract the comment data from Reddit's response and process it for
 * rendering.
 *
 * @param {Object} data - The data as returned by the Reddit API.
 */
RedditComments.prototype.extractComments = function(data) {
    var cData = [];
    if (!(data[1].data)) return cData;
    data = data[1].data.children;
    for (var i = 0; i < data.length; ++i) {
        if (data[i].kind != "t1") continue;
        var c = data[i].data,
            date = new Date(0),
            vt;
        date.setUTCSeconds(c.created_utc);
        vt = vagueTime.get({to: date});
        cData.push({author: c.author,
                    created_vague: vt,
                    created_timestamp: date,
                    score: c.ups - c.downs, // XXX: Where is c.score?
                    body: c.body});
    }
    return cData;
};

/**
 * Given a URL, get its ID36.
 *
 * ID36 is the unique ID used by Reddit.
 * @see http://www.reddit.com/dev/api#fullnames
 *
 * @param {String} url
 */
RedditComments.prototype.getUrlId = function(url) {
    var rc = this,
        hash = url.hashCode().toString(),
        urlId = cache.get(hash);

    if (urlId != null) {
        // Fake Promise to match the API
        return {
            then: function(resolve, reject) {return resolve(urlId);}
        }
    }

    return api.getInfo({url: url}).then(function(res) {
        var data = JSON.parse(res || {}).data,
            urlId = rc.extractUrlId(data);
        cache.set(hash, urlId);
        return urlId;
    });
};

/**
 * Extract the URL's ID36 from Reddit's response.
 *
 * @param {Object} data - The data as returned by the Reddit API.
 */
RedditComments.prototype.extractUrlId = function(data) {
    var rc = this;

    if (data && data.children.length) {
        var linkData = data.children[0].data;
        if (!(linkData.subreddit == rc.options.subreddit)) {
            console.log("Post doesn't belong to this subreddit");
        } else {
            return linkData.id;
        }
    }
};
<commit_msg>extractComments: extract nested replies, allow recursive calls<commit_after>/**
 * Reddit as a commenting system backend.
 * @module reddit-comments
 */

/**
 * Module dependencies.
 */
var Reddit = require('reddit-api'),
    Emitter = require('emitter'),
    events = require('event'),
    classes = require('classes'),
    query = require('query'),
    render = require('./templates/comments'),
    cache = require('ls-cache'),
    extend = require('extend'),
    vagueTime = require('vague-time');

exports = module.exports = init;

var api = new Reddit();

/**
 * Module initialization function.
 *
 * @borrows RedditComments as init
 * @alias module:reddit-comments
 * @public
 */
function init(frame, options) {
    try {
        var rc = new RedditComments(frame, options);
    } catch (e) {
        console.log(e.toString());
        return;
    }
    rc.init();
    return rc;
}

/**
 * Generate a hash code from a string.
 *
 * @link http://stackoverflow.com/a/7616484
 * @return {number}
 */
String.prototype.hashCode = function(){
    var hash = 0, i, char;
    if (this.length == 0) return hash;
    for (i = 0, l = this.length; i < l; i++) {
        char  = this.charCodeAt(i);
        hash  = ((hash<<5)-hash)+char;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

/**
 * Main module object.
 *
 * @param {String} frame - A CSS selector of the element to be populated by comments.
 * @param {Object} options - Module configuration.
 * @param {String} options.subreddit - The subreddit name.
 * @param {String} [options.url=document.URL] - The URL to retrieve comments for.
 * @param {number} [options.commentsCacheExpiration=5] - Expiration time for
 *     retrieved comments in the `localStorage` cache.
 * @constructor
 * @private
 */
function RedditComments(frame, options) {
    var defaultOptions = {
        url: document.URL,
        commentsCacheExpiration: 5
    };
    if (!('subreddit' in (options || {}))) {
        throw new TypeError('Must specify a "subreddit"');
    }
    api.subreddit = options.subreddit;
    this.options = extend(defaultOptions, options);
    this.frame = query(frame);
    return this;
};

/**
 * Object initialization function.
 *
 * Displays retrieved comments.
 */
RedditComments.prototype.init = function() {
    var rc = this,
        frame = rc.frame;

    rc.getUrlId(rc.options.url).then(function(urlId) {
        return rc.getComments(urlId);
    }).then(function(comments) {
        frame.innerHTML = render({'comments': comments});
    });
};

/**
 * Logs in a Reddit user.
 *
 * @param {String} username
 * @param {String} password
 */
RedditComments.prototype.login = function(username, password) {
};

/**
 * Logs out a Reddit user.
 */
RedditComments.prototype.logout = function() {
};

/**
 * Posts a comment on the Reddit post.
 *
 * @param {String} body - The comment body.
 */
RedditComments.prototype.comment = function(body) {
};

/**
 * Get the comments associated with a URL.
 *
 * @param {String} urlId - Reddit's ID36 of a URL.
 */
RedditComments.prototype.getComments = function(urlId) {
    var rc = this,
        hash = urlId.hashCode().toString(),
        comments = cache.get(hash);

    if (comments != null) {
        // Fake Promise to match the API
        return {
            then: function(resolve, reject) {return resolve(comments);}
        }
    }

    return api.getComments(urlId).then(function(res) {
        var data = JSON.parse(res || {}),
            comments = rc.extractComments(data);
        cache.set(hash, comments, rc.options.commentsCacheExpiration);
        return comments;
    });
};

/**
 * Extract the comment data from Reddit's response and process it for
 * rendering.
 *
 * @param {Object} data - The data as returned by the Reddit API.
 */
RedditComments.prototype.extractComments = function(data) {
    var rc = this,
        cData = [];
    data = (data[1] || data);
    if (!data.data.children) return cData;
    data = data.data.children;
    for (var i = 0; i < data.length; ++i) {
        if (data[i].kind != "t1") continue;
        var replies = [],
            c = data[i].data,
            date = new Date(0),
            vt;
        if (c.replies) {
            replies = rc.extractComments(c.replies);
        }
        date.setUTCSeconds(c.created_utc);
        vt = vagueTime.get({to: date});
        cData.push({author: c.author,
                    created_vague: vt,
                    created_timestamp: date,
                    replies: replies,
                    score: c.ups - c.downs, // XXX: Where is c.score?
                    body: c.body});
    }
    return cData;
};

/**
 * Given a URL, get its ID36.
 *
 * ID36 is the unique ID used by Reddit.
 * @see http://www.reddit.com/dev/api#fullnames
 *
 * @param {String} url
 */
RedditComments.prototype.getUrlId = function(url) {
    var rc = this,
        hash = url.hashCode().toString(),
        urlId = cache.get(hash);

    if (urlId != null) {
        // Fake Promise to match the API
        return {
            then: function(resolve, reject) {return resolve(urlId);}
        }
    }

    return api.getInfo({url: url}).then(function(res) {
        var data = JSON.parse(res || {}).data,
            urlId = rc.extractUrlId(data);
        cache.set(hash, urlId);
        return urlId;
    });
};

/**
 * Extract the URL's ID36 from Reddit's response.
 *
 * @param {Object} data - The data as returned by the Reddit API.
 */
RedditComments.prototype.extractUrlId = function(data) {
    var rc = this;

    if (data && data.children.length) {
        var linkData = data.children[0].data;
        if (!(linkData.subreddit == rc.options.subreddit)) {
            console.log("Post doesn't belong to this subreddit");
        } else {
            return linkData.id;
        }
    }
};
<|endoftext|>


<commit_before>
var peerIo = false;
var peerSocket = false;
var events = require('events');
var fs = require('fs');

var torrentWorker = {
	engine: false,
	_worker: require('workerjs'),
	_workerBee: false,
	_destroyedCB: false,
	_removedCB: false,
	_closedCB: false,
	_portrange: 45032,
	_unusedPort: function(cb) {
		var selfie = this;
		var port = this._portrange;
		this._portrange += 1;
		var server = require('net').createServer();
		server.listen(port, function (err) {
			server.once('close', function () { cb(port) });
			server.close();
		})
		server.on('error', function (err) { selfie._unusedPort(cb) });
	},
	process: function(torLink, opts) {
		if (this.engine) this.engine.removeAllListeners();
		this.engine = new events.EventEmitter();
		opts.target = torLink;
		if (!this._workerBee) {
			var self = this;
			this._unusedPort(function(port) {
				peerIo = require('socket.io').listen(port);
				opts.targetPort = port;
				self._workerBee = new self._worker('../torrent-worker/worker.js', true);

				peerIo.on('connection', function(pSocket){

					peerSocket = pSocket;

					peerSocket.on('interested', function(data) {
						self.engine.emit('interested');
					});

					peerSocket.on('uninterested', function(data) {
						self.engine.emit('uninterested');
					});

					peerSocket.on('listening', function(data) {
						self.engine.server = data;
						self.engine.server.address = function() {
							return { port: data.port }
						};
						self.engine.server.close = function(theCB) {
							self._closedCB = theCB;
							peerSocket.emit('serverClose', { });
						};
						self.engine.emit('listening');
					});

					peerSocket.on('ready', function(data) {

						for (key in data)
							if (data.hasOwnProperty(key))
							  if (Object.prototype.toString.call(data[key]) === '[object Object]') {
								  for (key2 in data[key])
									if (data[key].hasOwnProperty(key2))
									  if (Object.prototype.toString.call(data[key][key2]) === '[object Object]') {
										  for (key3 in data[key][key2])
											if (data[key][key2].hasOwnProperty(key3))
											  if (!Object.prototype.toString.call(data[key][key2][key3]) === '[object Object]') {
												  if (!self.engine[key]) self.engine[key] = {};
												  if (!self.engine[key][key2]) self.engine[key][key2] = {};
												self.engine[key][key2][key3] = data[key][key2][key3];
											  }
									  } else {
										if (!self.engine[key]) self.engine[key] = {};
										self.engine[key][key2] = data[key][key2];
									  }
							  } else
								self.engine[key] = data[key];

						self.engine.torrent.pieces = {};
						self.engine.torrent.pieces.length = data.torrent.pieces.length;

						self.engine.selectFile = function (targetFile) {
							self.engine.files[targetFile].selected = true;
							peerSocket.emit('selectFile', targetFile);
						}

						self.engine.deselectFile = function (targetFile) {
							self.engine.files[targetFile].selected = false;
							peerSocket.emit('deselectFile', targetFile);
						}

						self.engine.flood = function() {
							peerSocket.emit('flood', {});
						};

						self.engine.setPulse = function(peerData) {
							peerSocket.emit('setPulse', peerData);
						};

						self.engine.discover = function() {
							peerSocket.emit('discover', {});
						};

						self.engine.kill = function() {
							peerSocket.emit('kill', {});
						};

						self.engine.swarmSetPaused = function() {
							peerSocket.emit('swarmSetPaused', false);
						};

						self.engine.destroy = function(theCB) {
							self._destroyedCB = theCB;
							peerSocket.emit('engineDestroy', {});
						};

						self.engine.remove = function(theCB) {
							self._removedCB = theCB;
							peerSocket.emit('engineRemove', {});
						};

						var newFiles = data.files;
						self.engine.files = newFiles.map(function (file, index) {

						  file.createReadStream = function (opts) {
							  if (opts) {
								var stream = fs.createReadStream(self.engine.path+'\\'+file.path, opts);
								self.engine.streamFile(index, opts);
							  } else {
								var stream = fs.createReadStream(self.engine.path+'\\'+file.path);
								self.engine.streamFile(index);
							  }

							return stream
						  }

						  return file
						})
						self.engine.emit('ready');
					});

					peerSocket.on('info', function(data) {
						if (self.engine) {
							self.engine.amInterested = data.amInterested;
							self.engine.swarm = {
								wires: {
									length: data.swarm.wires.length
								},
								downloadSpeed: data.swarm.downloadSpeed,
								uploadSpeed: data.swarm.uploadSpeed,
								uploaded: data.swarm.uploaded,
								paused: data.swarm.paused
							};

							data.downloadPieces.forEach(function(pc) {
								self.engine.emit('download', pc);
							});

						}
					});

					peerSocket.on('killed', function() {
						self.engine.emit('killed');
					});

					peerSocket.on('engineDestroyed', function(data) {
						if (self._destroyedCB) {
							self._destroyedCB();
							delete self._destroyedCB;
						}
					});

					peerSocket.on('engineRemoved', function(data) {
						if (self._removedCB) {
							self._removedCB();
							delete self._removedCB;
						}
					});

					peerSocket.on('killed', function() {
						if (self._closedCB) {
							self._closedCB();
							delete self._closedCB;
						}
					});

				});

				self._workerBee.postMessage(opts);

			});
		} else {
			peerSocket.emit('reset', opts);
		}

		return this.engine;
	}
}

module.exports = torrentWorker;
<commit_msg>Added a Callback to engine.kill()<commit_after>
var peerIo = false;
var peerSocket = false;
var events = require('events');

var torrentWorker = {
	engine: false,
	_worker: require('workerjs'),
	_workerBee: false,
	_destroyedCB: false,
	_removedCB: false,
	_killCB: false,
	_closedCB: false,
	_portrange: 45032,
	_unusedPort: function(cb) {
		var selfie = this;
		var port = this._portrange;
		this._portrange += 1;
		var server = require('net').createServer();
		server.listen(port, function (err) {
			server.once('close', function () { cb(port) });
			server.close();
		})
		server.on('error', function (err) { selfie._unusedPort(cb) });
	},
	process: function(torLink, opts) {
		if (this.engine) this.engine.removeAllListeners();
		this.engine = new events.EventEmitter();
		opts.target = torLink;
		if (!this._workerBee) {
			var self = this;
			this._unusedPort(function(port) {
				peerIo = require('socket.io').listen(port);
				opts.targetPort = port;
				self._workerBee = new self._worker('../torrent-worker/worker.js', true);

				peerIo.on('connection', function(pSocket){

					peerSocket = pSocket;

					peerSocket.on('interested', function(data) {
						self.engine.emit('interested');
					});

					peerSocket.on('uninterested', function(data) {
						self.engine.emit('uninterested');
					});

					peerSocket.on('listening', function(data) {
						self.engine.server = data;
						self.engine.server.address = function() {
							return { port: data.port }
						};
						self.engine.server.close = function(theCB) {
							self._closedCB = theCB;
							peerSocket.emit('serverClose', { });
						};
						self.engine.emit('listening');
					});

					peerSocket.on('ready', function(data) {

						for (key in data)
							if (data.hasOwnProperty(key))
							  if (Object.prototype.toString.call(data[key]) === '[object Object]') {
								  for (key2 in data[key])
									if (data[key].hasOwnProperty(key2))
									  if (Object.prototype.toString.call(data[key][key2]) === '[object Object]') {
										  for (key3 in data[key][key2])
											if (data[key][key2].hasOwnProperty(key3))
											  if (!Object.prototype.toString.call(data[key][key2][key3]) === '[object Object]') {
												  if (!self.engine[key]) self.engine[key] = {};
												  if (!self.engine[key][key2]) self.engine[key][key2] = {};
												self.engine[key][key2][key3] = data[key][key2][key3];
											  }
									  } else {
										if (!self.engine[key]) self.engine[key] = {};
										self.engine[key][key2] = data[key][key2];
									  }
							  } else
								self.engine[key] = data[key];

						self.engine.torrent.pieces = {};
						self.engine.torrent.pieces.length = data.torrent.pieces.length;

						self.engine.selectFile = function (targetFile) {
							self.engine.files[targetFile].selected = true;
							peerSocket.emit('selectFile', targetFile);
						}

						self.engine.deselectFile = function (targetFile) {
							self.engine.files[targetFile].selected = false;
							peerSocket.emit('deselectFile', targetFile);
						}

						self.engine.flood = function() {
							peerSocket.emit('flood', {});
						};

						self.engine.setPulse = function(peerData) {
							peerSocket.emit('setPulse', peerData);
						};

						self.engine.discover = function() {
							peerSocket.emit('discover', {});
						};

						self.engine.kill = function(theCB) {
							self._killCB = theCB;
							peerSocket.emit('kill', {});
						};

						self.engine.swarmSetPaused = function() {
							peerSocket.emit('swarmSetPaused', false);
						};

						self.engine.destroy = function(theCB) {
							self._destroyedCB = theCB;
							peerSocket.emit('engineDestroy', {});
						};

						self.engine.remove = function(theCB) {
							self._removedCB = theCB;
							peerSocket.emit('engineRemove', {});
						};

						self.engine.files = data.files;

						self.engine.emit('ready');
					});

					peerSocket.on('info', function(data) {
						if (self.engine) {
							self.engine.amInterested = data.amInterested;
							self.engine.swarm = {
								wires: {
									length: data.swarm.wires.length
								},
								downloadSpeed: data.swarm.downloadSpeed,
								uploadSpeed: data.swarm.uploadSpeed,
								uploaded: data.swarm.uploaded,
								paused: data.swarm.paused
							};

							data.downloadPieces.forEach(function(pc) {
								self.engine.emit('download', pc);
							});

						}
					});

					peerSocket.on('killed', function() {
						if (self._killCB) {
							self._killCB();
							delete self._killCB;
						}
						self.engine.emit('killed');
					});

					peerSocket.on('engineDestroyed', function(data) {
						if (self._destroyedCB) {
							self._destroyedCB();
							delete self._destroyedCB;
						}
					});

					peerSocket.on('engineRemoved', function(data) {
						if (self._removedCB) {
							self._removedCB();
							delete self._removedCB;
						}
					});

				});

				self._workerBee.postMessage(opts);

			});
		} else {
			peerSocket.emit('reset', opts);
		}

		return this.engine;
	}
}

module.exports = torrentWorker;
<|endoftext|>


<commit_before>class Book {
  logSomething() {
    console.log( 'Book.logSomething has been called' );
  }
}

module.exports = Book;
<commit_msg>Change pure ES6 class declaration syntax for consistency with React classes<commit_after>export default class {
  logSomething() {
    console.log( 'Book.logSomething has been called' );
  }
}
<|endoftext|>


<commit_before>var express = require("express");
var methods = require("methods");
var assert = require('assert-diff');
var querystring = require("querystring");
var EventEmitter = require("events").EventEmitter;
var util = require("util");

module.exports = function(port, middlewares) {
  var app = express();

  app.on("error", function(err) {
    throw err;
  });

  app.use(express.json());
  app.use(express.urlencoded());

  // If the user has defined custom middlewares...
  if(middlewares) {
    // Iterate over them...
    middlewares.forEach(function(middleware) {
      // ... and injet them into the Express app
      app.use(middleware);
    });
  }

  app.use(function(req, res, next){
    if (req.is('text/*')) {
      req.text = '';
      req.setEncoding('utf8');
      req.on('data', function(chunk){ req.text += chunk });
      req.on('end', next);
    } else {
      next();
    }
  });

  var server;
  if(port) {
    server = app.listen(port);
  } else {
    server = app.listen();
  }

  methods.forEach(function(method) {
    server[method] = function(path) {
      return new Assertion(app, method, path);
    }
  });

  server.clean = function() {
    app._router.map = {};
  }

  return server;
}

function Assertion(app, method, path) {
  var self = this;
  this.app = app;
  this.method = method;
  this.path = path;
  this.headers = {};
  this.isDone = false;
  this.removeWhenMet = true;

  this.parseExpectedRequestBody = function() {
    if(!self.headers["content-type"]) {
      if(typeof self.data == "string") {
        return self.requestBody = querystring.parse(self.data);
      }
    }
    self.requestBody = self.data;
  }
}

Assertion.prototype.send = function(data) {
  this.data = data;
  return this;
}

Assertion.prototype.query = function(qs) {
  var q;
  if(typeof qs == "string") {
    q = querystring.parse(qs);
  } else {
    q = qs;
  }
  if(!this.qs) {
    this.qs = {};
  }
  for(var n in q) {
    this.qs[n] = q[n];
  }
  return this;
}

Assertion.prototype.set = function(name, value) {
  this.headers[name.toLowerCase()] = value;
  return this;
}

Assertion.prototype.delay = function(ms) {
  this.delay_ms = ms;
  return this;
}

Assertion.prototype.persist = function() {
  this.removeWhenMet = false;
  return this;
}

Assertion.prototype.reply = function(status, responseBody, responseHeaders) {
  this.parseExpectedRequestBody();

  var self = this;

  this.app[this.method](this.path, function(req, res) {
    if(self.qs) {
      assert.deepEqual(req.query, self.qs);
    }
    if(self.requestBody) {
      if(req.text) {
        assert.deepEqual(req.text, self.requestBody);
      } else {
        assert.deepEqual(req.body, self.requestBody);
      }
    }
    for(var name in self.headers) {
      assert.deepEqual(req.headers[name], self.headers[name]);
    }

    if(responseHeaders) {
      res.set(responseHeaders);
    }

    var reply = function() {
        self.handler.emit("done");

        // Remove route from express since the expectation was met
        // Unless this mock is suposed to persist
        if (self.removeWhenMet) self.app._router.map[self.method].splice(req._route_index, 1);

        if (typeof responseBody === 'function') {
          res.status(status).send(responseBody());
        } else {
          res.status(status).send(responseBody);
        }

      };
    if(self.delay_ms) {
      setTimeout(reply, self.delay_ms);
    } else {
      reply();
    }
  });

  this.handler = new Handler(this);
  return this.handler;
}

function Handler(assertion) {
  this.defaults = {
    waitTimeout: 2000
  };
  var self = this;
  this.assertion = assertion;
  this.isDone = false;
  this.on("done", function() {
    self.isDone = true;
  });
}

util.inherits(Handler, EventEmitter);

Handler.prototype.done = function() {
  if(!this.isDone) {
    throw new Error(this.assertion.method + " " + this.assertion.path + " was not made yet.");
  }
}

Handler.prototype.wait = function(ms, fn) {
  if(!fn && typeof ms == "function") {
    fn = ms;
    ms = this.defaults.waitTimeout;
  }

  var self = this;
  var timeout = null;
  var cb = function() {
    clearTimeout(timeout);
    fn();
  }
  this.once("done", cb);
  timeout = setTimeout(function() {
    self.removeListener("done", cb);
    fn(new Error(self.assertion.method + " " + self.assertion.path + " was not called within " + ms + "ms."));
  }, ms);
}
<commit_msg>Pass req to responseBody if reply if it is a function<commit_after>var express = require("express");
var methods = require("methods");
var assert = require('assert-diff');
var querystring = require("querystring");
var EventEmitter = require("events").EventEmitter;
var util = require("util");

module.exports = function(port, middlewares) {
  var app = express();

  app.on("error", function(err) {
    throw err;
  });

  app.use(express.json());
  app.use(express.urlencoded());

  // If the user has defined custom middlewares...
  if(middlewares) {
    // Iterate over them...
    middlewares.forEach(function(middleware) {
      // ... and injet them into the Express app
      app.use(middleware);
    });
  }

  app.use(function(req, res, next){
    if (req.is('text/*')) {
      req.text = '';
      req.setEncoding('utf8');
      req.on('data', function(chunk){ req.text += chunk });
      req.on('end', next);
    } else {
      next();
    }
  });

  var server;
  if(port) {
    server = app.listen(port);
  } else {
    server = app.listen();
  }

  methods.forEach(function(method) {
    server[method] = function(path) {
      return new Assertion(app, method, path);
    }
  });

  server.clean = function() {
    app._router.map = {};
  }

  return server;
}

function Assertion(app, method, path) {
  var self = this;
  this.app = app;
  this.method = method;
  this.path = path;
  this.headers = {};
  this.isDone = false;
  this.removeWhenMet = true;

  this.parseExpectedRequestBody = function() {
    if(!self.headers["content-type"]) {
      if(typeof self.data == "string") {
        return self.requestBody = querystring.parse(self.data);
      }
    }
    self.requestBody = self.data;
  }
}

Assertion.prototype.send = function(data) {
  this.data = data;
  return this;
}

Assertion.prototype.query = function(qs) {
  var q;
  if(typeof qs == "string") {
    q = querystring.parse(qs);
  } else {
    q = qs;
  }
  if(!this.qs) {
    this.qs = {};
  }
  for(var n in q) {
    this.qs[n] = q[n];
  }
  return this;
}

Assertion.prototype.set = function(name, value) {
  this.headers[name.toLowerCase()] = value;
  return this;
}

Assertion.prototype.delay = function(ms) {
  this.delay_ms = ms;
  return this;
}

Assertion.prototype.persist = function() {
  this.removeWhenMet = false;
  return this;
}

Assertion.prototype.reply = function(status, responseBody, responseHeaders) {
  this.parseExpectedRequestBody();

  var self = this;

  this.app[this.method](this.path, function(req, res) {
    if(self.qs) {
      assert.deepEqual(req.query, self.qs);
    }
    if(self.requestBody) {
      if(req.text) {
        assert.deepEqual(req.text, self.requestBody);
      } else {
        assert.deepEqual(req.body, self.requestBody);
      }
    }
    for(var name in self.headers) {
      assert.deepEqual(req.headers[name], self.headers[name]);
    }

    if(responseHeaders) {
      res.set(responseHeaders);
    }

    var reply = function() {
        self.handler.emit("done");

        // Remove route from express since the expectation was met
        // Unless this mock is suposed to persist
        if (self.removeWhenMet) self.app._router.map[self.method].splice(req._route_index, 1);

        if (typeof responseBody === 'function') {
          res.status(status).send(responseBody(req));
        } else {
          res.status(status).send(responseBody);
        }

      };
    if(self.delay_ms) {
      setTimeout(reply, self.delay_ms);
    } else {
      reply();
    }
  });

  this.handler = new Handler(this);
  return this.handler;
}

function Handler(assertion) {
  this.defaults = {
    waitTimeout: 2000
  };
  var self = this;
  this.assertion = assertion;
  this.isDone = false;
  this.on("done", function() {
    self.isDone = true;
  });
}

util.inherits(Handler, EventEmitter);

Handler.prototype.done = function() {
  if(!this.isDone) {
    throw new Error(this.assertion.method + " " + this.assertion.path + " was not made yet.");
  }
}

Handler.prototype.wait = function(ms, fn) {
  if(!fn && typeof ms == "function") {
    fn = ms;
    ms = this.defaults.waitTimeout;
  }

  var self = this;
  var timeout = null;
  var cb = function() {
    clearTimeout(timeout);
    fn();
  }
  this.once("done", cb);
  timeout = setTimeout(function() {
    self.removeListener("done", cb);
    fn(new Error(self.assertion.method + " " + self.assertion.path + " was not called within " + ms + "ms."));
  }, ms);
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import dragula from 'dragula';
import { getComponentName, layoutAttr, editAttr, componentListProp, componentListClass, pageAreaClass, dropAreaClass, dragItemClass, dragItemUnsavedClass, refAttr, refProp } from '../utils/references';
import { getData, getSchema } from '../core-data/components';
import { getComponentEl } from '../utils/component-elements';
import store from '../core-data/store';

/**
 * Save the order of the items as found in the DOM.
 * @param {Element} el
 * @param {{ref: string, path: string}} options
 * @returns {Promise}
 */
function updateOrder(el) {
  const componentEl = getComponentEl(el),
    uri = componentEl.getAttribute(layoutAttr) || componentEl.getAttribute(refAttr),
    path = el.getAttribute(editAttr),
    list = getData(uri, path),
    childEls = el.querySelectorAll(':scope > [' + refAttr + ']'); // only get direct children of the list;

  let newList = [];

  if (_.isArray(list)) {
    // data is in the current component. save it!
    newList = _.map(childEls, (childEl) => {
      return {
        [refProp]: childEl.getAttribute(refAttr)
      };
    });

    if (_.get(store, 'state.ui.currentFocus')) {
      // save an open child component's form before saving the parent component
      return store.dispatch('unfocus').then(() => store.dispatch('saveComponent', { uri, data: { [path]: newList }}));
    } else {
      return store.dispatch('saveComponent', { uri, data: { [path]: newList }});
    }
  } else {
    // data is in a list
    newList = _.map(childEls, (childEl) => childEl.getAttribute(refAttr));

    if (_.get(store, 'state.ui.currentFocus')) {
      // save an open child component's form before saving the page
      return store.dispatch('unfocus').then(() => store.dispatch('savePage', { [path]: newList }));
    } else {
      return store.dispatch('savePage', { [path]: newList });
    }
  }
}

/**
 * get the number of components between the handle and container
 * @param {Element} handle
 * @param {Element} container
 * @returns {number}
 */
function getComponentDepth(handle, container) {
  let cursor = handle,
    depth = 0;

  // note: Element#matches doesn't work on all browsers, limiting our support
  while (cursor && !cursor.matches('html') && cursor !== container) {
    cursor = cursor.parentNode; // iterate up through the elements
    if (cursor.getAttribute(refAttr)) {
      depth++; // every time you hit a component, add to the depth
    }
  }

  return depth; // return the number of you passed through
}

/**
 * determine if a component is draggable inside a specific container
 * @param {Element} handle
 * @param {Element} container
 * @returns {boolean}
 */
function isDraggable(handle, container) {
  // components are draggable if the handle is the component element and it's a direct child of the container (depth 0)
  // OR if the handle is some OTHER element inside the direct child component (depth 1)
  return !!handle.hasAttribute(refAttr) && getComponentDepth(handle, container) === 0
    || !handle.hasAttribute(refAttr) && getComponentDepth(handle, container) === 1;
}

function addDragula(el) {
  const drag = dragula([el], {
    deadzone: 20,
    ignoreInputTextSelection: true, // allow selecting text in draggable components
    moves(selectedItem, container, handle) {
      // only allow direct child components of a list to be dragged
      // this allows for nested component lists + dragdrop
      return selectedItem.hasAttribute(refAttr) && getComponentName(selectedItem.getAttribute(refAttr)) !== 'clay-kiln' && isDraggable(handle, container);
    }
  });

  // add event listeners to reorder components
  // auto-scroll when you drag to the edge of the window
  drag.on('cloned', function (mirror) {
    const buffer = 40;

    let dragging = window.setInterval(() => {
      const rect = mirror.getBoundingClientRect();

      if (!drag.dragging) {
        window.clearInterval(dragging);
      } else if (rect.top < buffer) {
        window.scrollBy(0, -buffer * 2);
      } else if (window.innerHeight - rect.bottom < buffer) {
        window.scrollBy(0, buffer * 2);
      }
    }, 250);
  });
  // add classes when you start dragging
  drag.on('drag', function (selectedItem, container) {
    selectedItem.classList.add(dragItemClass);
    container.classList.add(dropAreaClass);
  });
  // remove classes when you cancel dragging
  drag.on('cancel', function (selectedItem, container) {
    selectedItem.classList.remove(dragItemClass);
    container.classList.remove(dropAreaClass);
  });
  // handle reordering
  drag.on('drop', function (selectedItem, container) {
    selectedItem.classList.add(dragItemUnsavedClass);
    selectedItem.classList.remove(dragItemClass);
    container.classList.remove(dropAreaClass);
    updateOrder(el).then(() => {
      selectedItem.classList.remove(dragItemUnsavedClass);
    });
  });
}

/**
 * decorate component list
 * @param {Element} el
 * @param {object} componentList
 */
function addComponentList(el, componentList) {
  const isPage = componentList.page;

  // add a class so we can easily reference it later
  el.classList.add(componentListClass);
  if (isPage) {
    el.classList.add(pageAreaClass);
  }

  // enable dragula
  addDragula(el);
}

/**
 * decorate component list if specified in the schema
 * @param  {string} uri
 * @param  {Element} el with data-editable
 */
export default function handler(uri, el) {
  const path = el.getAttribute(editAttr),
    schema = getSchema(uri, path); // note: component lists are ALWAYS a single field, so we don't need co call groups.get

  if (schema && schema[componentListProp]) {
    addComponentList(el, schema[componentListProp]);
  }
}
<commit_msg>increase drag deadzone<commit_after>import _ from 'lodash';
import dragula from 'dragula';
import { getComponentName, layoutAttr, editAttr, componentListProp, componentListClass, pageAreaClass, dropAreaClass, dragItemClass, dragItemUnsavedClass, refAttr, refProp } from '../utils/references';
import { getData, getSchema } from '../core-data/components';
import { getComponentEl } from '../utils/component-elements';
import store from '../core-data/store';

/**
 * Save the order of the items as found in the DOM.
 * @param {Element} el
 * @param {{ref: string, path: string}} options
 * @returns {Promise}
 */
function updateOrder(el) {
  const componentEl = getComponentEl(el),
    uri = componentEl.getAttribute(layoutAttr) || componentEl.getAttribute(refAttr),
    path = el.getAttribute(editAttr),
    list = getData(uri, path),
    childEls = el.querySelectorAll(':scope > [' + refAttr + ']'); // only get direct children of the list;

  let newList = [];

  if (_.isArray(list)) {
    // data is in the current component. save it!
    newList = _.map(childEls, (childEl) => {
      return {
        [refProp]: childEl.getAttribute(refAttr)
      };
    });

    if (_.get(store, 'state.ui.currentFocus')) {
      // save an open child component's form before saving the parent component
      return store.dispatch('unfocus').then(() => store.dispatch('saveComponent', { uri, data: { [path]: newList }}));
    } else {
      return store.dispatch('saveComponent', { uri, data: { [path]: newList }});
    }
  } else {
    // data is in a list
    newList = _.map(childEls, (childEl) => childEl.getAttribute(refAttr));

    if (_.get(store, 'state.ui.currentFocus')) {
      // save an open child component's form before saving the page
      return store.dispatch('unfocus').then(() => store.dispatch('savePage', { [path]: newList }));
    } else {
      return store.dispatch('savePage', { [path]: newList });
    }
  }
}

/**
 * get the number of components between the handle and container
 * @param {Element} handle
 * @param {Element} container
 * @returns {number}
 */
function getComponentDepth(handle, container) {
  let cursor = handle,
    depth = 0;

  // note: Element#matches doesn't work on all browsers, limiting our support
  while (cursor && !cursor.matches('html') && cursor !== container) {
    cursor = cursor.parentNode; // iterate up through the elements
    if (cursor.getAttribute(refAttr)) {
      depth++; // every time you hit a component, add to the depth
    }
  }

  return depth; // return the number of you passed through
}

/**
 * determine if a component is draggable inside a specific container
 * @param {Element} handle
 * @param {Element} container
 * @returns {boolean}
 */
function isDraggable(handle, container) {
  // components are draggable if the handle is the component element and it's a direct child of the container (depth 0)
  // OR if the handle is some OTHER element inside the direct child component (depth 1)
  return !!handle.hasAttribute(refAttr) && getComponentDepth(handle, container) === 0
    || !handle.hasAttribute(refAttr) && getComponentDepth(handle, container) === 1;
}

function addDragula(el) {
  const drag = dragula([el], {
    deadzone: 50,
    ignoreInputTextSelection: true, // allow selecting text in draggable components
    moves(selectedItem, container, handle) {
      // only allow direct child components of a list to be dragged
      // this allows for nested component lists + dragdrop
      return selectedItem.hasAttribute(refAttr) && getComponentName(selectedItem.getAttribute(refAttr)) !== 'clay-kiln' && isDraggable(handle, container);
    }
  });

  // add event listeners to reorder components
  // auto-scroll when you drag to the edge of the window
  drag.on('cloned', function (mirror) {
    const buffer = 40;

    let dragging = window.setInterval(() => {
      const rect = mirror.getBoundingClientRect();

      if (!drag.dragging) {
        window.clearInterval(dragging);
      } else if (rect.top < buffer) {
        window.scrollBy(0, -buffer * 2);
      } else if (window.innerHeight - rect.bottom < buffer) {
        window.scrollBy(0, buffer * 2);
      }
    }, 250);
  });
  // add classes when you start dragging
  drag.on('drag', function (selectedItem, container) {
    selectedItem.classList.add(dragItemClass);
    container.classList.add(dropAreaClass);
  });
  // remove classes when you cancel dragging
  drag.on('cancel', function (selectedItem, container) {
    selectedItem.classList.remove(dragItemClass);
    container.classList.remove(dropAreaClass);
  });
  // handle reordering
  drag.on('drop', function (selectedItem, container) {
    selectedItem.classList.add(dragItemUnsavedClass);
    selectedItem.classList.remove(dragItemClass);
    container.classList.remove(dropAreaClass);
    updateOrder(el).then(() => {
      selectedItem.classList.remove(dragItemUnsavedClass);
    });
  });
}

/**
 * decorate component list
 * @param {Element} el
 * @param {object} componentList
 */
function addComponentList(el, componentList) {
  const isPage = componentList.page;

  // add a class so we can easily reference it later
  el.classList.add(componentListClass);
  if (isPage) {
    el.classList.add(pageAreaClass);
  }

  // enable dragula
  addDragula(el);
}

/**
 * decorate component list if specified in the schema
 * @param  {string} uri
 * @param  {Element} el with data-editable
 */
export default function handler(uri, el) {
  const path = el.getAttribute(editAttr),
    schema = getSchema(uri, path); // note: component lists are ALWAYS a single field, so we don't need co call groups.get

  if (schema && schema[componentListProp]) {
    addComponentList(el, schema[componentListProp]);
  }
}
<|endoftext|>


<commit_before>var download    = require('download'),
    spinner     = require('cli-spinner').Spinner,
    path        = require('path'),
    walker      = require('walker'),
    fse         = require('fs-extra'),
    replace     = require('replace'),
    solution    = {};

if(process.argv.length < 3 || process.argv[2].length === 0)
{
    console.error("Please provide a valid path to your source files.");
    process.exit(1);
}

var isPathValid = function (dirPath) {
    return fse.existsSync(dirPath);
};

var isValidFile = function (filePath) {
    return (filePath.indexOf('.cs') === filePath.length - 3);
};

var isEditorScript = function (pathReference, scriptFile) {

    for(var i = 0; i < pathReference.length; i++)
    {
        if(scriptFile.indexOf(pathReference[i]) > -1)
        {
            return true;
        }
    }
    return false;
};

var invertSlashes = function (string) {
    return string.replace(/\//ig, '\\');
};

var preprocessPath = function (element, index, array) {
    array[index] = '<Compile Include="' + invertSlashes(element) + '" />';
};

var placeSolution = function (sourceCodePath) {
    var targetPath = path.resolve(sourceCodePath + '/..');
    fse.copySync('./template', targetPath);
    return targetPath;
};

var writeScripts = function (solutionPath, scripts) {
    replace({
        regex: '{{SCRIPTITEMS}}',
        replacement: scripts.join('\n'),
        paths: [solutionPath],
        recursive: false,
        silent: true,
        preview: false
    });
};

var prepareReferences = function(solutionPath) {
    var dl = new download({ extract: true, strip: 1 });
    dl.get('https://github.com/malud/unity-libs/archive/5.0.0f4.zip').dest(solutionPath);
    var spi = new spinner('Downloading references...');
    spi.setSpinnerString(10);
    spi.start();

    dl.run(function (err, files) {
        if(err)
        {
            throw err;
        }

        spi.stop(true);
        console.log('Solution is prepared now.');
        replace({
            regex: '{{REFERENCEPATH}}',
            replacement: invertSlashes(path.resolve(path.join(solutionPath, 'References'))),
            paths: [solutionPath],
            recursive: true,
            silent: true
        });
    });
};

solution.create = function (pathParam) {
    if(!isPathValid(pathParam))
    {
        console.error('Path does not exist.');
        return false;
    }

    var unityEditorRelated = [];
    var playerFiles = [];
    var editorFiles = [];

    walker(fullPath)
        .on('dir', function (dir, stat) {
            if(dir.indexOf('Editor') > -1)
            {
                var isChildEditorPath = false;
                for(var i = 0; i < unityEditorRelated.length; i++)
                {
                    if(dir.indexOf(unityEditorRelated[i]) === 0)
                    {
                        isChildEditorPath = true;
                        break;
                    }
                }
                if(!isChildEditorPath) unityEditorRelated.push(dir);
            }
        })
        .on('file', function (file, stat) {
            if(isValidFile(file))
            {
                if(isEditorScript(unityEditorRelated, file))
                {
                    editorFiles.push(file);
                } else
                {
                    playerFiles.push(file);
                }
            }
        })
        .on('end', function() {
            playerFiles.forEach(preprocessPath);
            editorFiles.forEach(preprocessPath);
            slnPath = placeSolution(pathParam);
            writeScripts(path.join(slnPath, 'Assembly-CSharp.csproj'), playerFiles);
            writeScripts(path.join(slnPath, 'Assembly-CSharp-Editor.csproj'), editorFiles);
            prepareReferences(slnPath);
        })
    ;
};

var fullPath = path.resolve(process.argv[2]);
solution.create(fullPath);

module.exports = solution;<commit_msg>relative template path<commit_after>var download    = require('download'),
    spinner     = require('cli-spinner').Spinner,
    path        = require('path'),
    walker      = require('walker'),
    fse         = require('fs-extra'),
    replace     = require('replace'),
    solution    = {};

if(process.argv.length < 3 || process.argv[2].length === 0)
{
    console.error("Please provide a valid path to your source files.");
    process.exit(1);
}

var isPathValid = function (dirPath) {
    return fse.existsSync(dirPath);
};

var isValidFile = function (filePath) {
    return (filePath.indexOf('.cs') === filePath.length - 3);
};

var isEditorScript = function (pathReference, scriptFile) {

    for(var i = 0; i < pathReference.length; i++)
    {
        if(scriptFile.indexOf(pathReference[i]) > -1)
        {
            return true;
        }
    }
    return false;
};

var invertSlashes = function (string) {
    return string.replace(/\//ig, '\\');
};

var preprocessPath = function (element, index, array) {
    array[index] = '<Compile Include="' + invertSlashes(element) + '" />';
};

var placeSolution = function (sourceCodePath) {
    var targetPath = path.resolve(sourceCodePath + '/..');
    fse.copySync(path.join(__dirname, 'template'), targetPath);
    return targetPath;
};

var writeScripts = function (solutionPath, scripts) {
    replace({
        regex: '{{SCRIPTITEMS}}',
        replacement: scripts.join('\n'),
        paths: [solutionPath],
        recursive: false,
        silent: true,
        preview: false
    });
};

var prepareReferences = function(solutionPath) {
    var dl = new download({ extract: true, strip: 1 });
    dl.get('https://github.com/malud/unity-libs/archive/5.0.0f4.zip').dest(solutionPath);
    var spi = new spinner('Downloading references...');
    spi.setSpinnerString(10);
    spi.start();

    dl.run(function (err, files) {
        if(err)
        {
            throw err;
        }

        spi.stop(true);
        console.log('Solution is prepared now.');
        replace({
            regex: '{{REFERENCEPATH}}',
            replacement: invertSlashes(path.resolve(path.join(solutionPath, 'References'))),
            paths: [solutionPath],
            recursive: true,
            silent: true
        });
    });
};

solution.create = function (pathParam) {
    if(!isPathValid(pathParam))
    {
        console.error('Path does not exist.');
        return false;
    }

    var unityEditorRelated = [];
    var playerFiles = [];
    var editorFiles = [];

    walker(fullPath)
        .on('dir', function (dir, stat) {
            if(dir.indexOf('Editor') > -1)
            {
                var isChildEditorPath = false;
                for(var i = 0; i < unityEditorRelated.length; i++)
                {
                    if(dir.indexOf(unityEditorRelated[i]) === 0)
                    {
                        isChildEditorPath = true;
                        break;
                    }
                }
                if(!isChildEditorPath) unityEditorRelated.push(dir);
            }
        })
        .on('file', function (file, stat) {
            if(isValidFile(file))
            {
                if(isEditorScript(unityEditorRelated, file))
                {
                    editorFiles.push(file);
                } else
                {
                    playerFiles.push(file);
                }
            }
        })
        .on('end', function() {
            playerFiles.forEach(preprocessPath);
            editorFiles.forEach(preprocessPath);
            slnPath = placeSolution(pathParam);
            writeScripts(path.join(slnPath, 'Assembly-CSharp.csproj'), playerFiles);
            writeScripts(path.join(slnPath, 'Assembly-CSharp-Editor.csproj'), editorFiles);
            prepareReferences(slnPath);
        })
    ;
};

var fullPath = path.resolve(process.argv[2]);
solution.create(fullPath);

module.exports = solution;<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This is a fork/based on Small Tabs, written by ロシア,
 * https://addons.mozilla.org/en-US/firefox/addon/small-tabs/
 */

"use strict";

Components.utils.import("resource://gre/modules/Services.jsm");

var ThinTabs = {

	getWindows : function() {
		var windows = [];

		var browserWindows = Services.wm.getEnumerator("navigator:browser");

		while (browserWindows.hasMoreElements()) {
			var browserWindow = browserWindows.getNext();
			browserWindow.QueryInterface(Components.interfaces.nsIDOMWindow);
			windows.push(browserWindow);
		}

		return windows;
	},

	handleEvent : function(e) {
		var doc = e.target;
		var win = doc.defaultView;

		win.removeEventListener("load", this, true);

		if (doc.documentElement.getAttribute("windowtype") != "navigator:browser") {
			return;
		}

		this.loadScript(win);
	},

	loadStyle : function() {
		var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
				.getService(Components.interfaces.nsIStyleSheetService);
		var uri = Services.io.newURI("resource://thintabs/thintabs.css", null, null);

		if (!sss.sheetRegistered(uri, sss.USER_SHEET)) {
			sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
		}
	},

	unloadStyle : function() {
		var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
				.getService(Components.interfaces.nsIStyleSheetService);
		var uri = Services.io.newURI("resource://thintabs/thintabs.css", null, null);

		if (sss.sheetRegistered(uri, sss.USER_SHEET)) {
			sss.unregisterSheet(uri, sss.USER_SHEET);
		}
	},

	loadScript : function(window) {
	},

	unloadScript : function(window) {
	},

	onOpenWindow : function(window) {
		var domWindow = window.docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(
				Components.interfaces.nsIDOMWindow);
		domWindow.addEventListener("load", this, true);
	},

	onCloseWindow : function(window) {
	},

	onWindowTitleChange : function(window, title) {
	},

	init : function() {
		this.loadStyle();

		Services.wm.addListener(this);

		this.getWindows().forEach(function(window) {
			this.loadScript(window);
		}, this);
	},

	uninit : function() {
		this.unloadStyle();

		Services.wm.removeListener(this);

		this.getWindows().forEach(function(window) {
			this.unloadScript(window);
		}, this);
	}
};

var ThinTabsResourceAlias = {
	register : function(alias, data) {
		if (this._resourceProtocolHandler) {
			return false;
		}

		this._resourceProtocolHandler = Services.io.getProtocolHandler("resource");
		this._resourceProtocolHandler.QueryInterface(Components.interfaces.nsIResProtocolHandler);

		var uri = data.resourceURI;

		if (!uri) {
			if (data.installPath.isDirectory()) {
				// packed
				uri = ios.newFileURI(data.installPath);
			} else {
				// unpacked
				var jarProtocolHandler = Services.io.getProtocolHandler("jar");
				jarProtocolHandler.QueryInterface(Components.interfaces.nsIJARProtocolHandler);
				var spec = "jar:" + Services.io.newFileURI(data.installPath).spec + "!/";
				uri = jarProtocolHandler.newURI(spec, null, null);
			}
		}

		this._resourceProtocolHandler.setSubstitution("thintabs", uri);

		return true;
	},

	unregister : function() {
		if (!this._resourceProtocolHandler) {
			return false;
		}

		this._resourceProtocolHandler.setSubstitution("thintabs", null);

		delete this._resourceProtocolHandler;
		delete this._alias;

		return true;
	}
}

function startup(data, reason) {
	ThinTabsResourceAlias.register("thintabs", data);
	ThinTabs.init();
}

function shutdown(data, reason) {
	ThinTabsResourceAlias.unregister();
	ThinTabs.uninit();
}

function install(data, reason) {
}

function uninstall(data, reason) {
}
<commit_msg>Fixed the stupid stuff I just comitted.<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This is a fork/based on Small Tabs, written by ロシア,
 * https://addons.mozilla.org/en-US/firefox/addon/small-tabs/
 */

"use strict";

Components.utils.import("resource://gre/modules/Services.jsm");

var ThinTabs = {

	getWindows : function() {
		var windows = [];

		var browserWindows = Services.wm.getEnumerator("navigator:browser");

		while (browserWindows.hasMoreElements()) {
			var browserWindow = browserWindows.getNext();
			browserWindow.QueryInterface(Components.interfaces.nsIDOMWindow);
			windows.push(browserWindow);
		}

		return windows;
	},

	handleEvent : function(event) {
		var document = event.target;
		var window = document.defaultView;

		window.removeEventListener("load", this, true);

		if (document.documentElement.getAttribute("windowtype") != "navigator:browser") {
			return;
		}

		this.loadScript(window);
	},

	loadStyle : function() {
		var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
				.getService(Components.interfaces.nsIStyleSheetService);
		var uri = Services.io.newURI("resource://thintabs/thintabs.css", null, null);

		if (!sss.sheetRegistered(uri, sss.USER_SHEET)) {
			sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
		}
	},

	unloadStyle : function() {
		var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
				.getService(Components.interfaces.nsIStyleSheetService);
		var uri = Services.io.newURI("resource://thintabs/thintabs.css", null, null);

		if (sss.sheetRegistered(uri, sss.USER_SHEET)) {
			sss.unregisterSheet(uri, sss.USER_SHEET);
		}
	},

	loadScript : function(window) {
	},

	unloadScript : function(window) {
	},

	onOpenWindow : function(window) {
		var domWindow = window.docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(
				Components.interfaces.nsIDOMWindow);
		domWindow.addEventListener("load", this, true);
	},

	onCloseWindow : function(window) {
	},

	onWindowTitleChange : function(window, title) {
	},

	init : function() {
		this.loadStyle();

		Services.wm.addListener(this);

		this.getWindows().forEach(function(window) {
			this.loadScript(window);
		}, this);
	},

	uninit : function() {
		this.unloadStyle();

		Services.wm.removeListener(this);

		this.getWindows().forEach(function(window) {
			this.unloadScript(window);
		}, this);
	}
};

var ThinTabsResourceAlias = {
	register : function(data) {
		if (this._resourceProtocolHandler) {
			return false;
		}

		this._resourceProtocolHandler = Services.io.getProtocolHandler("resource");
		this._resourceProtocolHandler.QueryInterface(Components.interfaces.nsIResProtocolHandler);

		var uri = data.resourceURI;

		if (!uri) {
			if (data.installPath.isDirectory()) {
				// packed
				uri = ios.newFileURI(data.installPath);
			} else {
				// unpacked
				var jarProtocolHandler = Services.io.getProtocolHandler("jar");
				jarProtocolHandler.QueryInterface(Components.interfaces.nsIJARProtocolHandler);
				var spec = "jar:" + Services.io.newFileURI(data.installPath).spec + "!/";
				uri = jarProtocolHandler.newURI(spec, null, null);
			}
		}

		this._resourceProtocolHandler.setSubstitution("thintabs", uri);

		return true;
	},

	unregister : function() {
		if (!this._resourceProtocolHandler) {
			return false;
		}

		this._resourceProtocolHandler.setSubstitution("thintabs", null);

		delete this._resourceProtocolHandler;
		delete this._alias;

		return true;
	}
}

function startup(data, reason) {
	ThinTabsResourceAlias.register(data);
	ThinTabs.init();
}

function shutdown(data, reason) {
	ThinTabsResourceAlias.unregister();
	ThinTabs.uninit();
}

function install(data, reason) {
}

function uninstall(data, reason) {
}
<|endoftext|>


<commit_before>var RBTree = require('bintrees').RBTree

function Index (comparator) {
    this.tree = new RBTree(comparator)
}

Index.prototype.added = function () {
}

Index.prototype.pushed = function (procession, node) {
    this.tree.insert(node)
}

Index.prototype.shifted = function (procession, node) {
    this.tree.remove(node)
}

Index.prototype.removed = function () {
    this.tree.clear()
}
<commit_msg>Export `Index`.<commit_after>var RBTree = require('bintrees').RBTree

function Index (comparator) {
    this.tree = new RBTree(comparator)
}

Index.prototype.added = function () {
}

Index.prototype.pushed = function (procession, node) {
    this.tree.insert(node)
}

Index.prototype.shifted = function (procession, node) {
    this.tree.remove(node)
}

Index.prototype.removed = function () {
    this.tree.clear()
}

module.exports = Index
<|endoftext|>


<commit_before>module.exports = {
  systemBusy:                         { code: -1,     message: 'system busy, retry later'},
  success:                            { code: 0,      message: 'success'},
  internalError:                      { code: 1,      message: 'internal error, contact us'},
  requireAppKey:                      { code: 10001,  message: 'require appKey'},
  requireAppSecret:                   { code: 10002,  message: 'require appSecret'},
  requireDeviceUdid:                  { code: 10003,  message: 'require deviceUdid'},
  invalidAppKey:                      { code: 10004,  message: 'invalid appKey'},
  invalidAppSecret:                   { code: 10005,  message: 'invalid appSecret'},
  failedToSaveDevice:                 { code: 10006,  message: 'failed to create/update device, contact us'},
  invalidToken:                       { code: 10007,  message: 'invalid token'},
  tokenExpired:                       { code: 10008,  message: 'token is expired'},
  failedToGenerateToken:              { code: 10009,  message: 'failed to generate token, contact us'},
  requireToken:                       { code: 10010,  message: 'require token'},
  requireDataFile:                    { code: 10011,  message: 'require uploaded data file'},
  requireAppBundle:                   { code: 10012,  message: 'require appBundle'},
  failedToGetApp:                     { code: 10013,  message: 'rpc error, failed to Get App'},
  requireUsername:                    { code: 11001,  message: 'require username'},
  requirePassword:                    { code: 11002,  message: 'require password'},
  userNotExist:                       { code: 11003,  message: 'user not exist'},
  passwordNotMatch:                   { code: 11004,  message: 'password not match'},
  failedToCreateUser:                 { code: 11006,  message: 'failed to create user'},
  failedToHashPassword:               { code: 11007,  message: 'failed to hash password'},
  failedToSaveUser:                   { code: 11008,  message: 'failed to save user, please check if required field is correct'},
  failedToSaveFile:                   { code: 11009,  message: 'failed to save file'},
  failedToDeleteFile:                 { code: 11010,  message: 'failed to delete file'},
  fileNotExist:                       { code: 11011,  message: 'file not exist'},
  failedToReadFile:                   { code: 11012,  message: 'error when read file'},
  requireClientKey:                   { code: 11014,  message: 'require clientKey'},
  requireClientSecret:                { code: 11015,  message: 'require clientSecret'},
  clientNotExist:                     { code: 11016,  message: 'client not exist'},
  invalidClientKey:                   { code: 11017,  message: 'invalid clientKey'},
  invalidClientSecret:                { code: 11018,  message: 'invalid clientSecret'},
  requirePoi:                         { code: 11020,  message: 'require poi'},
  requireOwner:                       { code: 11021,  message: 'require owner'},
  pendingPoiPullRequestExists:        { code: 11020,  message: 'pending poi pull request exists'},
  failedToUpdatePoi:                  { code: 11021,  message: 'failed to update poi'},
  failedToCreateDevice:               { code: 40001,  message: 'failed to create device, contact us'},
  failedToGetDevice:                  { code: 40002,  message: 'failed to get device, contact us'},
  failedToUpdateDevice:               { code: 40003,  message: 'failed to update device, contact us'},
  failedToQueueDeviceDataCollectJob:  { code: 40004,  message: 'failed to queue device data collect job'},
  failedToQueuePoiImportJob:          { code: 40005,  message: 'failed to queue poi import job'},
  failedToFindRegions:                { code: 40006,  message: 'failed to find regions'},
  failedToFindPois:                   { code: 40007,  message: 'failed to find pois'},
  failedToEnsureDevice:               { code: 40008,  message: 'rpc error, failed to ensure device'},
  requirePoiId:                       { code: 40009,  message: 'require poi id'},
  poiNotExist:                        { code: 40010,  message: 'poi not exist'},
  requirePoiPullRequest:              { code: 40011,  message: 'require poi pull request info'},
  requirePoiPullRequestId:            { code: 40012,  message: 'require poi pull request id'},
  poiNotReady:                        { code: 40013,  message: 'poi not ready'},
  failedToFindPoiPullRequest:         { code: 40014,  message: 'failed to find poi pull request, contact us'},
  poiPullRequestNotExist:             { code: 40015,  message: 'poi pull request not exist'},
  poiPullRequestNotActive:            { code: 40016,  message: 'poi pull request not active'},
  failedToUpdatePoiPullRequest:       { code: 40017,  message: 'failed to update poi pull request'},
  requireAttachment:                  { code: 40018,  message: 'require attachment info'}
};
<commit_msg>add app/scenario api error codes<commit_after>module.exports = {
  systemBusy:                         { code: -1,    message: 'system busy, retry later'},
  success:                            { code: 0,     message: 'success'},
  internalError:                      { code: 1,     message: 'internal error, contact us'},
  requireAppKey:                      { code: 10001, message: 'require appKey'},
  requireAppSecret:                   { code: 10002, message: 'require appSecret'},
  requireDeviceUdid:                  { code: 10003, message: 'require deviceUdid'},
  invalidAppKey:                      { code: 10004, message: 'invalid appKey'},
  invalidAppSecret:                   { code: 10005, message: 'invalid appSecret'},
  failedToSaveDevice:                 { code: 10006, message: 'failed to create/update device, contact us'},
  invalidToken:                       { code: 10007, message: 'invalid token'},
  tokenExpired:                       { code: 10008, message: 'token is expired'},
  failedToGenerateToken:              { code: 10009, message: 'failed to generate token, contact us'},
  requireToken:                       { code: 10010, message: 'require token'},
  requireDataFile:                    { code: 10011, message: 'require uploaded data file'},
  requireAppBundle:                   { code: 10012, message: 'require appBundle'},
  failedToGetApp:                     { code: 10013, message: 'rpc error, failed to Get App'},
  requireUsername:                    { code: 11001, message: 'require username'},
  requirePassword:                    { code: 11002, message: 'require password'},
  userNotExist:                       { code: 11003, message: 'user not exist'},
  passwordNotMatch:                   { code: 11004, message: 'password not match'},
  failedToCreateUser:                 { code: 11006, message: 'failed to create user'},
  failedToHashPassword:               { code: 11007, message: 'failed to hash password'},
  failedToSaveUser:                   { code: 11008, message: 'failed to save user, please check if required field is correct'},
  failedToSaveFile:                   { code: 11009, message: 'failed to save file'},
  failedToDeleteFile:                 { code: 11010, message: 'failed to delete file'},
  fileNotExist:                       { code: 11011, message: 'file not exist'},
  failedToReadFile:                   { code: 11012, message: 'error when read file'},
  requireClientKey:                   { code: 11014, message: 'require clientKey'},
  requireClientSecret:                { code: 11015, message: 'require clientSecret'},
  clientNotExist:                     { code: 11016, message: 'client not exist'},
  invalidClientKey:                   { code: 11017, message: 'invalid clientKey'},
  invalidClientSecret:                { code: 11018, message: 'invalid clientSecret'},
  requirePoi:                         { code: 11020, message: 'require poi'},
  requireOwner:                       { code: 11021, message: 'require owner'},
  pendingPoiPullRequestExists:        { code: 11020, message: 'pending poi pull request exists'},
  failedToUpdatePoi:                  { code: 11021, message: 'failed to update poi'},
  failedToCreateDevice:               { code: 40001, message: 'failed to create device, contact us'},
  failedToGetDevice:                  { code: 40002, message: 'failed to get device, contact us'},
  failedToUpdateDevice:               { code: 40003, message: 'failed to update device, contact us'},
  failedToQueueDeviceDataCollectJob:  { code: 40004, message: 'failed to queue device data collect job'},
  failedToQueuePoiImportJob:          { code: 40005, message: 'failed to queue poi import job'},
  failedToFindRegions:                { code: 40006, message: 'failed to find regions'},
  failedToFindPois:                   { code: 40007, message: 'failed to find pois'},
  failedToEnsureDevice:               { code: 40008, message: 'rpc error, failed to ensure device'},
  requirePoiId:                       { code: 40009, message: 'require poi id'},
  poiNotExist:                        { code: 40010, message: 'poi not exist'},
  requirePoiPullRequest:              { code: 40011, message: 'require poi pull request info'},
  requirePoiPullRequestId:            { code: 40012, message: 'require poi pull request id'},
  poiNotReady:                        { code: 40013, message: 'poi not ready'},
  failedToFindPoiPullRequest:         { code: 40014, message: 'failed to find poi pull request, contact us'},
  poiPullRequestNotExist:             { code: 40015, message: 'poi pull request not exist'},
  poiPullRequestNotActive:            { code: 40016, message: 'poi pull request not active'},
  failedToUpdatePoiPullRequest:       { code: 40017, message: 'failed to update poi pull request'},
  requireAttachment:                  { code: 40018, message: 'require attachment info'},
  requireScenario:                    { code: 40019, message: 'require scenario'},
  requireScenarioId:                  { code: 40020, message: 'require scenario id'},
  failedToFindScenario:               { code: 40021, message: 'failed to find scenario'},
  scenarioNotExist:                   { code: 40022, message: 'scenario not exist'},
  failedToFindApp:                    { code: 41002, message: 'failed to get app, check if appKey is valid'},
  appNotExist:                        { code: 41003, message: 'app not exist'}
};
<|endoftext|>


<commit_before>import React from 'react'

export default () =>
<commit_msg>Mock up Buildings<commit_after>import React, { Component } from 'react'
import _pickBy from 'lodash/pickBy'

import API from './api'

export default class Buildings extends Component {
  constructor () {
    super()
    this.data = {
      buildings: []
    }
    this.state = Object.assign({}, this.data)
  }

  componentDidMount () {
    this.loadData()
  }

  // Get clients
  loadData () {
    let { filters, currentPage, sort } = this.state
    let _filters = _pickBy(filters, filter => filter.length > 0)
    // let page = currentPage > 1 ? {page: currentPage} : {}
    let params = Object.assign({}, _filters)
    API.Buildings.GetList(params)
      .then(response => {
        console.log(response)
        this.setState({buildings: response.edificios})
      })
  }

  renderTable () {
    let { buildings } = this.state
    let table = (
Cargando...
)
    if (buildings.length > 0) {
      let buildingsList = buildings.map((building, index) => {
        return (
          <tr
            key={`buildings-${index}`}
          >
            {building.address}
            {building.colony}
            {building.status}
            {building.mapsLink}
            {building.comments}

        )
      })
      table = (

                Nombre
                Edad
                Sexo
                Estado
                Comentarios

              {buildingsList}

      )
    }
    return table
  }
  render () {
    return (

        {this.renderTable()}

    )
  }
}
<|endoftext|>


<commit_before>var path = require('path');
var mcss = require('mcss');
var loaderUtils = require('loader-utils');

module.exports = function(content) {
    this.cacheable && this.cacheable();

    var callback = this.async();
    var options = loaderUtils.parseQuery(this.query);

    options.filename = this.resource; //fix the path bug: @import string contain char like '../../'

    var include;
    var cwd = process.cwd();

    if (options.include) {
        if (!Array.isArray(options.include)) { options.include = [ options.include ]; }
        include = options.include.map(function (p) {
            return path.resolve(cwd, p);
        });
    }

    var instance = mcss(options);

    if (include) { instance.include(include); }

    instance.translate(content).done(function(text) {
        callback(null, text);
    }).fail(function(err) {
        callback(err);
    });
};
<commit_msg>feat: add dependency for imports (#9)<commit_after>const path = require('path');
const mcss = require('mcss');
const loaderUtils = require('loader-utils');
const { Translator, Interpreter } = mcss

module.exports = function(content) {
    this.cacheable && this.cacheable();

    const callback = this.async();
    const options = loaderUtils.parseQuery(this.query);

    options.filename = this.resource; //fix the path bug: @import string contain char like '../../'

    // include to pathes
    if (options.include) {
      options.pathes = options.pathes || [];
      options.pathes.concat(ensureArray(options.include));
    }

    // path to absolute
    if (Array.isArray(options.pathes)) {
      const cwd = process.cwd();
      options.pathes = options.pathes.map(function (p) {
          return path.resolve(cwd, p);
      });
    }

    translate(content, options).then(result => {
      result.imports.forEach(imp => {
        this.addDependency(imp);
      });
      callback(null, result.css || '');
    }).catch(e => {
      callback(e);
    });
};

function ensureArray(target) {
  if (!target) {
    return []
  }

  if (Array.isArray(target)) {
    return target
  }

  return [target]
}

function translate(string, options) {
  const instance = mcss(options);

  const translator = new Translator(options);
  const interpreter = new Interpreter(options);

  const walkers = options.walkers;
  if (walkers.length){
      walkers.forEach(function(hook){
          hook && interpreter.on(hook);
      })
  }

  return new Promise(function(resolve, reject) {
    instance.parse(string).done(function(ast) {
      try{
          ast = interpreter.interpret(ast);

          resolve( {
            css: translator.translate(ast),
            imports: interpreter._globalImports || []
          } )
      }catch(e){
          reject(e);
      }
    } ).fail( e => {
      reject(e);
    } )
  });
}
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

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

io.on('connection', function(socket){
  //First what client do is emit current chat data
  /**
   *  chatData = {
   *    userName,
   *    rommName
   *  }
   */
  socket.on('enter room', function(chatData){
    socket.chatData = chatData;

    socket.join(socket.chatData.roomName);

    sendMessageFromServer(socket, socket.chatData.userName + " connected.");

     socket.on('chat message', function(data){
       socket.broadcast.to(socket.chatData.roomName).emit('chat message', data);
     });

     socket.on('name change', function(newName){
       var oldName = socket.chatData.userName;
       socket.chatData.userName = newName;
       sendMessageFromServer(socket, oldName + " changes name to " + newName + ".");
     });

     socket.on('disconnect', function(data){
       sendMessageFromServer(socket, socket.chatData.userName + " disconnected.");
     });
  });
});

http.listen(process.env.PORT || 5000, function(){
  console.log('listening on *:' + process.env.PORT || 5000);
});

var sendMessageFromServer = function(socket, content){
  var msg = {
      key: (new Date()).getTime(),
      sender: "Chat",
      content: content,
      power: 0,
      isFromServer: true
  };

  socket.broadcast.to(socket.chatData.roomName).emit('chat message', msg);
}<commit_msg>Server now sends just enough data to clients<commit_after>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

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

io.on('connection', function(socket){
  //First what client do is emit current chat data
  /**
   *  chatData = {
   *    userName,
   *    rommName
   *  }
   */
  socket.on('enter room', function(chatData){
    socket.chatData = chatData;

    socket.join(socket.chatData.roomName);

    sendMessageFromServer(socket, socket.chatData.userName + " connected.");

     socket.on('chat message', function(data){
       socket.broadcast.to(socket.chatData.roomName).emit('chat message', data);
     });

     socket.on('name change', function(newName){
       var oldName = socket.chatData.userName;
       socket.chatData.userName = newName;
       sendMessageFromServer(socket, oldName + " changes name to " + newName + ".");
     });

     socket.on('disconnect', function(data){
       sendMessageFromServer(socket, socket.chatData.userName + " disconnected.");
     });
  });
});

http.listen(process.env.PORT || 5000, function(){
  console.log('listening on *:' + process.env.PORT || 5000);
});

var sendMessageFromServer = function(socket, content){
  var msg = {
      content: content,
      isFromServer: true
  };

  socket.broadcast.to(socket.chatData.roomName).emit('chat message', msg);
}<|endoftext|>


<commit_before>'use strict';
import express from 'express';
import path from 'path';
require('dotenv').config({path: path.resolve(__dirname, './.env')});
import bodyParser from  'body-parser';
import errorHandler from 'errorhandler';
import methodOverride from 'method-override';

import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
import { Provider }  from 'react-redux';
import { match, RoutingContext } from 'react-router';

import AppReducer from './src/js/reducers/reducers.js';
import App from './src/js/components/app.jsx';
import routes from './src/js/components/routes.jsx';

var port = parseInt(process.env.PORT, 10) || 8000;
var app = express();

app.use(handleRender);

function handleRender(req, res) {
    // Note that req.url here should be the full URL path from
    // the original request, including the query string.
    console.log(routes);
    match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
        if (error) {
            res.status(500).send(error.message);
        } else if (redirectLocation) {
            res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        } else if (renderProps) {
            res.status(200).send(renderToString(<RoutingContext {...renderProps} />));
        } else {
            res.status(404).send('Not found');
        }
    });
};

function renderFullPage(html, initialState) {
    return `
    <!doctype html>

    <title>Redux Universal Example</title>

${html}

    `;
};

app.use(express.static(__dirname + '/public'));
app.get('/*', function (request, response){
    response.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

app.use(methodOverride());

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(errorHandler({
    dumpExceptions: true,
    showStack: true
}));

app.listen(port);
console.log('server started on port ' + port);
<commit_msg>Reversed to old server<commit_after>'use strict';
var express = require('express');
var path = require('path');
require('dotenv').config({path: path.resolve(__dirname, '.env')});
var app = express();
var bodyParser = require('body-parser');
var errorHandler = require('errorhandler');
var methodOverride = require('method-override');
var port = parseInt(process.env.PORT, 10) || 8000;

app.use(express.static(__dirname + '/public'));
app.get('/*', function (request, response){
    response.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

app.use(methodOverride());

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(errorHandler({
    dumpExceptions: true,
    showStack: true
}));

app.listen(port);
console.log('server started on port ' + port);
<|endoftext|>