<commit_before>'use strict';

var _    = require('lodash');
var path = require('path');

var utility  = require('./utility');

function copyDocs() {
  var input  = path.join(dir.root, 'docs', '*.rst'),
      output = path.join(dir.build, 'docs');

  return {
    logDocs: { task: ['log', 'Copying documentation.'] },
    readDocs: {
      requires: 'logDocs',
      task: ['glob', { pattern: input }]
    },
    writeDocsLog: {
      requires: 'readDocs',
      task: ['log', 'Writing documentation.']
    },
    writeDocs: { requires: 'writeDocsLog', task: ['dest', output] }
  };
}

module.exports = function(commander) {
  var amdArgs, hljsExt, output, requiresTask, tasks,
      replace           = utility.replace,
      regex             = utility.regex,
      replaceClassNames = utility.replaceClassNames,

      readArgs     = { pattern: path.join('src', '**', '*.js') },
      filterCB     = utility.buildFilterCallback(commander.args),
      replaceArgs  = replace(regex.header, ''),
      templateArgs = { _: 'hljs.registerLanguage(\'<%= name %>\',' +
                          ' <%= content %>);\n'
                     , highlight: 'var hljs = new <%= content %>();\n'
                     };

  tasks = {
    startlog: { task: ['log', 'Building highlight.js pack file.'] },
    read: { requires: 'startlog', task: ['glob', readArgs] },
    filter: { requires: 'read', task: ['filter', filterCB] },
    reorder: { requires: 'filter', task: 'reorderDeps' },
    replace: { requires: 'reorder', task: ['replace', replaceArgs] },
    template: { requires: 'replace', task: ['template', templateArgs] },
    concat: { requires: 'template', task: 'concat' }
  };
  requiresTask = 'concat';

  if(commander.compress || commander.target === 'cdn') {
    tasks.compresslog = {
      requires: requiresTask,
      task: ['log', 'Compressing highlight.js pack file.']
    };

    tasks.replace2 = {
      requires: 'compresslog',
      task: [ 'replaceSkippingStrings'
            , replace(regex.replaces, replaceClassNames)
            ]
    };

    tasks.replace3 = {
      requires: 'replace2',
      task: ['replace', replace(regex.classname, '$1.className')]
    };

    tasks.minify  = { requires: 'replace3', task: 'jsminify' };
    requiresTask  = 'minify';
  }

  tasks.writelog = {
    requires: requiresTask,
    task: ['log', 'Writing highlight.js pack file.']
  };

  hljsExt = commander.target === 'cdn' ? 'min' : 'pack';
  output  = path.join(dir.build, 'highlight.' + hljsExt + '.js');

  tasks.write = {
    requires: 'writelog',
    task: ['write', output]
  };

  if(commander.target === 'browser') {
    tasks = _.merge(copyDocs(), tasks);
  }

  return tasks;
};
<commit_msg>Change browser build to use new template task<commit_after>'use strict';

var _    = require('lodash');
var path = require('path');

var utility  = require('./utility');

function copyDocs() {
  var input  = path.join(dir.root, 'docs', '*.rst'),
      output = path.join(dir.build, 'docs');

  return {
    logDocs: { task: ['log', 'Copying documentation.'] },
    readDocs: {
      requires: 'logDocs',
      task: ['glob', { pattern: input }]
    },
    writeDocsLog: {
      requires: 'readDocs',
      task: ['log', 'Writing documentation.']
    },
    writeDocs: { requires: 'writeDocsLog', task: ['dest', output] }
  };
}

module.exports = function(commander) {
  var amdArgs, hljsExt, output, requiresTask, tasks,
      replace           = utility.replace,
      regex             = utility.regex,
      replaceClassNames = utility.replaceClassNames,

      readArgs     = { pattern: path.join('src', '**', '*.js') },
      filterCB     = utility.buildFilterCallback(commander.args),
      replaceArgs  = replace(regex.header, ''),
      templateArgs = { template: 'hljs.registerLanguage(' +
                          '\'<%= name %>\', <%= content %>);\n'
                     , skip: 'highlight'
                     };

  tasks = {
    startlog: { task: ['log', 'Building highlight.js pack file.'] },
    read: { requires: 'startlog', task: ['glob', readArgs] },
    filter: { requires: 'read', task: ['filter', filterCB] },
    reorder: { requires: 'filter', task: 'reorderDeps' },
    replace: { requires: 'reorder', task: ['replace', replaceArgs] },
    template: { requires: 'replace', task: ['template', templateArgs] },
    concat: { requires: 'template', task: 'concat' }
  };
  requiresTask = 'concat';

  if(commander.compress || commander.target === 'cdn') {
    tasks.compresslog = {
      requires: requiresTask,
      task: ['log', 'Compressing highlight.js pack file.']
    };

    tasks.replace2 = {
      requires: 'compresslog',
      task: [ 'replaceSkippingStrings'
            , replace(regex.replaces, replaceClassNames)
            ]
    };

    tasks.replace3 = {
      requires: 'replace2',
      task: ['replace', replace(regex.classname, '$1.className')]
    };

    tasks.minify  = { requires: 'replace3', task: 'jsminify' };
    requiresTask  = 'minify';
  }

  tasks.writelog = {
    requires: requiresTask,
    task: ['log', 'Writing highlight.js pack file.']
  };

  hljsExt = commander.target === 'cdn' ? 'min' : 'pack';
  output  = path.join(dir.build, 'highlight.' + hljsExt + '.js');

  tasks.write = {
    requires: 'writelog',
    task: ['write', output]
  };

  if(commander.target === 'browser') {
    tasks = _.merge(copyDocs(), tasks);
  }

  return tasks;
};
<|endoftext|>


<commit_before>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

// a more explicit promisification for redis client

// also see more automated attempt using es6-promisify:
// https://github.com/evanx/redex/blob/master/lib/redisPromisified.js

import lodash from 'lodash';
import redis from 'redis';

import Paths from './Paths';
import Loggers from './Loggers';

const logger = Loggers.create(module.filename, 'info');

const state = {
   count: 0,
   clients: new Set()
};

function createClient(options) {
   state.count++;
   let redisClient = redis.createClient(options || {});
   state.clients.add(redisClient);
   redisClient.on('error', err => {
      logger.error('redis error:', err);
   });
   return redisClient;
}

function createCallback(resolve, reject) {
   return (err, reply) => {
      if (err) {
         logger.debug('redis reject error:', err);
         reject(err);
      } else {
         logger.debug('redis resolve:', reply);
         resolve(reply);
      }
   };
}

function createPromise(fn) {
   return new Promise((resolve, reject) => fn(createCallback(resolve, reject)));
}

export default class Redis {

   // @param client
   // client maybe null e.g. if constructed with empty options object i.e. {}
   // if no options, then client is created

   constructor(options) {
      if (options) {
         if (lodash.isString(options)) {
            this.source = Paths.basename(options);
            this.client = createClient();
            logger.info('construct', state.count, this.source);
         } else if (options === {}) {
            logger.info('construct defer');
         } else if (options.client) {
            this.client = options.client;
            logger.info('construct wrapper');
         } else if (options.source) {
            this.source = Files.basename(options.source);
            this.client = createClient(options);
            logger.info('construct', state.count, this.source);
         } else if (options.return_buffers || options.dbNumber) {
            this.client = createClient(options);
         } else {
            throw 'Invalid options: ' + options.toString();
         }
      } else {
         this.client = createClient();
         logger.info('construct', state.count);
      }
      if (this.client) {
         this.init(options);
      }
   }

   init(options) {
      if (!this.client) {
         this.client = createClient(options);
      }
      if (Redis.dbNumber) { // use alternative database for all connections
         this.select(Redis.dbNumber);
      } else if (options && options.dbNumber) {
         this.select(options.dbNumber);
      }
   }

   select(dbNumber) {
      return createPromise(cb => this.client.select(dbNumber, cb));
   }

   end() {
      if (this.client) {
         if (state.clients.size > 0) {
            state.clients.delete(this.client);
            logger.info('end', state.clients.size, this.source);
         } else {
            logger.error('end');
         }
         this.client.end();
         this.client = null;
      }
   }

   time() {
      return createPromise(cb => this.client.time(cb));
   }

   timeSeconds() {
      return this.time().then(time => {
         return parseInt(time[0]);
      });
   }

   del(key) {
      return createPromise(cb => this.client.del(key, cb));
   }

   get(key) {
      return createPromise(cb => this.client.get(key, cb));
   }

   exists(key) {
      return createPromise(cb => this.client.exists(key, cb));
   }

   expire(key, seconds) {
      return createPromise(cb => this.client.expire(key, seconds, cb));
   }

   mget(keys) {
      return createPromise(cb => this.client.mget(keys, cb));
   }

   set(key, value) {
      return createPromise(cb => this.client.set(key, value, cb));
   }

   setex(key, seconds, value) {
      return createPromise(cb => this.client.setex(key, seconds, value, cb));
   }

   setnx(key, value) {
      return createPromise(cb => this.client.setnx(key, value, cb));
   }

   sadd(key, member) {
      return createPromise(cb => this.client.sadd(key, member, cb));
   }

   sismember(key, member) {
      return createPromise(cb => this.client.sismember(key, member, cb));
   }

   smembers(key) {
      return createPromise(cb => this.client.smembers(key, cb));
   }

   srem(key, member) {
      return createPromise(cb => this.client.srem(key, member, cb));
   }

   scard(key) {
      return createPromise(cb => this.client.scard(key, cb));
   }

   hdel(key, field) {
      return createPromise(cb => this.client.hdel(key, field, cb));
   }

   hget(key, field) {
      return createPromise(cb => this.client.hget(key, field, cb));
   }

   hgetall(key) {
      return createPromise(cb => this.client.hgetall(key, cb));
   }

   hkeys(key) {
      return createPromise(cb => this.client.hkeys(key, cb));
   }

   hmset(key, value) {
      return createPromise(cb => this.client.hmset(key, value, cb));
   }

   hset(key, field, value) {
      return createPromise(cb => this.client.hset(key, field, value, cb));
   }

   hsetnx(key, field, value) {
      return createPromise(cb => this.client.hsetnx(key, field, value, cb));
   }

   lindex(key, index) {
      return createPromise(cb => this.client.lindex(key, index, cb));
   }

   linsert(key, position, pivot, value) {
      return createPromise(cb => this.client.linsert(key, position, pivot, value, cb));
   }

   lrem(key, count, value) {
      return createPromise(cb => this.client.lrem(key, count, value, cb));
   }

   lset(key, index, value) {
      return createPromise(cb => this.client.lset(key, index, value, cb));
   }

   llen(key) {
      return createPromise(cb => this.client.llen(key, cb));
   }

   ltrim(key, start, stop) {
      return createPromise(cb => this.client.ltrim(key, start, stop, cb));
   }

   lrange(key, start, stop) {
      return createPromise(cb => this.client.lrange(key, start, stop, cb));
   }

   lpush(key, value) {
      return createPromise(cb => this.client.lpush(key, value, cb));
   }

   rpush(key, value) {
      return createPromise(cb => this.client.rpush(key, value, cb));
   }

   lpop(key) {
      return createPromise(cb => this.client.lpop(key, cb));
   }

   rpop(key) {
      return createPromise(cb => this.client.rpop(key, cb));
   }

   blpop(key, timeout) {
      return createPromise(cb => this.client.blpop(key, timeout, cb));
   }

   brpop(key, timeout) {
      return createPromise(cb => this.client.brpop(key, timeout, cb));
   }

   rpoplpush(source, destination) {
      return createPromise(cb => this.client.rpoplpush(source, destination, cb));
   }

   brpoplpush(source, destination, timeout) {
      return createPromise(cb => this.client.brpoplpush(source, destination, timeout, cb));
   }

   zrange(key, start, stop) {
      return createPromise(cb => this.client.zrange(key, start, stop, cb));
   }

   zrem(key, member) {
      return createPromise(cb => this.client.zrem(key, member, cb));
   }

   zrevrange(key, start, stop) {
      return createPromise(cb => this.client.zrevrange(key, start, stop, cb));
   }

   // TODO all the rest, see https://github.com/mranney/node_redis/blob/master/lib/commands.js

   multi() {
      let multi = this.client.multi();
      multi.execCallback = multi.exec.bind(multi); // TODO
      multi.exec = function() {
         return createPromise(cb => multi.execCallback(cb));
      };
      return multi;
   }
}

// see test: https://github.com/evanx/redex/blob/master/test/redisPromised.js
<commit_msg>redis<commit_after>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

// a more explicit promisification for redis client

// also see more automated attempt using es6-promisify:
// https://github.com/evanx/redex/blob/master/lib/redisPromisified.js

import lodash from 'lodash';
import redis from 'redis';

import Paths from './Paths';
import Loggers from './Loggers';

const logger = Loggers.create(module.filename, 'info');

const state = {
   count: 0,
   clients: new Set()
};

function createClient(options) {
   state.count++;
   let redisClient = redis.createClient(options || {});
   state.clients.add(redisClient);
   redisClient.on('error', err => {
      logger.error('redis error:', err);
   });
   return redisClient;
}

function createCallback(resolve, reject) {
   return (err, reply) => {
      if (err) {
         logger.debug('redis reject error:', err);
         reject(err);
      } else {
         logger.debug('redis resolve:', reply);
         resolve(reply);
      }
   };
}

function createPromise(fn) {
   return new Promise((resolve, reject) => fn(createCallback(resolve, reject)));
}

export default class Redis {

   // @param client
   // client maybe null e.g. if constructed with empty options object i.e. {}
   // if no options, then client is created

   constructor(options) {
      if (options) {
         if (lodash.isString(options)) {
            this.source = Paths.basename(options);
            this.client = createClient();
            logger.info('construct', state.count, this.source);
         } else if (options === {}) {
            logger.info('construct defer');
         } else if (options.client) {
            this.client = options.client;
            logger.info('construct wrapper');
         } else if (options.source) {
            this.source = Files.basename(options.source);
            this.client = createClient(options);
            logger.info('construct', state.count, this.source);
         } else if (options.return_buffers || options.dbNumber) {
            this.client = createClient(options);
         } else {
            throw 'Invalid options: ' + options.toString();
         }
      } else {
         this.client = createClient();
         logger.info('construct', state.count);
      }
      if (this.client) {
         this.init(options);
      }
   }

   init(options) {
      if (!this.client) {
         this.client = createClient(options);
      }
      if (Redis.dbNumber) { // use alternative database for all connections
         this.select(Redis.dbNumber);
      } else if (options && options.dbNumber) {
         this.select(options.dbNumber);
      }
   }

   select(dbNumber) {
      return createPromise(cb => this.client.select(dbNumber, cb));
   }

   end() {
      if (this.client) {
         if (state.clients.size > 0) {
            state.clients.delete(this.client);
            logger.info('end', state.clients.size, this.source);
         } else {
            logger.error('end');
         }
         this.client.end();
         this.client = null;
      }
   }

   time() {
      return createPromise(cb => this.client.time(cb));
   }

   timeSeconds() {
      return this.time().then(time => {
         return parseInt(time[0]);
      });
   }

   del(key) {
      return createPromise(cb => this.client.del(key, cb));
   }

   get(key) {
      return createPromise(cb => this.client.get(key, cb));
   }

   exists(key) {
      return createPromise(cb => this.client.exists(key, cb));
   }

   expire(key, seconds) {
      return createPromise(cb => this.client.expire(key, seconds, cb));
   }

   mget(keys) {
      return createPromise(cb => this.client.mget(keys, cb));
   }

   set(key, value) {
      return createPromise(cb => this.client.set(key, value, cb));
   }

   setex(key, seconds, value) {
      return createPromise(cb => this.client.setex(key, seconds, value, cb));
   }

   setnx(key, value) {
      return createPromise(cb => this.client.setnx(key, value, cb));
   }

   sadd(key, member) {
      return createPromise(cb => this.client.sadd(key, member, cb));
   }

   sismember(key, member) {
      return createPromise(cb => this.client.sismember(key, member, cb));
   }

   smembers(key) {
      return createPromise(cb => this.client.smembers(key, cb));
   }

   srem(key, member) {
      return createPromise(cb => this.client.srem(key, member, cb));
   }

   scard(key) {
      return createPromise(cb => this.client.scard(key, cb));
   }

   hdel(key, ...fields) {
      return createPromise(cb => this.client.hdel(key, fields, cb));
   }

   hget(key, field) {
      return createPromise(cb => this.client.hget(key, field, cb));
   }

   hgetall(key) {
      return createPromise(cb => this.client.hgetall(key, cb));
   }

   hkeys(key) {
      return createPromise(cb => this.client.hkeys(key, cb));
   }

   hmset(key, value) {
      return createPromise(cb => this.client.hmset(key, value, cb));
   }

   hset(key, field, value) {
      return createPromise(cb => this.client.hset(key, field, value, cb));
   }

   hsetnx(key, field, value) {
      return createPromise(cb => this.client.hsetnx(key, field, value, cb));
   }

   lindex(key, index) {
      return createPromise(cb => this.client.lindex(key, index, cb));
   }

   linsert(key, position, pivot, value) {
      return createPromise(cb => this.client.linsert(key, position, pivot, value, cb));
   }

   lrem(key, count, value) {
      return createPromise(cb => this.client.lrem(key, count, value, cb));
   }

   lset(key, index, value) {
      return createPromise(cb => this.client.lset(key, index, value, cb));
   }

   llen(key) {
      return createPromise(cb => this.client.llen(key, cb));
   }

   ltrim(key, start, stop) {
      return createPromise(cb => this.client.ltrim(key, start, stop, cb));
   }

   lrange(key, start, stop) {
      return createPromise(cb => this.client.lrange(key, start, stop, cb));
   }

   lpush(key, value) {
      return createPromise(cb => this.client.lpush(key, value, cb));
   }

   rpush(key, value) {
      return createPromise(cb => this.client.rpush(key, value, cb));
   }

   lpop(key) {
      return createPromise(cb => this.client.lpop(key, cb));
   }

   rpop(key) {
      return createPromise(cb => this.client.rpop(key, cb));
   }

   blpop(key, timeout) {
      return createPromise(cb => this.client.blpop(key, timeout, cb));
   }

   brpop(key, timeout) {
      return createPromise(cb => this.client.brpop(key, timeout, cb));
   }

   rpoplpush(source, destination) {
      return createPromise(cb => this.client.rpoplpush(source, destination, cb));
   }

   brpoplpush(source, destination, timeout) {
      return createPromise(cb => this.client.brpoplpush(source, destination, timeout, cb));
   }

   zrange(key, start, stop) {
      return createPromise(cb => this.client.zrange(key, start, stop, cb));
   }

   zrem(key, member) {
      return createPromise(cb => this.client.zrem(key, member, cb));
   }

   zrevrange(key, start, stop) {
      return createPromise(cb => this.client.zrevrange(key, start, stop, cb));
   }

   // TODO all the rest, see https://github.com/mranney/node_redis/blob/master/lib/commands.js

   multi() {
      let multi = this.client.multi();
      multi.execCallback = multi.exec.bind(multi); // TODO
      multi.exec = function() {
         return createPromise(cb => multi.execCallback(cb));
      };
      return multi;
   }
}

// see test: https://github.com/evanx/redex/blob/master/test/redisPromised.js
<|endoftext|>


<commit_before>var RomoWordBoundaryFilter = function(filterString, setElems, getElemTextContentCallback) {
  this.boundaryCharsRegex = /[\s-_]+/;
  this.matchingNodes      = [];
  this.notMatchingNodes   = [];
  this.filters            = filterString
                              .trim()
                              .toLowerCase()
                              .split(this.boundaryCharsRegex);

  Romo.toArray(setElems).forEach($.proxy(function(node) {
    var contentStack = getElemTextContentCallback($(node))
                         .trim()
                         .toLowerCase()
                         .split(this.boundaryCharsRegex).reverse();

    var match = this.filters.reduce($.proxy(function(filterMatch, filter) {
      if (filterMatch === false) {
        // short-circuit the reduce
        return false;
      } else {
        var contentMatch = false;
        do {
          var content = contentStack.pop();
          if (content !== undefined && content.indexOf(filter) === 0) {
            contentMatch = true;
            // we found a match for this filter so we need to
            // break out of this do...while and go to next filter
            content = undefined;
          }
        } while(content !== undefined);
        return contentMatch;
      }
    }, this), true);

    if (match === true) {
      this.matchingNodes.push(node);
    } else {
      this.notMatchingNodes.push(node);
    }
  }, this));

  this.matchingElems    = $(this.matchingNodes);
  this.notMatchingElems = $(this.notMatchingNodes);
}
<commit_msg>Update `RomoWordBoundaryFilter` component to not use jquery<commit_after>var RomoWordBoundaryFilter = function(filterString, setElems, getElemTextContentCallback) {
  this.boundaryCharsRegex = /[\s-_]+/;
  this.matchingElems      = [];
  this.notMatchingElems   = [];
  this.filters            = filterString
                              .trim()
                              .toLowerCase()
                              .split(this.boundaryCharsRegex);

  Romo.array(setElems).forEach(Romo.proxy(function(elem) {
    var contentStack = getElemTextContentCallback(elem)
                         .trim()
                         .toLowerCase()
                         .split(this.boundaryCharsRegex).reverse();

    var match = this.filters.reduce(Romo.proxy(function(filterMatch, filter) {
      if (filterMatch === false) {
        // short-circuit the reduce
        return false;
      } else {
        var contentMatch = false;
        do {
          var content = contentStack.pop();
          if (content !== undefined && content.indexOf(filter) === 0) {
            contentMatch = true;
            // we found a match for this filter so we need to
            // break out of this do...while and go to next filter
            content = undefined;
          }
        } while(content !== undefined);
        return contentMatch;
      }
    }, this), true);

    if (match === true) {
      this.matchingElems.push(elem);
    } else {
      this.notMatchingElems.push(elems);
    }
  }, this));
}
<|endoftext|>


<commit_before>const RxMongo = require('./RxMongo');
const Rx = require('rx');

const RxCursor = (function(){
    function RxCursor(observableCursor){
        this.rxCursor = observableCursor;
    }

    /**
     * Sorts the cursor result based on the specified properties
     * @param {Object} sort
     * @return {RxCursor} RxCursor - a new instance of RxCursor
     */
    RxCursor.prototype.sort = function(sort){
        return new RxCursor(this.rxCursor.flatMap(cursor => RxMongo.sort(cursor, sort)));
    }

    /**
     * Limits the cursor result to the specified number of items
     * @param {Number} count
     * @return {RxCursor} RxCursor - a new instance of RxCursor
     */
    RxCursor.prototype.limit = function(count){
        return new RxCursor(this.rxCursor.flatMap(cursor => RxMongo.limit(cursor, count)));
    }

    /**
     * Skips a specified number of items in the cursor
     * @param {Number} count
     * @return {RxCursor} RxCursor - a new instance of RxCursor
     */
    RxCursor.prototype.skip = function(count){
        return new RxCursor(this.rxCursor.flatMap(cursor => RxMongo.skip(cusror, count)))
    }

    /**
     * Maps a doc from one type to another
     * @param {Function} func
     * @return {Object} object - the return value of the func
     */
    RxCursor.prototype.map = function(func){
        return this.rxCursor.flatMap(cursor => RxMongo.map(cursor, func));
    }

    /**
     * Counts the number of items in the cursor
     * @return {Number} number - a new instance of RxCursor
     */
    RxCursor.prototype.count = function(){
        return this.rxCursor.flatMap(cursor => RxMongo.countByCursor(cursor));
    }

    /**
     * Returns a single value from the cursor, throws error if more than one item ewxists in the cursor.
     * Undefined is returned if the cursor contains no items.
     * @return {Object} object - The object returned from the cursor
     */
    RxCursor.prototype.single = function(){
        return Rx.Observable.create.call(this, s => {
            this.toArray()
                .subscribe(arr => {
                    if(arr.length > 1){
                        s.onError(new Error('Result set contains more than one element'));
                        s.onCompleted();
                        return;
                    }

                    if(arr.length > 0) {
                        s.onNext(arr[0]);
                    } else {
                        s.onNext(undefined);
                    }

                    s.onCompleted();
                });
        });
    }

    /**
     * Returns the first value from the cursor. Undefined is returned if the cursor contains no items.
     * @return {Object} object - The first object returned from the cursor
     */
    RxCursor.prototype.first = function(){
        return this.limit(1)
                    .toArray()
                    .map(arr => {
                        if(arr.length > 0) {
                            return arr[0];
                        } else {
                            return undefined;
                        }
                    });
    }

    /**
     * Returns the cursor result set as an array.
     * @return {Array} array - the results
     */
    RxCursor.prototype.toArray = function(){
        return this.rxCursor.flatMap(cursor => RxMongo.toArray(cursor));
    }

    return RxCursor;
})();

module.exports = RxCursor;<commit_msg>Added limit call in .single() method<commit_after>const RxMongo = require('./RxMongo');
const Rx = require('rx');

const RxCursor = (function(){
    function RxCursor(observableCursor){
        this.rxCursor = observableCursor;
    }

    /**
     * Sorts the cursor result based on the specified properties
     * @param {Object} sort
     * @return {RxCursor} RxCursor - a new instance of RxCursor
     */
    RxCursor.prototype.sort = function(sort){
        return new RxCursor(this.rxCursor.flatMap(cursor => RxMongo.sort(cursor, sort)));
    }

    /**
     * Limits the cursor result to the specified number of items
     * @param {Number} count
     * @return {RxCursor} RxCursor - a new instance of RxCursor
     */
    RxCursor.prototype.limit = function(count){
        return new RxCursor(this.rxCursor.flatMap(cursor => RxMongo.limit(cursor, count)));
    }

    /**
     * Skips a specified number of items in the cursor
     * @param {Number} count
     * @return {RxCursor} RxCursor - a new instance of RxCursor
     */
    RxCursor.prototype.skip = function(count){
        return new RxCursor(this.rxCursor.flatMap(cursor => RxMongo.skip(cusror, count)))
    }

    /**
     * Maps a doc from one type to another
     * @param {Function} func
     * @return {Object} object - the return value of the func
     */
    RxCursor.prototype.map = function(func){
        return this.rxCursor.flatMap(cursor => RxMongo.map(cursor, func));
    }

    /**
     * Counts the number of items in the cursor
     * @return {Number} number - a new instance of RxCursor
     */
    RxCursor.prototype.count = function(){
        return this.rxCursor.flatMap(cursor => RxMongo.countByCursor(cursor));
    }

    /**
     * Returns a single value from the cursor, throws error if more than one item ewxists in the cursor.
     * Undefined is returned if the cursor contains no items.
     * @return {Object} object - The object returned from the cursor
     */
    RxCursor.prototype.single = function(){
        return Rx.Observable.create.call(this, s => {
            this.limit(2)
                .toArray()
                .subscribe(arr => {
                    if(arr.length > 1){
                        s.onError(new Error('Result set contains more than one element'));
                        s.onCompleted();
                        return;
                    }

                    if(arr.length > 0) {
                        s.onNext(arr[0]);
                    } else {
                        s.onNext(undefined);
                    }

                    s.onCompleted();
                });
        });
    }

    /**
     * Returns the first value from the cursor. Undefined is returned if the cursor contains no items.
     * @return {Object} object - The first object returned from the cursor
     */
    RxCursor.prototype.first = function(){
        return this.limit(1)
                    .toArray()
                    .map(arr => {
                        if(arr.length > 0) {
                            return arr[0];
                        } else {
                            return undefined;
                        }
                    });
    }

    /**
     * Returns the cursor result set as an array.
     * @return {Array} array - the results
     */
    RxCursor.prototype.toArray = function(){
        return this.rxCursor.flatMap(cursor => RxMongo.toArray(cursor));
    }

    return RxCursor;
})();

module.exports = RxCursor;<|endoftext|>


<commit_before>QuizEngine.module('Quiz', function(Quiz) {

    Quiz.QuizQuestionView = Marionette.ItemView.extend({
        template: '#quiz-quizquestion',
        templateHelpers: function() {
            var options = this.options;

            return {
                questionNumber: function() {
                    return options.questionNumber;
                },
                isLastQuestion: function() {
                    return options.questionNumber === options.quizLength;
                }
            };
        },

        events: {
            'click [data-action=next]': 'submitAnswer'
        },

        submitAnswer: function(event) {
            var selectedAnswer = this.$(':radio:checked').val();

            if (typeof selectedAnswer === "undefined") {
                alert("Please select an answer");
            }
            else {
                this.model.set('chosenAnswer', parseInt(selectedAnswer, 10));
            }

            event.preventDefault();
        }
    });

});<commit_msg>Why do I not use Underscore?<commit_after>QuizEngine.module('Quiz', function(Quiz) {

    Quiz.QuizQuestionView = Marionette.ItemView.extend({
        template: '#quiz-quizquestion',
        templateHelpers: function() {
            var options = this.options;

            return {
                questionNumber: function() {
                    return options.questionNumber;
                },
                isLastQuestion: function() {
                    return options.questionNumber === options.quizLength;
                }
            };
        },

        events: {
            'click [data-action=next]': 'submitAnswer'
        },

        submitAnswer: function(event) {
            var selectedAnswer = this.$(':radio:checked').val();

            if (_.isUndefined(selectedAnswer)) {
                alert("Please select an answer");
            }
            else {
                this.model.set('chosenAnswer', parseInt(selectedAnswer, 10));
            }

            event.preventDefault();
        }
    });

});<|endoftext|>


<commit_before>'use babel';

import {Point, Range} from 'atom';

export default class EventHandler {
  constructor(socket, editor, doc, subscriptions, clientId) {
    this.socket = socket;
    this.editor = editor;
    this.doc = doc;
    this.subscriptions = subscriptions;
    this.clientId = clientId;
    this.push = true;
    this.buffer = editor.getBuffer();
  }

  listen() {
    let disposables = [];

    // local events
    disposables.push(this.editor.onDidSave( (event) => {
      if (!this.push) {
        return;
      }
      let saveData = {
        a: 'meta',
        type: 'save',
        path: atom.project.relativizePath(event.path)[1]
      };
      setTimeout( () => {
        this.sendSocketMsg( () => {
          this.socket.send(JSON.stringify(saveData));
        });
      }, 0);
    }));

    disposables.push(this.editor.onDidChangeSelectionRange( (event) => {
      let data = {
        a: 'meta',
        type: 'highlight',
        newRange: event.newBufferRange
      };

      setTimeout( () => {
        this.sendSocketMsg( () => {
          this.socket.send(JSON.stringify(data));
        });
      }, 0);
    }));

    disposables.push(this.editor.onDidChangeCursorPosition( (event) => {
      let data = {
        a: 'meta',
        type: 'cursorMoved',
        newPosition: event.newBufferPosition,
        clientId: this.clientId
      };
      setTimeout( () => {
        this.sendSocketMsg( () => {
          this.socket.send(JSON.stringify(data));
        });
      }, 0);
    }));

    disposables.push(this.buffer.onDidChange((event) => {
      if (!this.push) {
        return;
      }
      // remove text event
      if (event['oldText'].length !== 0) {
        let startPoint = event['oldRange'].start;
        let position = this.buffer.characterIndexForPosition(startPoint);
        let op = [position, {d: event['oldText'].length}];
        this.doc.submitOp(op);
      }
      // insert text event
      if (event['newText'].length !== 0) {
        let startPoint = event['newRange'].start;
        let position = this.buffer.characterIndexForPosition(startPoint);
        let op = [position, event['newText']];
        this.doc.submitOp(op);
      }
    }));
    this.subscriptions.add(...disposables);

    // remote events
    this.listenToServerChanges();
  }

  listenToServerChanges() {
    this.socket.on('message', (msg) => {
      let data = JSON.parse(msg);
      console.log(data);
      if (data.a !== 'meta') {
        return;
      }
      switch (data.type) {
        case 'cursorMoved':
          // if (typeof this.marker !== 'undefined') {
          //   this.marker.destroy();
          // }
          this.onCursorMoved(data.newPosition, data.clientId);
          break;
        case 'highlight':
          // if (typeof this.overlayMarker !== 'undefined') {
          //   this.overlayMarker.destroy();
          // }
          this.onHighlight(data.newRange);
          break;
        case 'save':
          this.onSave(data.path);
          break;
        case 'close':
          this.onClose();
          break;
        case 'socketClose':
          this.onSocketClose(data.clientId);
          break;
        default:
      }
    });

    this.doc.on('op', (op, source) => {
      if (source) {
        console.log('Got your own changes, I am not doing anything...');
        return;
      }
      console.log('changing...');
      console.log(op);

      var pos = 0;
      for (var i = 0; i < op.length; i++) {
        var component = op[i];
        switch (typeof component) {
          case 'number':
            pos += component;
            break;
          case 'string':
            this.onInsert(pos, component);
            pos += component.length;
            break;
          case 'object':
            this.onRemove(pos, component.d);
            break;
          default:
            break;
        }
      }
    });
  }

  onCursorMoved(positionObj, clientId) {
    // type = overlay
    if (typeof this.overlayMarker !== 'undefined') {
      this.overlayMarker.destroy();
    }

    // if (typeof this.cursorMarker !== 'undefined') {
    //   this.cursorMarker.destroy();
    // }

    // this.cursorMarker = this.editor.markBufferPosition(Point.fromObject(positionObj), {
    //   'invalidate': 'never'
    // });

    this.overlayMarker = this.editor.markBufferPosition(Point.fromObject(positionObj), {
      'invalidate': 'never'
    });

    let indicator = document.createElement('div');
    Object.assign(indicator.style, {
      display: 'inline'
    });

    let cursor = document.createElement('div');
    Object.assign(cursor.style, {
      transform: 'translate(0, -100%)',
      display: 'inline',
      height: '27px',
      width: '10px',
      borderLeft: '2px solid #528bff'
    });

    indicator.appendChild(cursor);

    let text = document.createElement('div');
    text.textContent = clientId;
    let style = {
      transform: 'translate(0, -100%)',
      display: 'inline',
      backgroundColor: 'rgba(31, 161, 93, 1)',
      paddingLeft: '1px',
      marginLeft: '1px',
      fontFamily: 'comic sans, comic sans ms, cursive, verdana, arial, sans-serif'
    }
    Object.assign(text.style, style);

    indicator.appendChild(text);

    // this.editor.decorateMarker(this.cursorMarker, {
    //   type: 'overlay',
    //   position: 'head',
    //   item: cursor
    // });

    this.editor.decorateMarker(this.overlayMarker, {
      type: 'overlay',
      position: 'head',
      item: indicator
    });

    cursor.animate([
      {opacity: '1'},
      {opacity: '0'}
    ], {
      duration: 300,
      iterations: 'Infinity',
      direction: 'alternate'
    });
  }

  onHighlight(rangeObj) {
    if (typeof this.marker !== 'undefined') {
      this.marker.destroy();
    }
    if (Point.fromObject(rangeObj.start).isEqual(Point.fromObject(rangeObj.end))) {
      return;
    }
    this.marker = this.editor.markBufferRange(Range.fromObject(rangeObj), {
      invalidate: 'never'
    });
    this.editor.decorateMarker(this.marker, {
      type: 'highlight',
      class: 'coeditor-selection'
    });
  }

  onSave(relativePath) {
    // atom.workspace.getActivePane().saveItem(atom.workspace.getActivePaneItem());
    this.push = false;
    console.log(atom.project.getPaths());
    if (typeof this.editor.getPath() !== 'undefined') {
      this.editor.save();
    }
    this.push = true;
    // if (typeof this.editor.getPath() !== 'undefined') {
    //   this.editor.save();
    // } else {
    //   let absolutePath = path.join(atom.project.getPaths()[0], relativePath);
    //   this.editor.saveAs(absolutePath);
    // }
  }

  onClose() {
    atom.workspace.getActivePaneItem().destroy();
  }

  onSocketClose(clientId) {
    atom.notifications.addInfo(clientId + ' left.');
  }

  onInsert(position, text) {
    this.doBufferChange( () => {
      let from = this.buffer.positionForCharacterIndex(position);
      this.buffer.insert(from, text);
    })
  }

  onRemove(position, length) {
    this.doBufferChange( () => {
      let from = this.buffer.positionForCharacterIndex(position);
      let to = this.buffer.positionForCharacterIndex(position + length);
      this.buffer.delete([from.toArray(), to.toArray()]);
    })
  }

  doBufferChange(callback) {
    this.push = false;
    callback();
    this.push = true;
  }

  sendSocketMsg(callback) {
    if (this.socket) {
      callback();
    }
  }
}
<commit_msg>add cursor and text div into a container<commit_after>'use babel';

import {Point, Range} from 'atom';

export default class EventHandler {
  constructor(socket, editor, doc, subscriptions, clientId) {
    this.socket = socket;
    this.editor = editor;
    this.doc = doc;
    this.subscriptions = subscriptions;
    this.clientId = clientId;
    this.push = true;
    this.buffer = editor.getBuffer();
  }

  listen() {
    let disposables = [];

    // local events
    disposables.push(this.editor.onDidSave( (event) => {
      if (!this.push) {
        return;
      }
      let saveData = {
        a: 'meta',
        type: 'save',
        path: atom.project.relativizePath(event.path)[1]
      };
      setTimeout( () => {
        this.sendSocketMsg( () => {
          this.socket.send(JSON.stringify(saveData));
        });
      }, 0);
    }));

    disposables.push(this.editor.onDidChangeSelectionRange( (event) => {
      let data = {
        a: 'meta',
        type: 'highlight',
        newRange: event.newBufferRange
      };

      setTimeout( () => {
        this.sendSocketMsg( () => {
          this.socket.send(JSON.stringify(data));
        });
      }, 0);
    }));

    disposables.push(this.editor.onDidChangeCursorPosition( (event) => {
      let data = {
        a: 'meta',
        type: 'cursorMoved',
        newPosition: event.newBufferPosition,
        clientId: this.clientId
      };
      setTimeout( () => {
        this.sendSocketMsg( () => {
          this.socket.send(JSON.stringify(data));
        });
      }, 0);
    }));

    disposables.push(this.buffer.onDidChange((event) => {
      if (!this.push) {
        return;
      }
      // remove text event
      if (event['oldText'].length !== 0) {
        let startPoint = event['oldRange'].start;
        let position = this.buffer.characterIndexForPosition(startPoint);
        let op = [position, {d: event['oldText'].length}];
        this.doc.submitOp(op);
      }
      // insert text event
      if (event['newText'].length !== 0) {
        let startPoint = event['newRange'].start;
        let position = this.buffer.characterIndexForPosition(startPoint);
        let op = [position, event['newText']];
        this.doc.submitOp(op);
      }
    }));
    this.subscriptions.add(...disposables);

    // remote events
    this.listenToServerChanges();
  }

  listenToServerChanges() {
    this.socket.on('message', (msg) => {
      let data = JSON.parse(msg);
      console.log(data);
      if (data.a !== 'meta') {
        return;
      }
      switch (data.type) {
        case 'cursorMoved':
          // if (typeof this.marker !== 'undefined') {
          //   this.marker.destroy();
          // }
          this.onCursorMoved(data.newPosition, data.clientId);
          break;
        case 'highlight':
          // if (typeof this.overlayMarker !== 'undefined') {
          //   this.overlayMarker.destroy();
          // }
          this.onHighlight(data.newRange);
          break;
        case 'save':
          this.onSave(data.path);
          break;
        case 'close':
          this.onClose();
          break;
        case 'socketClose':
          this.onSocketClose(data.clientId);
          break;
        default:
      }
    });

    this.doc.on('op', (op, source) => {
      if (source) {
        console.log('Got your own changes, I am not doing anything...');
        return;
      }
      console.log('changing...');
      console.log(op);

      var pos = 0;
      for (var i = 0; i < op.length; i++) {
        var component = op[i];
        switch (typeof component) {
          case 'number':
            pos += component;
            break;
          case 'string':
            this.onInsert(pos, component);
            pos += component.length;
            break;
          case 'object':
            this.onRemove(pos, component.d);
            break;
          default:
            break;
        }
      }
    });
  }

  onCursorMoved(positionObj, clientId) {
    // type = overlay
    if (typeof this.overlayMarker !== 'undefined') {
      this.overlayMarker.destroy();
    }

    this.overlayMarker = this.editor.markBufferPosition(Point.fromObject(positionObj), {
      'invalidate': 'never'
    });

    let indicator = document.createElement('div');
    Object.assign(indicator.style, {
      transform: 'translate(0, -100%)',
      display: 'flex'
    });

    let cursor = document.createElement('div');
    Object.assign(cursor.style, {
      alignItems: 'stretch',
      borderLeft: '2px solid rgba(31, 161, 93, 1)'
    });

    indicator.appendChild(cursor);

    let text = document.createElement('div');
    text.textContent = clientId;
    let style = {
      alignItems: 'stretch',
      backgroundColor: 'rgba(31, 161, 93, 1)',
      paddingLeft: '1px',
      fontFamily: 'comic sans, comic sans ms, cursive, verdana, arial, sans-serif'
    }
    Object.assign(text.style, style);

    indicator.appendChild(text);

    this.editor.decorateMarker(this.overlayMarker, {
      type: 'overlay',
      position: 'head',
      item: indicator
    });

    cursor.animate([
      {opacity: '1'},
      {opacity: '0'}
    ], {
      duration: 300,
      iterations: 'Infinity',
      direction: 'alternate'
    });
  }

  onHighlight(rangeObj) {
    if (typeof this.marker !== 'undefined') {
      this.marker.destroy();
    }
    if (Point.fromObject(rangeObj.start).isEqual(Point.fromObject(rangeObj.end))) {
      return;
    }
    this.marker = this.editor.markBufferRange(Range.fromObject(rangeObj), {
      invalidate: 'never'
    });
    this.editor.decorateMarker(this.marker, {
      type: 'highlight',
      class: 'coeditor-selection'
    });
  }

  onSave(relativePath) {
    // atom.workspace.getActivePane().saveItem(atom.workspace.getActivePaneItem());
    this.push = false;
    console.log(atom.project.getPaths());
    if (typeof this.editor.getPath() !== 'undefined') {
      this.editor.save();
    }
    this.push = true;
    // if (typeof this.editor.getPath() !== 'undefined') {
    //   this.editor.save();
    // } else {
    //   let absolutePath = path.join(atom.project.getPaths()[0], relativePath);
    //   this.editor.saveAs(absolutePath);
    // }
  }

  onClose() {
    atom.workspace.getActivePaneItem().destroy();
  }

  onSocketClose(clientId) {
    atom.notifications.addInfo(clientId + ' left.');
  }

  onInsert(position, text) {
    this.doBufferChange( () => {
      let from = this.buffer.positionForCharacterIndex(position);
      this.buffer.insert(from, text);
    })
  }

  onRemove(position, length) {
    this.doBufferChange( () => {
      let from = this.buffer.positionForCharacterIndex(position);
      let to = this.buffer.positionForCharacterIndex(position + length);
      this.buffer.delete([from.toArray(), to.toArray()]);
    })
  }

  doBufferChange(callback) {
    this.push = false;
    callback();
    this.push = true;
  }

  sendSocketMsg(callback) {
    if (this.socket) {
      callback();
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var _        = require('lodash');
var bluebird = require('bluebird');
var fs       = bluebird.promisifyAll(require('fs'));
var path     = require('path');

var registry = require('./tasks');
var utility  = require('./utility');

var directory;

function templateAllFunc(blobs) {
  var name = path.join('demo', 'index.html');

  return bluebird.join(
    fs.readFileAsync(name),
    utility.getStyleNames(),
    function(template, styles) {
      return {
        template: template,
        path: path,
        blobs: _.compact(blobs),
        styles: styles
      };
    });
}

function copyDocs() {
  var input  = path.join(directory.root, 'docs', '*.rst'),
      output = path.join(directory.build, 'docs');

  return {
    startLog: { task: ['log', 'Copying documentation.'] },
    read: { requires: 'startLog', task: ['glob', utility.glob(input)] },
    writeLog: { requires: 'read', task: ['log', 'Writing documentation.'] },
    write: { requires: 'writeLog', task: ['dest', output] }
  };
}

function generateDemo(filterCB, readArgs) {
  var staticArgs   = utility.glob(path.join('demo', '*.{js,css}')),
      stylesArgs   = utility.glob(path.join('src', 'styles', '*'), 'binary'),
      demoRoot     = path.join(directory.build, 'demo'),
      templateArgs = { callback: templateAllFunc },
      destArgs     = {
        dir: path.join(demoRoot, 'styles'),
        encoding: 'binary'
      };

  return {
    logStart: { task: ['log', 'Generating demo.'] },
    readLanguages: { requires: 'logStart', task: ['glob', readArgs] },
    filterSnippets: { requires: 'readLanguages', task: ['filter', filterCB] },
    readSnippet: { requires: 'filterSnippets', task: 'readSnippet' },
    template: {
      requires: 'readSnippet',
      task: ['templateAll', templateArgs]
    },
    write: {
      requires: 'template',
      task: ['write', path.join(demoRoot, 'index.html')]
    },
    readStatic: { requires: 'logStart', task: ['glob', staticArgs] },
    writeStatic: { requires: 'readStatic', task: ['dest', demoRoot] },
    readStyles: { requires: 'logStart', task: ['glob', stylesArgs] },
    writeStyles: { requires: 'readStyles', task: ['dest', destArgs] }
  };
}

module.exports = function(commander, dir) {
  directory = dir;

  var hljsExt, output, requiresTask, tasks,
      replace           = utility.replace,
      regex             = utility.regex,
      replaceClassNames = utility.replaceClassNames,

      coreFile     = path.join('src', 'highlight.js'),
      languages    = utility.glob(path.join('src', 'languages', '*.js')),
      filterCB     = utility.buildFilterCallback(commander.args),
      replaceArgs  = replace(regex.header, ''),
      templateArgs =
        'hljs.registerLanguage(\'<%= name %>\', <%= content %>);\n';

  tasks = {
    startLog: { task: ['log', 'Building highlight.js pack file.'] },
    readCore: { requires: 'startLog', task: ['read', coreFile] },
    read: { requires: 'startLog', task: ['glob', languages] },
    filter: { requires: 'read', task: ['filter', filterCB] },
    reorder: { requires: 'filter', task: 'reorderDeps' },
    replace: { requires: 'reorder', task: ['replace', replaceArgs] },
    template: { requires: 'replace', task: ['template', templateArgs] },
    packageFiles: {
      requires: ['readCore', 'template'],
      task: 'packageFiles'
    }
  };
  requiresTask = 'packageFiles';

  if(commander.compress || commander.target === 'cdn') {
    tasks.compresslog = {
      requires: requiresTask,
      task: ['log', 'Compressing highlight.js pack file.']
    };

    tasks.replace2 = {
      requires: 'compresslog',
      task: [ 'replaceSkippingStrings'
            , replace(regex.replaces, replaceClassNames)
            ]
    };

    tasks.replace3 = {
      requires: 'replace2',
      task: ['replace', replace(regex.classname, '$1.className')]
    };

    tasks.minify  = { requires: 'replace3', task: 'jsminify' };
    requiresTask  = 'minify';
  }

  tasks.insertLicenseTag = {
    requires: requiresTask,
    task: 'insertLicenseTag'
  };

  tasks.writelog = {
    requires: 'insertLicenseTag',
    task: ['log', 'Writing highlight.js pack file.']
  };

  hljsExt = commander.target === 'cdn' ? 'min' : 'pack';
  output  = path.join(directory.build, 'highlight.' + hljsExt + '.js');

  tasks.write = {
    requires: 'writelog',
    task: ['write', output]
  };

  tasks = (commander.target === 'browser')
        ? [copyDocs(), generateDemo(filterCB, languages), tasks]
        : [tasks];

  return utility.toQueue(tasks, registry);
};
<commit_msg>Use object literal shorthand<commit_after>'use strict';

var _        = require('lodash');
var bluebird = require('bluebird');
var fs       = bluebird.promisifyAll(require('fs'));
var path     = require('path');

var registry = require('./tasks');
var utility  = require('./utility');

var directory;

function templateAllFunc(blobs) {
  var name = path.join('demo', 'index.html');

  blobs = _.compact(blobs);

  return bluebird.join(
    fs.readFileAsync(name),
    utility.getStyleNames(),
    (template, styles) => ({ template, path, blobs, styles })
  );
}

function copyDocs() {
  var input  = path.join(directory.root, 'docs', '*.rst'),
      output = path.join(directory.build, 'docs');

  return {
    startLog: { task: ['log', 'Copying documentation.'] },
    read: { requires: 'startLog', task: ['glob', utility.glob(input)] },
    writeLog: { requires: 'read', task: ['log', 'Writing documentation.'] },
    write: { requires: 'writeLog', task: ['dest', output] }
  };
}

function generateDemo(filterCB, readArgs) {
  var staticArgs   = utility.glob(path.join('demo', '*.{js,css}')),
      stylesArgs   = utility.glob(path.join('src', 'styles', '*'), 'binary'),
      demoRoot     = path.join(directory.build, 'demo'),
      templateArgs = { callback: templateAllFunc },
      destArgs     = {
        dir: path.join(demoRoot, 'styles'),
        encoding: 'binary'
      };

  return {
    logStart: { task: ['log', 'Generating demo.'] },
    readLanguages: { requires: 'logStart', task: ['glob', readArgs] },
    filterSnippets: { requires: 'readLanguages', task: ['filter', filterCB] },
    readSnippet: { requires: 'filterSnippets', task: 'readSnippet' },
    template: {
      requires: 'readSnippet',
      task: ['templateAll', templateArgs]
    },
    write: {
      requires: 'template',
      task: ['write', path.join(demoRoot, 'index.html')]
    },
    readStatic: { requires: 'logStart', task: ['glob', staticArgs] },
    writeStatic: { requires: 'readStatic', task: ['dest', demoRoot] },
    readStyles: { requires: 'logStart', task: ['glob', stylesArgs] },
    writeStyles: { requires: 'readStyles', task: ['dest', destArgs] }
  };
}

module.exports = function(commander, dir) {
  directory = dir;

  var hljsExt, output, requiresTask, tasks,
      replace           = utility.replace,
      regex             = utility.regex,
      replaceClassNames = utility.replaceClassNames,

      coreFile     = path.join('src', 'highlight.js'),
      languages    = utility.glob(path.join('src', 'languages', '*.js')),
      filterCB     = utility.buildFilterCallback(commander.args),
      replaceArgs  = replace(regex.header, ''),
      templateArgs =
        'hljs.registerLanguage(\'<%= name %>\', <%= content %>);\n';

  tasks = {
    startLog: { task: ['log', 'Building highlight.js pack file.'] },
    readCore: { requires: 'startLog', task: ['read', coreFile] },
    read: { requires: 'startLog', task: ['glob', languages] },
    filter: { requires: 'read', task: ['filter', filterCB] },
    reorder: { requires: 'filter', task: 'reorderDeps' },
    replace: { requires: 'reorder', task: ['replace', replaceArgs] },
    template: { requires: 'replace', task: ['template', templateArgs] },
    packageFiles: {
      requires: ['readCore', 'template'],
      task: 'packageFiles'
    }
  };
  requiresTask = 'packageFiles';

  if(commander.compress || commander.target === 'cdn') {
    tasks.compresslog = {
      requires: requiresTask,
      task: ['log', 'Compressing highlight.js pack file.']
    };

    tasks.replace2 = {
      requires: 'compresslog',
      task: [ 'replaceSkippingStrings'
            , replace(regex.replaces, replaceClassNames)
            ]
    };

    tasks.replace3 = {
      requires: 'replace2',
      task: ['replace', replace(regex.classname, '$1.className')]
    };

    tasks.minify  = { requires: 'replace3', task: 'jsminify' };
    requiresTask  = 'minify';
  }

  tasks.insertLicenseTag = {
    requires: requiresTask,
    task: 'insertLicenseTag'
  };

  tasks.writelog = {
    requires: 'insertLicenseTag',
    task: ['log', 'Writing highlight.js pack file.']
  };

  hljsExt = commander.target === 'cdn' ? 'min' : 'pack';
  output  = path.join(directory.build, 'highlight.' + hljsExt + '.js');

  tasks.write = {
    requires: 'writelog',
    task: ['write', output]
  };

  tasks = (commander.target === 'browser')
        ? [copyDocs(), generateDemo(filterCB, languages), tasks]
        : [tasks];

  return utility.toQueue(tasks, registry);
};
<|endoftext|>


<commit_before>jsio('from shared.javascript import Class')
jsio('import fan.ui.Component')

exports = Class(fan.ui.Component, function(supr) {

	this._className = 'RadioButtons'

	this._createContent = function() {
		this._delegateOn('click', bind(this, '_onDelegateClick'))
		this._payloads = {}
		this._payloadIndex = {}
		this._buttons = []
	}

	this.addButton = function(props) {
		var className = 'Button ' + (props.className ? ' ' + props.className : '')
			el = this._create({ className: className, text: props.text, parent: this.getElement() }),
			delegateId = fin.unique(),
			buttons = this._buttons

		this._makeUnselectable(el)
		this._payloads[delegateId] = props.payload
		this._payloadIndex[props.payload] = buttons.length
		el.delegateId = delegateId
		buttons.push(el)
		buttons[delegateId] = el

		if (!this._leftButton) {
			this._leftButton = el
			this.addClassName(el, 'left')
		}
		if (this._rightButton) {
			this.removeClassName(this._rightButton, 'right')
		}
		this._rightButton = el
		this.addClassName(el, 'right')

		return this
	}

	this.select = function(index, silent) {
		this._onDelegateClick(this._buttons[index].delegateId, null, silent)
		return this
	}

	this.reflect = function(itemId, property) {
		fin.observe(itemId, property, bind(this, function(op, value) {
			this.select(this._payloadIndex[value], true)
		}))
		this.subscribe('Click', this, function(value) {
			fin.set(itemId, property, value)
		})
		return this
	}

	this._onDelegateClick = function(delegateId, e, silent) {
		var currSelected = this._selected,
			newSelected = this._buttons[delegateId]

		if (currSelected) { this.removeClassName(currSelected, 'down') }
		this.addClassName(newSelected, 'down')
		this._selected = newSelected

		if (!silent) { this._publish('Click', this._payloads[delegateId]) }
	}
})<commit_msg>The first argument is the mutation, not the operation<commit_after>jsio('from shared.javascript import Class')
jsio('import fan.ui.Component')

exports = Class(fan.ui.Component, function(supr) {

	this._className = 'RadioButtons'

	this._createContent = function() {
		this._delegateOn('click', bind(this, '_onDelegateClick'))
		this._payloads = {}
		this._payloadIndex = {}
		this._buttons = []
	}

	this.addButton = function(props) {
		var className = 'Button ' + (props.className ? ' ' + props.className : '')
			el = this._create({ className: className, text: props.text, parent: this.getElement() }),
			delegateId = fin.unique(),
			buttons = this._buttons

		this._makeUnselectable(el)
		this._payloads[delegateId] = props.payload
		this._payloadIndex[props.payload] = buttons.length
		el.delegateId = delegateId
		buttons.push(el)
		buttons[delegateId] = el

		if (!this._leftButton) {
			this._leftButton = el
			this.addClassName(el, 'left')
		}
		if (this._rightButton) {
			this.removeClassName(this._rightButton, 'right')
		}
		this._rightButton = el
		this.addClassName(el, 'right')

		return this
	}

	this.select = function(index, silent) {
		this._onDelegateClick(this._buttons[index].delegateId, null, silent)
		return this
	}

	this.reflect = function(itemId, property) {
		fin.observe(itemId, property, bind(this, function(mutation, value) {
			this.select(this._payloadIndex[value], true)
		}))
		this.subscribe('Click', this, function(value) {
			fin.set(itemId, property, value)
		})
		return this
	}

	this._onDelegateClick = function(delegateId, e, silent) {
		var currSelected = this._selected,
			newSelected = this._buttons[delegateId]

		if (currSelected) { this.removeClassName(currSelected, 'down') }
		this.addClassName(newSelected, 'down')
		this._selected = newSelected

		if (!silent) { this._publish('Click', this._payloads[delegateId]) }
	}
})<|endoftext|>


<commit_before>'use strict'
var OperationHelper = require('apac').OperationHelper;
var util = require(__base + '/lib/util');
var AWSConfig = util.loadAWSConfig();
var awsController;

var getData = function(req, res) {
    var keywords = req;
    var opHelper = new OperationHelper({
        awsId:     AWSConfig.access_key,
        awsSecret: AWSConfig.secret_access_key,
        assocId:   AWSConfig.associate_id
    });
    opHelper.execute('ItemSearch', {
      'SearchIndex': 'VideoGames',
      'Keywords': keywords,
      'ResponseGroup': 'ItemAttributes,Offers'
    }).then((response) => {
        var obj = {
            'link' : response.result.ItemSearchResponse.Items.Item[0].DetailPageURL,
            'lowestPrice' : response.result.ItemSearchResponse.Items.Item[0].OfferSummary.LowestNewPrice.FormattedPrice
        };
        res.json(obj);
    }).catch((err) => {
        console.error("Something went wrong! ", err);
    });
};

awsController = {
    getData: getData
};

module.exports = awsController;<commit_msg>Revision Amazon API<commit_after>'use strict'
var aws = require('aws-lib');
var util = require(__base + '/lib/util');
var AWSConfig = util.loadAWSConfig();
var awsController;

var getData = function(req, res) {
    var keywords = req;

    var awsId=     AWSConfig.access_key,
        awsSecret= AWSConfig.secret_access_key,
        assocId=   AWSConfig.associate_id;
    var prodAdv = aws.createProdAdvClient(awsId,awsSecret,assocId);
    var options = {SearchIndex:"VideoGames", Keywords:keywords,'ResponseGroup': 'ItemAttributes,Offers'};

    prodAdv.call("ItemSearch", options, function(err,result){
        var obj = {
            'link' : result.Items.Item[0].DetailPageURL,
            'lowestPrice' : result.Items.Item[0].OfferSummary.LowestNewPrice.FormattedPrice
        };
        res.send(obj);
    });

};

awsController = {
    getData: getData
};

module.exports = awsController;<|endoftext|>


<commit_before>dojo.provide("dojox.charting.Theme");
dojo.require("dojox.charting._color");

(function(){
	var dxc=dojox.charting;
	//	TODO: Legend information
	dxc.Theme=function(/*object?*/kwArgs){
		kwArgs=kwArgs||{};
		this.chart=dojo.mixin(dojo.clone(dxc.Theme._def.chart), kwArgs.chart||{});
		this.plotarea=dojo.mixin(dojo.clone(dxc.Theme._def.plotarea), kwArgs.plotarea||{});
		this.axis=dojo.mixin(dojo.clone(dxc.Theme._def.axis), kwArgs.axis||{});
		this.series=dojo.mixin(dojo.clone(dxc.Theme._def.series), kwArgs.series||{});
		this.marker=dojo.mixin(dojo.clone(dxc.Theme._def.marker), kwArgs.marker||{});
		this.markers=dojo.mixin(dojo.clone(dxc.Theme.Markers), kwArgs.markers||{});
		this.colors=[];
		this.antiAlias=("antiAlias" in kwArgs)?kwArgs.antiAlias:true;
		this.assignColors=("assignColors" in kwArgs)?kwArgs.assignColors:true;
		this.assignMarkers=("assignMarkers" in kwArgs)?kwArgs.assignMarkers:true;
		this._colorCache=null;

		//	push the colors, use _def colors if none passed.
		kwArgs.colors=kwArgs.colors||dxc.Theme._def.colors;
		dojo.forEach(kwArgs.colors, function(item){
			this.colors.push(item);
		}, this);

		//	private variables for color and marker indexing
		this._current={ color:0, marker: 0 };
		this._markers=[];
		this._buildMarkerArray();
	};

	//	"static" fields
	//	default markers.
	//	A marker is defined by an SVG path segment; it should be defined as
	//		relative motion, and with the assumption that the path segment
	//		will be moved to the value point (i.e prepend Mx,y)
	dxc.Theme.Markers={
		NONE:"",
		CIRCLE:"m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0",
		SQUARE:"m-3,-3 l0,6 6,0 0,-6 z",
		DIAMOND:"m0,-3 l3,3 -3,3 -3,-3 z",
		CROSS:"m0,-3 l0,6 m-3,-3 l6,0",
		X:"m-3,-3 l6,6 m0,-6 l-6,6",
		TRIANGLE:"m-3,3 l3,-6 3,6 z",
		TRIANGLE_INVERTED:"m-3,-3 l3,6 3,-6 z"
	};
	dxc.Theme._def={
		//	all objects are structs used directly in dojox.gfx
		chart:{
			stroke: {width: 0},
			fill: "white"
		},
		plotarea:{
			stroke: {width: 0},
			fill: "white"
		},
		//	TODO: label rotation on axis
		axis:{
			stroke:{ color:"#000",width:2 },							//	the axis itself
			line:{ color:"#ccc",width:1,style:"Dot",cap:"round" },		//	gridlines
			majorTick:{ color:"#999", width:2, length:12, position:"center" },	//	major ticks on axis
			minorTick:{ color:"#999", width:1, length:8, position:"center" },	//	minor ticks on axis
			font:"normal normal normal 8pt Tahoma",						//	labels on axis
			fontColor:"#000"											//	color of labels
		},
		series:{
			outline: {width: 2, color: "#ccc"},							//	line or outline
			stroke: {width: 2, color: "#333"},							//	line or outline
			fill: "#ccc",												//	fill, if appropriate
			font: "normal normal normal 7pt Tahoma",					//	if there's a label
			fontColor: "#000"											// 	color of labels
		},
		marker:{	//	any markers on a series.
			stroke: {width:2},											//	stroke or outline
			fill: "#333",												//	fill if needed
			font: "normal normal normal 7pt Tahoma",					//	label
			fontColor: "#000"
		},
		colors:[
			"#000","#111","#222","#333",
			"#444","#555","#666","#777",
			"#888","#999","#aaa","#bbb",
			"#ccc"
		]
	};

	//	prototype methods
	dojo.extend(dxc.Theme, {
		defineColors: function(obj){
			//	we can generate a set of colors based on keyword arguments
			var kwArgs=obj||{};

			//	deal with caching
			var cache=false;
			if(kwArgs.cache===undefined){ cache=true; }
			if(kwArgs.cache==true){ cache=true; }

			if(cache){
				this._colorCache=kwArgs;
			} else {
				var mix=this._colorCache||{};
				kwArgs=dojo.mixin(dojo.clone(mix), kwArgs);
			}

			var c=[], n=kwArgs.num||32;	//	the number of colors to generate
			if(kwArgs.colors){
				//	we have an array of colors predefined, so fix for the number of series.
				var l=kwArgs.colors.length;
				for(var i=0; i<n; i++){
					c.push(kwArgs.colors[i%l]);
				}
				this.colors=c;
			}
			else if(kwArgs.hue){
				//	single hue, generate a set based on brightness
				var s=kwArgs.saturation||100;	//	saturation
				var st=kwArgs.low||30;
				var end=kwArgs.high||90;
				var step=(end-st)/n;			//	brightness steps
				for(var i=0; i<n; i++){
					c.push(dxc._color.fromHsb(kwArgs.hue, s, st+(step*i)).toHex());
				}
				this.colors=c;
			}
			else if(kwArgs.stops){
				//	create color ranges that are either equally distributed, or
				//	(optionally) based on a passed "offset" property.  If you
				//	pass an array of Colors, it will equally distribute, if
				//	you pass an array of structs { color, offset }, it will
				//	use the offset (0.0 - 1.0) to distribute.  Note that offset
				//	values should be plotted on a line from 0.0 to 1.0--i.e.
				//	they should be additive.  For example:
				//	[ {color, offset:0}, { color, offset:0.2 }, { color, offset:0.5 }, { color, offset:1.0 } ]
				//
				//	If you use stops for colors, you MUST have a color at 0.0 and one
				//	at 1.0.

				//	figure out how many stops we have
				var l=kwArgs.stops.length;
				if(l<2){
					throw new Error(
						"dojox.charting.Theme::defineColors: when using stops to "
						+ "define a color range, you MUST specify at least 2 colors."
					);
				}

				//	figure out if the distribution is equal or not.  Note that
				//	colors may not exactly match the stops you define; because
				//	color generation is linear (i.e. evenly divided on a linear
				//	axis), it's very possible that a color will land in between
				//	two stops and not exactly *at* a stop.
				//
				//	The only two colors guaranteed will be the end stops (i.e.
				//	the first and last stop), which will *always* be set as
				//	the end stops.
				if(typeof(kwArgs.stops[0].offset)=="undefined"){
					//	set up equal offsets
					var off=1/(l-1);
					for(var i=0; i<l; i++){
						kwArgs.stops[i]={
							color:kwArgs.stops[i],
							offset:off*i
						};
					}
				}
				//	ensure the ends.
				kwArgs.stops[0].offset=0;
				kwArgs.stops[l-1].offset=1;
				kwArgs.stops.sort(function(a,b){ return a.offset-b.offset; });

				//	create the colors.
				//	first stop.
				c.push(kwArgs.stops[0].color.toHex());

				//	TODO: calculate the blend at n/steps and set the color

				//	last stop
				c.push(kwArgs.stops[l-1].color.toHex());
				this.colors=c;
			}
		},

		_buildMarkerArray: function(){
			this._markers=[];
			for(var p in this.markers){ this._markers.push(this.markers[p]); }
			//	reset the position
			this._current.marker=0;
		},

		addMarker:function(/* string */name, /*string*/segment){
			//	summary
			//	Add a custom marker to this theme.
			//
			//	example
			//	myTheme.addMarker("Ellipse", foo);
			this.markers[name]=segment;
			this._buildMarkerArray();
		},
		setMarkers:function(/* object */obj){
			//	summary
			//	Set all the markers of this theme at once.  obj should be
			//	a dictionary of keys and path segments.
			//
			//	example
			//	myTheme.setMarkers({ "CIRCLE": foo });
			this.markers=obj;
			this._buildMarkerArray();
		},

		next: function(/* string? */type){
			//	summary
			//	get either the next color or the next marker, depending on what was
			//	passed.  If type is not passed, it assumes color.
			//
			//	example
			//	var color=myTheme.next();
			//	var color=myTheme.next("color");
			//	var marker=myTheme.next("marker");
			if(!type) type="color";
			if(type=="color"){
				return this.colors[this._current.color++%this.colors.length];
			}
			else if(type=="marker"){
				return this._markers[this._current.marker++%this._markers.length];
			}
		},
		clear: function(){
			this._current = {color: 0, marker: 0};
		}
	});
})();
<commit_msg>Default definition fixes.<commit_after>dojo.provide("dojox.charting.Theme");
dojo.require("dojox.charting._color");

(function(){
	var dxc=dojox.charting;
	//	TODO: Legend information
	dxc.Theme=function(/*object?*/kwArgs){
		kwArgs=kwArgs||{};
		this.chart=dojo.mixin(dojo.clone(dxc.Theme._def.chart), kwArgs.chart||{});
		this.plotarea=dojo.mixin(dojo.clone(dxc.Theme._def.plotarea), kwArgs.plotarea||{});
		this.axis=dojo.mixin(dojo.clone(dxc.Theme._def.axis), kwArgs.axis||{});
		this.series=dojo.mixin(dojo.clone(dxc.Theme._def.series), kwArgs.series||{});
		this.marker=dojo.mixin(dojo.clone(dxc.Theme._def.marker), kwArgs.marker||{});
		this.markers=dojo.mixin(dojo.clone(dxc.Theme.Markers), kwArgs.markers||{});
		this.colors=[];
		this.antiAlias=("antiAlias" in kwArgs)?kwArgs.antiAlias:true;
		this.assignColors=("assignColors" in kwArgs)?kwArgs.assignColors:true;
		this.assignMarkers=("assignMarkers" in kwArgs)?kwArgs.assignMarkers:true;
		this._colorCache=null;

		//	push the colors, use _def colors if none passed.
		kwArgs.colors=kwArgs.colors||dxc.Theme._def.colors;
		dojo.forEach(kwArgs.colors, function(item){
			this.colors.push(item);
		}, this);

		//	private variables for color and marker indexing
		this._current={ color:0, marker: 0 };
		this._markers=[];
		this._buildMarkerArray();
	};

	//	"static" fields
	//	default markers.
	//	A marker is defined by an SVG path segment; it should be defined as
	//		relative motion, and with the assumption that the path segment
	//		will be moved to the value point (i.e prepend Mx,y)
	dxc.Theme.Markers={
		NONE:"",
		CIRCLE:"m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0",
		SQUARE:"m-3,-3 l0,6 6,0 0,-6 z",
		DIAMOND:"m0,-3 l3,3 -3,3 -3,-3 z",
		CROSS:"m0,-3 l0,6 m-3,-3 l6,0",
		X:"m-3,-3 l6,6 m0,-6 l-6,6",
		TRIANGLE:"m-3,3 l3,-6 3,6 z",
		TRIANGLE_INVERTED:"m-3,-3 l3,6 3,-6 z"
	};
	dxc.Theme._def={
		//	all objects are structs used directly in dojox.gfx
		chart:{
			stroke: {width: 0},
			fill: "white"
		},
		plotarea:{
			stroke: {width: 0},
			fill: "white"
		},
		//	TODO: label rotation on axis
		axis:{
			stroke:{ color:"#333",width:1 },							//	the axis itself
			line:{ color:"#ccc",width:1,style:"Dot",cap:"round" },		//	gridlines
			majorTick:{ color:"#666", width:1, length:6, position:"center" },	//	major ticks on axis
			minorTick:{ color:"#666", width:0.8, length:3, position:"center" },	//	minor ticks on axis
			font:"normal normal normal 7pt Tahoma",						//	labels on axis
			fontColor:"#333"											//	color of labels
		},
		series:{
			outline: {width: 2, color: "#ccc"},							//	line or outline
			stroke: {width: 2, color: "#333"},							//	line or outline
			fill: "#ccc",												//	fill, if appropriate
			font: "normal normal normal 7pt Tahoma",					//	if there's a label
			fontColor: "#000"											// 	color of labels
		},
		marker:{	//	any markers on a series.
			stroke: {width:1},											//	stroke or outline
			fill: "#333",												//	fill if needed
			font: "normal normal normal 7pt Tahoma",					//	label
			fontColor: "#000"
		},
		colors:[
			"#000","#111","#222","#333",
			"#444","#555","#666","#777",
			"#888","#999","#aaa","#bbb",
			"#ccc"
		]
	};

	//	prototype methods
	dojo.extend(dxc.Theme, {
		defineColors: function(obj){
			//	we can generate a set of colors based on keyword arguments
			var kwArgs=obj||{};

			//	deal with caching
			var cache=false;
			if(kwArgs.cache===undefined){ cache=true; }
			if(kwArgs.cache==true){ cache=true; }

			if(cache){
				this._colorCache=kwArgs;
			} else {
				var mix=this._colorCache||{};
				kwArgs=dojo.mixin(dojo.clone(mix), kwArgs);
			}

			var c=[], n=kwArgs.num||32;	//	the number of colors to generate
			if(kwArgs.colors){
				//	we have an array of colors predefined, so fix for the number of series.
				var l=kwArgs.colors.length;
				for(var i=0; i<n; i++){
					c.push(kwArgs.colors[i%l]);
				}
				this.colors=c;
			}
			else if(kwArgs.hue){
				//	single hue, generate a set based on brightness
				var s=kwArgs.saturation||100;	//	saturation
				var st=kwArgs.low||30;
				var end=kwArgs.high||90;
				var step=(end-st)/n;			//	brightness steps
				for(var i=0; i<n; i++){
					c.push(dxc._color.fromHsb(kwArgs.hue, s, st+(step*i)).toHex());
				}
				this.colors=c;
			}
			else if(kwArgs.stops){
				//	create color ranges that are either equally distributed, or
				//	(optionally) based on a passed "offset" property.  If you
				//	pass an array of Colors, it will equally distribute, if
				//	you pass an array of structs { color, offset }, it will
				//	use the offset (0.0 - 1.0) to distribute.  Note that offset
				//	values should be plotted on a line from 0.0 to 1.0--i.e.
				//	they should be additive.  For example:
				//	[ {color, offset:0}, { color, offset:0.2 }, { color, offset:0.5 }, { color, offset:1.0 } ]
				//
				//	If you use stops for colors, you MUST have a color at 0.0 and one
				//	at 1.0.

				//	figure out how many stops we have
				var l=kwArgs.stops.length;
				if(l<2){
					throw new Error(
						"dojox.charting.Theme::defineColors: when using stops to "
						+ "define a color range, you MUST specify at least 2 colors."
					);
				}

				//	figure out if the distribution is equal or not.  Note that
				//	colors may not exactly match the stops you define; because
				//	color generation is linear (i.e. evenly divided on a linear
				//	axis), it's very possible that a color will land in between
				//	two stops and not exactly *at* a stop.
				//
				//	The only two colors guaranteed will be the end stops (i.e.
				//	the first and last stop), which will *always* be set as
				//	the end stops.
				if(typeof(kwArgs.stops[0].offset)=="undefined"){
					//	set up equal offsets
					var off=1/(l-1);
					for(var i=0; i<l; i++){
						kwArgs.stops[i]={
							color:kwArgs.stops[i],
							offset:off*i
						};
					}
				}
				//	ensure the ends.
				kwArgs.stops[0].offset=0;
				kwArgs.stops[l-1].offset=1;
				kwArgs.stops.sort(function(a,b){ return a.offset-b.offset; });

				//	create the colors.
				//	first stop.
				c.push(kwArgs.stops[0].color.toHex());

				//	TODO: calculate the blend at n/steps and set the color

				//	last stop
				c.push(kwArgs.stops[l-1].color.toHex());
				this.colors=c;
			}
		},

		_buildMarkerArray: function(){
			this._markers=[];
			for(var p in this.markers){ this._markers.push(this.markers[p]); }
			//	reset the position
			this._current.marker=0;
		},

		addMarker:function(/* string */name, /*string*/segment){
			//	summary
			//	Add a custom marker to this theme.
			//
			//	example
			//	myTheme.addMarker("Ellipse", foo);
			this.markers[name]=segment;
			this._buildMarkerArray();
		},
		setMarkers:function(/* object */obj){
			//	summary
			//	Set all the markers of this theme at once.  obj should be
			//	a dictionary of keys and path segments.
			//
			//	example
			//	myTheme.setMarkers({ "CIRCLE": foo });
			this.markers=obj;
			this._buildMarkerArray();
		},

		next: function(/* string? */type){
			//	summary
			//	get either the next color or the next marker, depending on what was
			//	passed.  If type is not passed, it assumes color.
			//
			//	example
			//	var color=myTheme.next();
			//	var color=myTheme.next("color");
			//	var marker=myTheme.next("marker");
			if(!type) type="color";
			if(type=="color"){
				return this.colors[this._current.color++%this.colors.length];
			}
			else if(type=="marker"){
				return this._markers[this._current.marker++%this._markers.length];
			}
		},
		clear: function(){
			this._current = {color: 0, marker: 0};
		}
	});
})();
<|endoftext|>


<commit_before>import { defineComponent } from 'vue'
import { RouterLink as VueRouterLink } from 'vue-router'
import { getPreloadPath } from './lib/runtime-utils'

const prefetchedPaths = new Set()

export const RouterLink = defineComponent({
  ...VueRouterLink,

  name: 'RouterLink',

  async mounted() {
    if (import.meta.env.DEV) return

    const { matched, path } = this.$router.resolve(this.to)

    if (prefetchedPaths.has(path)) return

    const components = await Promise.all(
      matched.map((m) =>
        typeof m.components.default === 'function'
          ? m.components.default()
          : m.components.default
      )
    )
    for (const component of components) {
      if (component.$$staticPreload) {
        const url = getPreloadPath(path)
        fetch(url, { credentials: `include` })
        prefetchedPaths.add(path)
        break
      }
    }
  },
})
<commit_msg>Revert "refactor: use fetch to prefetch url"<commit_after>import { defineComponent } from 'vue'
import { RouterLink as VueRouterLink } from 'vue-router'
import { getPreloadPath } from './lib/runtime-utils'

const prefetchedPaths = new Set()

const link = import.meta.env.SSR ? null : document.createElement('link')
const hasPrefetch = import.meta.env.SSR
  ? false
  : link.relList && link.relList.supports && link.relList.supports('prefetch')

/**
 * Fetch URL using `<link rel="prefetch">` with fallback to `fetch` API
 * Safari doesn't have it enabled by default: https://caniuse.com/?search=prefetch
 * @param {string} url
 */
const prefetchURL = (url) => {
  if (hasPrefetch) {
    const link = document.createElement('link')
    link.rel = 'prefetch'
    link.href = url
    document.head.appendChild(link)
  } else {
    fetch(url, { credentials: `include` })
  }
}

export const RouterLink = defineComponent({
  ...VueRouterLink,

  name: 'RouterLink',

  async mounted() {
    if (import.meta.env.DEV) return

    const { matched, path } = this.$router.resolve(this.to)

    if (prefetchedPaths.has(path)) return

    const components = await Promise.all(
      matched.map((m) =>
        typeof m.components.default === 'function'
          ? m.components.default()
          : m.components.default
      )
    )
    for (const component of components) {
      if (component.$$staticPreload) {
        const url = getPreloadPath(path)
        prefetchURL(url)
        prefetchedPaths.add(path)
        break
      }
    }
  },
})
<|endoftext|>


<commit_before>console.log("SIBot v0.1");
console.log("Loading...");

var config = {
        channels: ["#sibot-test"],
        server: "chat.freenode.net",
        botName: "SIbot"
};

var irc = require("irc");
var bot = new irc.Client(config.server, config.botName, {
        channels: config.channels
});

stream.on('tweet', function (tweet) {
        if(typeof tweet.retweeted_status == 'undefined'
        && (tweet.text.indexOf("RT") == -1)
        && (tweet.text.indexOf("MT") == -1) ) { // If not retweeted
                console.log(tweet.user.screen_name+': '+tweet.text.replace(/&/g,'&'));
                bot.say('#highaltitude', "@"+tweet.user.screen_name+': '+tweet.text.replace(/&/g,'&'));
        }
});

client.addListener('message', function (from, to, message) {
    if(message.search("/([0-9]+)\s?f[e]{0,2}t\s/") != -1) { // ft/feet
        console.log("Detected feet at "+message.search("/([0-9]+)\s?f[e]{0,2}t/");
        sillyNum=message.substr(message.search("/([0-9]+)\s?f[e]{0,2}t/"),12).match("/([0-9]+)/");
        realNum=parseInt(sillynum)*0.3048;
        console.log(" - Got Number as "+sillyNum);
        bot.say(config.channels[0], "In real units: "+sillyNum+"ft = ");
    }
});

console.log("Loaded.");
<commit_msg>Remove old tweetbot code.<commit_after>console.log("SIBot v0.1");
console.log("Loading...");

var config = {
        channels: ["#sibot-test"],
        server: "chat.freenode.net",
        botName: "SIbot"
};

var irc = require("irc");
var bot = new irc.Client(config.server, config.botName, {
        channels: config.channels
});

client.addListener('message', function (from, to, message) {
    if(message.search("/([0-9]+)\s?f[e]{0,2}t\s/") != -1) { // ft/feet
        console.log("Detected feet at "+message.search("/([0-9]+)\s?f[e]{0,2}t/");
        sillyNum=message.substr(message.search("/([0-9]+)\s?f[e]{0,2}t/"),12).match("/([0-9]+)/");
        realNum=parseInt(sillynum)*0.3048;
        console.log(" - Got Number as "+sillyNum);
        bot.say(config.channels[0], "In real units: "+sillyNum+"ft = ");
    }
});

console.log("Loaded.");
<|endoftext|>


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

d = require('lightsaber/lib/log').d

Nodesphere = require('..')
Metamaps = Nodesphere.adaptor.Metamaps

protocol = 'https://'
domain = 'metamaps.herokuapp.com'
mapId = 3
url = protocol + domain + '/maps/' + mapId

metamaps = new Metamaps()

console.log('Fetching Metamap from ' + url + ' ...')

return Ipfs.create()
.then(function(ipfs) {
  return ipfs.fetch({rootNodeId: 'QmavE42xtK1VovJFVTVkCR5Jdf761QWtxmvak9Zx718TVr'})
}).then(function(sphere) {
  d(sphere)
}).catch(function(error) {
  console.error(error.stack);
})
<commit_msg>fix for example<commit_after>#!/usr/bin/env node

d = require('lightsaber/lib/log').d

Nodesphere = require('..')
Metamaps = Nodesphere.adaptor.Metamaps
Ipfs = Nodesphere.adaptor.Ipfs

protocol = 'https://'
domain = 'metamaps.herokuapp.com'
mapId = 3
url = protocol + domain + '/maps/' + mapId

metamaps = new Metamaps()

console.log('Fetching Metamap from ' + url + ' ...')

return Ipfs.create()
.then(function(ipfs) {
  return ipfs.fetch({rootNodeId: 'QmavE42xtK1VovJFVTVkCR5Jdf761QWtxmvak9Zx718TVr'})
}).then(function(sphere) {
  d(sphere)
}).catch(function(error) {
  console.error(error.stack);
})
<|endoftext|>


<commit_before>import React, {
  useState,
  useEffect,
  useRef
} from 'react';

import {
  Col,
  Row,
  Box,
  Text,
  Icon,
  Button,
  BaseImage
} from '@tlon/indigo-react';
import ReconnectButton from './ReconnectButton';
import { Dropdown } from './Dropdown';
import { StatusBarItem } from './StatusBarItem';
import { Sigil } from '~/logic/lib/sigil';
import { uxToHex } from "~/logic/lib/util";
import { SetStatusBarModal } from './SetStatusBarModal';
import { useTutorialModal } from './useTutorialModal';

import useLocalState from '~/logic/state/local';

const StatusBar = (props) => {
  const { ourContact, api, ship } = props;
  const invites = [].concat(...Object.values(props.invites).map(obj => Object.values(obj)));
  const metaKey = (window.navigator.platform.includes('Mac')) ? '⌘' : 'Ctrl+';
  const { toggleOmnibox, hideAvatars } =
    useLocalState(({ toggleOmnibox, hideAvatars }) =>
      ({ toggleOmnibox, hideAvatars })
    );

  const color = !!ourContact ? `#${uxToHex(props.ourContact.color)}` : '#000';
  const xPadding = (!hideAvatars && ourContact?.avatar) ? '0' : '2';
  const bgColor = (!hideAvatars && ourContact?.avatar) ? '' : color;
  const profileImage = (!hideAvatars && ourContact?.avatar) ? (
    <BaseImage
      src={ourContact.avatar}
      borderRadius={2}
      width='32px'
      height='32px'
      style={{ objectFit: 'cover' }} />
  ) : <Sigil ship={ship} size={16} color={color} icon />;

  const anchorRef = useRef(null);

  const leapHighlight = useTutorialModal('leap', true, anchorRef.current);

  const floatLeap = leapHighlight && window.matchMedia('(max-width: 550px)').matches;

  return (
    <Box
      display='grid'
      width="100%"
      gridTemplateRows="30px"
      gridTemplateColumns="3fr 1fr"
      py='3'
      px='3'
      pb='3'
      >
      <Row collapse>
      <Button width="32px" borderColor='washedGray' mr='2' px='2' onClick={() => props.history.push('/')} {...props}>
        <Icon icon='Spaces' color='black'/>
      </Button>
        <StatusBarItem float={floatLeap} mr={2} onClick={() => toggleOmnibox()}>
        { !props.doNotDisturb && (props.notificationsCount > 0 || invites.length > 0) &&
          (<Box display="block" right="-8px" top="-8px" position="absolute" >
            <Icon color="blue" icon="Bullet" />
           </Box>
        )}
        <Icon icon='LeapArrow'/>
          <Text ref={anchorRef} ml={2} color='black'>
            Leap
          </Text>
          <Text display={['none', 'inline']} ml={2} color='gray'>
            {metaKey}/
          </Text>
        </StatusBarItem>
        <ReconnectButton
          connection={props.connection}
          subscription={props.subscription}
        />
      </Row>
      <Row justifyContent="flex-end" collapse>
        <StatusBarItem
          mr='2'
          backgroundColor='yellow'
          display={process.env.LANDSCAPE_STREAM === 'development' ? 'flex' : 'none'}
          justifyContent="flex-end"
          flexShrink='0'
          onClick={() => window.open(
            'https://github.com/urbit/landscape/issues/new' +
            '?assignees=&labels=development-stream&title=&' +
            `body=commit:%20urbit/urbit@${process.env.LANDSCAPE_SHORTHASH}`
            )}
          >
          <Text color='#000000'>Submit <Text color='#000000' display={['none', 'inline']}>an</Text> issue</Text>
        </StatusBarItem>
        <StatusBarItem mr={2} onClick={() => props.history.push('/~landscape/messages')}>
            <Icon icon="Users"/>
        </StatusBarItem>
        <Dropdown
          dropWidth="150px"
          width="auto"
          alignY="top"
          alignX="right"
          options={
            <Col
              mt='6'
              p='1'
              backgroundColor="white"
              color="washedGray"
              border={1}
              borderRadius={2}
              borderColor="lightGray"
              boxShadow="0px 0px 0px 3px">
              <Row
                p={1}
                color='black'
                cursor='pointer'
                fontSize={1}
                onClick={() => props.history.push(`/~profile/~${ship}`)}>
                View Profile
              </Row>
              <SetStatusBarModal
                ship={`~${ship}`}
                contact={ourContact}
                api={api} />
              <Row
                p={1}
                color='black'
                cursor='pointer'
                fontSize={1}
                onClick={() => props.history.push('/~settings')}>
                System Settings
              </Row>
            </Col>
          }>
          <StatusBarItem
            px={xPadding}
            width="32px"
            flexShrink='0'
            backgroundColor={bgColor}>
            {profileImage}
          </StatusBarItem>
        </Dropdown>
      </Row>
    </Box>
  );
};

export default StatusBar;
<commit_msg>StatusBar: make 'users' icon a square<commit_after>import React, {
  useState,
  useEffect,
  useRef
} from 'react';

import {
  Col,
  Row,
  Box,
  Text,
  Icon,
  Button,
  BaseImage
} from '@tlon/indigo-react';
import ReconnectButton from './ReconnectButton';
import { Dropdown } from './Dropdown';
import { StatusBarItem } from './StatusBarItem';
import { Sigil } from '~/logic/lib/sigil';
import { uxToHex } from "~/logic/lib/util";
import { SetStatusBarModal } from './SetStatusBarModal';
import { useTutorialModal } from './useTutorialModal';

import useLocalState from '~/logic/state/local';

const StatusBar = (props) => {
  const { ourContact, api, ship } = props;
  const invites = [].concat(...Object.values(props.invites).map(obj => Object.values(obj)));
  const metaKey = (window.navigator.platform.includes('Mac')) ? '⌘' : 'Ctrl+';
  const { toggleOmnibox, hideAvatars } =
    useLocalState(({ toggleOmnibox, hideAvatars }) =>
      ({ toggleOmnibox, hideAvatars })
    );

  const color = !!ourContact ? `#${uxToHex(props.ourContact.color)}` : '#000';
  const xPadding = (!hideAvatars && ourContact?.avatar) ? '0' : '2';
  const bgColor = (!hideAvatars && ourContact?.avatar) ? '' : color;
  const profileImage = (!hideAvatars && ourContact?.avatar) ? (
    <BaseImage
      src={ourContact.avatar}
      borderRadius={2}
      width='32px'
      height='32px'
      style={{ objectFit: 'cover' }} />
  ) : <Sigil ship={ship} size={16} color={color} icon />;

  const anchorRef = useRef(null);

  const leapHighlight = useTutorialModal('leap', true, anchorRef.current);

  const floatLeap = leapHighlight && window.matchMedia('(max-width: 550px)').matches;

  return (
    <Box
      display='grid'
      width="100%"
      gridTemplateRows="30px"
      gridTemplateColumns="3fr 1fr"
      py='3'
      px='3'
      pb='3'
      >
      <Row collapse>
      <Button width="32px" borderColor='washedGray' mr='2' px='2' onClick={() => props.history.push('/')} {...props}>
        <Icon icon='Spaces' color='black'/>
      </Button>
        <StatusBarItem float={floatLeap} mr={2} onClick={() => toggleOmnibox()}>
        { !props.doNotDisturb && (props.notificationsCount > 0 || invites.length > 0) &&
          (<Box display="block" right="-8px" top="-8px" position="absolute" >
            <Icon color="blue" icon="Bullet" />
           </Box>
        )}
        <Icon icon='LeapArrow'/>
          <Text ref={anchorRef} ml={2} color='black'>
            Leap
          </Text>
          <Text display={['none', 'inline']} ml={2} color='gray'>
            {metaKey}/
          </Text>
        </StatusBarItem>
        <ReconnectButton
          connection={props.connection}
          subscription={props.subscription}
        />
      </Row>
      <Row justifyContent="flex-end" collapse>
        <StatusBarItem
          mr='2'
          backgroundColor='yellow'
          display={process.env.LANDSCAPE_STREAM === 'development' ? 'flex' : 'none'}
          justifyContent="flex-end"
          flexShrink='0'
          onClick={() => window.open(
            'https://github.com/urbit/landscape/issues/new' +
            '?assignees=&labels=development-stream&title=&' +
            `body=commit:%20urbit/urbit@${process.env.LANDSCAPE_SHORTHASH}`
            )}
          >
          <Text color='#000000'>Submit <Text color='#000000' display={['none', 'inline']}>an</Text> issue</Text>
        </StatusBarItem>
        <StatusBarItem width="32px" mr={2} onClick={() => props.history.push('/~landscape/messages')}>
            <Icon icon="Users"/>
        </StatusBarItem>
        <Dropdown
          dropWidth="150px"
          width="auto"
          alignY="top"
          alignX="right"
          options={
            <Col
              mt='6'
              p='1'
              backgroundColor="white"
              color="washedGray"
              border={1}
              borderRadius={2}
              borderColor="lightGray"
              boxShadow="0px 0px 0px 3px">
              <Row
                p={1}
                color='black'
                cursor='pointer'
                fontSize={1}
                onClick={() => props.history.push(`/~profile/~${ship}`)}>
                View Profile
              </Row>
              <SetStatusBarModal
                ship={`~${ship}`}
                contact={ourContact}
                api={api} />
              <Row
                p={1}
                color='black'
                cursor='pointer'
                fontSize={1}
                onClick={() => props.history.push('/~settings')}>
                System Settings
              </Row>
            </Col>
          }>
          <StatusBarItem
            px={xPadding}
            width="32px"
            flexShrink='0'
            backgroundColor={bgColor}>
            {profileImage}
          </StatusBarItem>
        </Dropdown>
      </Row>
    </Box>
  );
};

export default StatusBar;
<|endoftext|>