<commit_before>'use strict';

var http = require('http');
var https = require('https');
var url = require('url');

function decodeURL(str) {
  var parsedUrl = url.parse(str);
  var hostname = parsedUrl.hostname;
  var port = parseInt(parsedUrl.port, 10);
  var protocol = parsedUrl.protocol;
  // strip trailing ":"
  protocol = protocol.substring(0, protocol.length - 1);
  var auth = parsedUrl.auth;
  var parts = auth.split(':');
  var user = parts[0] ? decodeURIComponent(parts[0]) : null;
  var pass = parts[1] ? decodeURIComponent(parts[1]) : null;
  var opts = {
    host: hostname,
    port: port,
    protocol: protocol,
    user: user,
    pass: pass,
  };
  return opts;
}

function RpcClient(opts) {
  // opts can ba an URL string
  if (typeof opts === 'string') {
    opts = decodeURL(opts);
  }
  opts = opts || {};
  this.host = opts.host || '127.0.0.1';
  this.port = opts.port || 8332;
  this.user = opts.user || 'user';
  this.pass = opts.pass || 'pass';
  this.protocol = opts.protocol === 'http' ? http : https;
  this.batchedCalls = null;
  this.disableAgent  = opts.disableAgent || false;

  var isRejectUnauthorized = typeof opts.rejectUnauthorized !== 'undefined';
  this.rejectUnauthorized = isRejectUnauthorized ? opts.rejectUnauthorized : true;

  if(RpcClient.config.log) {
    this.log = RpcClient.config.log;
  } else {
    this.log = RpcClient.loggers[RpcClient.config.logger || 'normal'];
  }

}

var cl = console.log.bind(console);

var noop = function() {};

RpcClient.loggers = {
  none: {info: noop, warn: noop, err: noop, debug: noop},
  normal: {info: cl, warn: cl, err: cl, debug: noop},
  debug: {info: cl, warn: cl, err: cl, debug: cl}
};

RpcClient.config = {
  logger: 'normal' // none, normal, debug
};

function rpc(request, callback) {

  var self = this;
  request = JSON.stringify(request);
  var auth = new Buffer(self.user + ':' + self.pass).toString('base64');

  var options = {
    host: self.host,
    path: '/',
    method: 'POST',
    port: self.port,
    rejectUnauthorized: self.rejectUnauthorized,
    agent: self.disableAgent ? false : undefined
  };

  if (self.httpOptions) {
    for (var k in self.httpOptions) {
      options[k] = self.httpOptions[k];
    }
  }

  var called = false;

  var errorMessage = 'Bitcoin JSON-RPC: ';

  var req = this.protocol.request(options, function(res) {

    var buf = '';
    res.on('data', function(data) {
      buf += data;
    });

    res.on('end', function() {

      if (called) {
        return;
      }
      called = true;

      if (res.statusCode === 401) {
        callback(new Error(errorMessage + 'Connection Rejected: 401 Unnauthorized'));
        return;
      }
      if (res.statusCode === 403) {
        callback(new Error(errorMessage + 'Connection Rejected: 403 Forbidden'));
        return;
      }
      if (res.statusCode === 500 && buf.toString('utf8') === 'Work queue depth exceeded') {
        var exceededError = new Error('Bitcoin JSON-RPC: ' + buf.toString('utf8'));
        exceededError.code = 429; // Too many requests
        callback(exceededError);
        return;
      }

      var parsedBuf;
      try {
        parsedBuf = JSON.parse(buf);
      } catch(e) {
        self.log.err(e.stack);
        self.log.err(buf);
        self.log.err('HTTP Status code:' + res.statusCode);
        var err = new Error(errorMessage + 'Error Parsing JSON: ' + e.message);
        callback(err);
        return;
      }

      callback(parsedBuf.error, parsedBuf);

    });
  });

  req.on('error', function(e) {
    var err = new Error(errorMessage + 'Request Error: ' + e.message);
    if (!called) {
      called = true;
      callback(err);
    }
  });

  req.setHeader('Content-Length', request.length);
  req.setHeader('Content-Type', 'application/json');
  req.setHeader('Authorization', 'Basic ' + auth);
  req.write(request);
  req.end();
}

RpcClient.prototype.batch = function(batchCallback, resultCallback) {
  this.batchedCalls = [];
  batchCallback();
  rpc.call(this, this.batchedCalls, resultCallback);
  this.batchedCalls = null;
};

RpcClient.callspec = {
  abandonTransaction: 'str',
  addMultiSigAddress: '',
  addNode: '',
  backupWallet: '',
  createMultiSig: '',
  createRawTransaction: 'obj obj',
  decodeRawTransaction: '',
  dumpPrivKey: '',
  encryptWallet: '',
  estimateFee: '',
  estimateSmartFee: 'int str',
  estimatePriority: 'int',
  generate: 'int',
  generateToAddress: 'int str',
  getAccount: '',
  getAccountAddress: 'str',
  getAddedNodeInfo: '',
  getAddressMempool: 'obj',
  getAddressUtxos: 'obj',
  getAddressBalance: 'obj',
  getAddressDeltas: 'obj',
  getAddressTxids: 'obj',
  getAddressesByAccount: '',
  getBalance: 'str int',
  getBestBlockHash: '',
  getBlockDeltas: 'str',
  getBlock: 'str int',
  getBlockchainInfo: '',
  getBlockCount: '',
  getBlockHashes: 'int int obj',
  getBlockHash: 'int',
  getBlockHeader: 'str',
  getBlockNumber: '',
  getBlockTemplate: '',
  getConnectionCount: '',
  getChainTips: '',
  getDifficulty: '',
  getGenerate: '',
  getHashesPerSec: '',
  getInfo: '',
  getMemoryPool: '',
  getMemPoolEntry: 'str',
  getMemPoolInfo: '',
  getMiningInfo: '',
  getNetworkInfo: '',
  getNewAddress: '',
  getPeerInfo: '',
  getRawMemPool: 'bool',
  getRawTransaction: 'str int',
  getReceivedByAccount: 'str int',
  getReceivedByAddress: 'str int',
  getSpentInfo: 'obj',
  getTransaction: '',
  getTxOut: 'str int bool',
  getTxOutSetInfo: '',
  getWalletInfo: '',
  getWork: '',
  help: '',
  importAddress: 'str str bool',
  importMulti: 'obj obj',
  importPrivKey: 'str str bool',
  invalidateBlock: 'str',
  keyPoolRefill: '',
  listAccounts: 'int',
  listAddressGroupings: '',
  listReceivedByAccount: 'int bool',
  listReceivedByAddress: 'int bool',
  listSinceBlock: 'str int',
  listTransactions: 'str int int',
  listUnspent: 'int int',
  listLockUnspent: 'bool',
  lockUnspent: '',
  move: 'str str float int str',
  prioritiseTransaction: 'str float int',
  sendFrom: 'str str float int str str',
  sendMany: 'str obj int str',  //not sure this is will work
  sendRawTransaction: 'str',
  sendToAddress: 'str float str str',
  setAccount: '',
  setGenerate: 'bool int',
  setTxFee: 'float',
  signMessage: '',
  signRawTransaction: '',
  signRawTransactionWithWallet: 'str',
  stop: '',
  submitBlock: '',
  validateAddress: '',
  verifyMessage: '',
  walletLock: '',
  walletPassPhrase: 'string int',
  walletPassphraseChange: '',
};

var slice = function(arr, start, end) {
  return Array.prototype.slice.call(arr, start, end);
};

function generateRPCMethods(constructor, apiCalls, rpc) {

  function createRPCMethod(methodName, argMap) {
    return function() {

      var limit = arguments.length - 1;

      if (this.batchedCalls) {
        limit = arguments.length;
      }

      for (var i = 0; i < limit; i++) {
        if(argMap[i]) {
          arguments[i] = argMap[i](arguments[i]);
        }
      }

      if (this.batchedCalls) {
        this.batchedCalls.push({
          jsonrpc: '2.0',
          method: methodName,
          params: slice(arguments),
          id: getRandomId()
        });
      } else {
        rpc.call(this, {
          method: methodName,
          params: slice(arguments, 0, arguments.length - 1),
          id: getRandomId()
        }, arguments[arguments.length - 1]);
      }

    };
  };

  var types = {
    str: function(arg) {
      return arg.toString();
    },
    int: function(arg) {
      return parseFloat(arg);
    },
    float: function(arg) {
      return parseFloat(arg);
    },
    bool: function(arg) {
      return (arg === true || arg == '1' || arg == 'true' || arg.toString().toLowerCase() == 'true');
    },
    obj: function(arg) {
      if(typeof arg === 'string') {
        return JSON.parse(arg);
      }
      return arg;
    }
  };

  for(var k in apiCalls) {
    var spec = [];
    if (apiCalls[k].length) {
      spec = apiCalls[k].split(' ');
      for (var i = 0; i < spec.length; i++) {
        if(types[spec[i]]) {
          spec[i] = types[spec[i]];
        } else {
          spec[i] = types.str;
        }
      }
    }
    var methodName = k.toLowerCase();
    constructor.prototype[k] = createRPCMethod(methodName, spec);
    constructor.prototype[methodName] = constructor.prototype[k];
  }

}

function getRandomId() {
  return parseInt(Math.random() * 100000);
}

generateRPCMethods(RpcClient, RpcClient.callspec, rpc);

module.exports = RpcClient;
<commit_msg>Add bumpfee capability<commit_after>'use strict';

var http = require('http');
var https = require('https');
var url = require('url');

function decodeURL(str) {
  var parsedUrl = url.parse(str);
  var hostname = parsedUrl.hostname;
  var port = parseInt(parsedUrl.port, 10);
  var protocol = parsedUrl.protocol;
  // strip trailing ":"
  protocol = protocol.substring(0, protocol.length - 1);
  var auth = parsedUrl.auth;
  var parts = auth.split(':');
  var user = parts[0] ? decodeURIComponent(parts[0]) : null;
  var pass = parts[1] ? decodeURIComponent(parts[1]) : null;
  var opts = {
    host: hostname,
    port: port,
    protocol: protocol,
    user: user,
    pass: pass,
  };
  return opts;
}

function RpcClient(opts) {
  // opts can ba an URL string
  if (typeof opts === 'string') {
    opts = decodeURL(opts);
  }
  opts = opts || {};
  this.host = opts.host || '127.0.0.1';
  this.port = opts.port || 8332;
  this.user = opts.user || 'user';
  this.pass = opts.pass || 'pass';
  this.protocol = opts.protocol === 'http' ? http : https;
  this.batchedCalls = null;
  this.disableAgent  = opts.disableAgent || false;

  var isRejectUnauthorized = typeof opts.rejectUnauthorized !== 'undefined';
  this.rejectUnauthorized = isRejectUnauthorized ? opts.rejectUnauthorized : true;

  if(RpcClient.config.log) {
    this.log = RpcClient.config.log;
  } else {
    this.log = RpcClient.loggers[RpcClient.config.logger || 'normal'];
  }

}

var cl = console.log.bind(console);

var noop = function() {};

RpcClient.loggers = {
  none: {info: noop, warn: noop, err: noop, debug: noop},
  normal: {info: cl, warn: cl, err: cl, debug: noop},
  debug: {info: cl, warn: cl, err: cl, debug: cl}
};

RpcClient.config = {
  logger: 'normal' // none, normal, debug
};

function rpc(request, callback) {

  var self = this;
  request = JSON.stringify(request);
  var auth = new Buffer(self.user + ':' + self.pass).toString('base64');

  var options = {
    host: self.host,
    path: '/',
    method: 'POST',
    port: self.port,
    rejectUnauthorized: self.rejectUnauthorized,
    agent: self.disableAgent ? false : undefined
  };

  if (self.httpOptions) {
    for (var k in self.httpOptions) {
      options[k] = self.httpOptions[k];
    }
  }

  var called = false;

  var errorMessage = 'Bitcoin JSON-RPC: ';

  var req = this.protocol.request(options, function(res) {

    var buf = '';
    res.on('data', function(data) {
      buf += data;
    });

    res.on('end', function() {

      if (called) {
        return;
      }
      called = true;

      if (res.statusCode === 401) {
        callback(new Error(errorMessage + 'Connection Rejected: 401 Unnauthorized'));
        return;
      }
      if (res.statusCode === 403) {
        callback(new Error(errorMessage + 'Connection Rejected: 403 Forbidden'));
        return;
      }
      if (res.statusCode === 500 && buf.toString('utf8') === 'Work queue depth exceeded') {
        var exceededError = new Error('Bitcoin JSON-RPC: ' + buf.toString('utf8'));
        exceededError.code = 429; // Too many requests
        callback(exceededError);
        return;
      }

      var parsedBuf;
      try {
        parsedBuf = JSON.parse(buf);
      } catch(e) {
        self.log.err(e.stack);
        self.log.err(buf);
        self.log.err('HTTP Status code:' + res.statusCode);
        var err = new Error(errorMessage + 'Error Parsing JSON: ' + e.message);
        callback(err);
        return;
      }

      callback(parsedBuf.error, parsedBuf);

    });
  });

  req.on('error', function(e) {
    var err = new Error(errorMessage + 'Request Error: ' + e.message);
    if (!called) {
      called = true;
      callback(err);
    }
  });

  req.setHeader('Content-Length', request.length);
  req.setHeader('Content-Type', 'application/json');
  req.setHeader('Authorization', 'Basic ' + auth);
  req.write(request);
  req.end();
}

RpcClient.prototype.batch = function(batchCallback, resultCallback) {
  this.batchedCalls = [];
  batchCallback();
  rpc.call(this, this.batchedCalls, resultCallback);
  this.batchedCalls = null;
};

RpcClient.callspec = {
  abandonTransaction: 'str',
  addMultiSigAddress: '',
  addNode: '',
  backupWallet: '',
  bumpFee: 'str',
  createMultiSig: '',
  createRawTransaction: 'obj obj',
  decodeRawTransaction: '',
  dumpPrivKey: '',
  encryptWallet: '',
  estimateFee: '',
  estimateSmartFee: 'int str',
  estimatePriority: 'int',
  generate: 'int',
  generateToAddress: 'int str',
  getAccount: '',
  getAccountAddress: 'str',
  getAddedNodeInfo: '',
  getAddressMempool: 'obj',
  getAddressUtxos: 'obj',
  getAddressBalance: 'obj',
  getAddressDeltas: 'obj',
  getAddressTxids: 'obj',
  getAddressesByAccount: '',
  getBalance: 'str int',
  getBestBlockHash: '',
  getBlockDeltas: 'str',
  getBlock: 'str int',
  getBlockchainInfo: '',
  getBlockCount: '',
  getBlockHashes: 'int int obj',
  getBlockHash: 'int',
  getBlockHeader: 'str',
  getBlockNumber: '',
  getBlockTemplate: '',
  getConnectionCount: '',
  getChainTips: '',
  getDifficulty: '',
  getGenerate: '',
  getHashesPerSec: '',
  getInfo: '',
  getMemoryPool: '',
  getMemPoolEntry: 'str',
  getMemPoolInfo: '',
  getMiningInfo: '',
  getNetworkInfo: '',
  getNewAddress: '',
  getPeerInfo: '',
  getRawMemPool: 'bool',
  getRawTransaction: 'str int',
  getReceivedByAccount: 'str int',
  getReceivedByAddress: 'str int',
  getSpentInfo: 'obj',
  getTransaction: '',
  getTxOut: 'str int bool',
  getTxOutSetInfo: '',
  getWalletInfo: '',
  getWork: '',
  help: '',
  importAddress: 'str str bool',
  importMulti: 'obj obj',
  importPrivKey: 'str str bool',
  invalidateBlock: 'str',
  keyPoolRefill: '',
  listAccounts: 'int',
  listAddressGroupings: '',
  listReceivedByAccount: 'int bool',
  listReceivedByAddress: 'int bool',
  listSinceBlock: 'str int',
  listTransactions: 'str int int',
  listUnspent: 'int int',
  listLockUnspent: 'bool',
  lockUnspent: '',
  move: 'str str float int str',
  prioritiseTransaction: 'str float int',
  sendFrom: 'str str float int str str',
  sendMany: 'str obj int str',  //not sure this is will work
  sendRawTransaction: 'str',
  sendToAddress: 'str float str str',
  setAccount: '',
  setGenerate: 'bool int',
  setTxFee: 'float',
  signMessage: '',
  signRawTransaction: '',
  signRawTransactionWithWallet: 'str',
  stop: '',
  submitBlock: '',
  validateAddress: '',
  verifyMessage: '',
  walletLock: '',
  walletPassPhrase: 'string int',
  walletPassphraseChange: '',
};

var slice = function(arr, start, end) {
  return Array.prototype.slice.call(arr, start, end);
};

function generateRPCMethods(constructor, apiCalls, rpc) {

  function createRPCMethod(methodName, argMap) {
    return function() {

      var limit = arguments.length - 1;

      if (this.batchedCalls) {
        limit = arguments.length;
      }

      for (var i = 0; i < limit; i++) {
        if(argMap[i]) {
          arguments[i] = argMap[i](arguments[i]);
        }
      }

      if (this.batchedCalls) {
        this.batchedCalls.push({
          jsonrpc: '2.0',
          method: methodName,
          params: slice(arguments),
          id: getRandomId()
        });
      } else {
        rpc.call(this, {
          method: methodName,
          params: slice(arguments, 0, arguments.length - 1),
          id: getRandomId()
        }, arguments[arguments.length - 1]);
      }

    };
  };

  var types = {
    str: function(arg) {
      return arg.toString();
    },
    int: function(arg) {
      return parseFloat(arg);
    },
    float: function(arg) {
      return parseFloat(arg);
    },
    bool: function(arg) {
      return (arg === true || arg == '1' || arg == 'true' || arg.toString().toLowerCase() == 'true');
    },
    obj: function(arg) {
      if(typeof arg === 'string') {
        return JSON.parse(arg);
      }
      return arg;
    }
  };

  for(var k in apiCalls) {
    var spec = [];
    if (apiCalls[k].length) {
      spec = apiCalls[k].split(' ');
      for (var i = 0; i < spec.length; i++) {
        if(types[spec[i]]) {
          spec[i] = types[spec[i]];
        } else {
          spec[i] = types.str;
        }
      }
    }
    var methodName = k.toLowerCase();
    constructor.prototype[k] = createRPCMethod(methodName, spec);
    constructor.prototype[methodName] = constructor.prototype[k];
  }

}

function getRandomId() {
  return parseInt(Math.random() * 100000);
}

generateRPCMethods(RpcClient, RpcClient.callspec, rpc);

module.exports = RpcClient;
<|endoftext|>


<commit_before>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 5/9/13
 * Time: 11:48 AM
 */

define([
    'plugins/plugin.element'
], function defineParticipantsElement(PluginElement) {

    /**
     * Define Participants Element
     * @param view
     * @param opts
     * @returns {ParticipantsElement}
     * @constructor
     * @class ParticipantsElement
     * @extends PluginElement
     */
    var ParticipantsElement = function ParticipantsElement(view, opts) {

        this._config(view, opts, $('
')).build({
            $container: opts.$container,
            destroy: true
        });

        this.addCSS('participants', {resource: '/widgets'});

        return this;
    };

    return ParticipantsElement.extend('ParticipantsElement', {

        /**
         * Render Embedded content
         * @memberOf ParticipantsElement
         */
        renderEmbeddedContent: function renderEmbeddedContent() {
            var data = [
                {
                    "name": "Naseem Hamed",
                    "fairPlayPoints": "434",
                    "icon": "1.jpg"
                },
                {
                    "name": "Eyal ben david",
                    "fairPlayPoints": "151",
                    "icon": "2.jpg"
                },
                {
                    "name": "Arkan Shalaban",
                    "fairPlayPoints": "602",
                    "icon": "3.jpg"
                },
                // {
                //     "name": "David",
                //     "fairPlayPoints": "7",
                //     "icon": "4.jpg"
                // },
                {
                    "name": "Vladimir Tkach",
                    "fairPlayPoints": "84",
                    "icon": "5.jpg"
                },
                {
                    "name": "Gilad",
                    "fairPlayPoints": "92",
                    "icon": "6.jpg"
                }
            ];

            this.$.append('
');

            var $ul = this.$.find('ul');
            for (var i = 0; i < data.length; i++) {

                $ul.append([
                    '
',
                    '',
                    '
', data[i].name, ' (', data[i].fairPlayPoints, ')
',
                    '',
                    '
'
                ].join(''));
            }

        }

    }, PluginElement.prototype);
});
<commit_msg>Update participants.element.js<commit_after>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 5/9/13
 * Time: 11:48 AM
 */

define([
    'plugins/plugin.element'
], function defineParticipantsElement(PluginElement) {

    /**
     * Define Participants Element
     * @param view
     * @param opts
     * @returns {ParticipantsElement}
     * @constructor
     * @class ParticipantsElement
     * @extends PluginElement
     */
    var ParticipantsElement = function ParticipantsElement(view, opts) {

        this._config(view, opts, $('
')).build({
            $container: opts.$container,
            destroy: true
        });

        this.addCSS('participants', {resource: '/widgets'});

        return this;
    };

    return ParticipantsElement.extend('ParticipantsElement', {

        /**
         * Render Embedded content
         * @memberOf ParticipantsElement
         */
        renderEmbeddedContent: function renderEmbeddedContent() {
            var data = [
                {
                    "name": "ronaldo7",
                    "fairPlayPoints": "434",
                    "icon": "1.jpg"
                },
                {
                    "name": "Mesi",
                    "fairPlayPoints": "151",
                    "icon": "2.jpg"
                },
                {
                    "name": "Wonder woman",
                    "fairPlayPoints": "602",
                    "icon": "3.jpg"
                },
                // {
                //     "name": "David",
                //     "fairPlayPoints": "7",
                //     "icon": "4.jpg"
                // },
                {
                    "name": "Vova",
                    "fairPlayPoints": "84",
                    "icon": "5.jpg"
                },
                {
                    "name": "Mr G",
                    "fairPlayPoints": "92",
                    "icon": "6.jpg"
                }
            ];

            this.$.append('
');

            var $ul = this.$.find('ul');
            for (var i = 0; i < data.length; i++) {

                $ul.append([
                    '
',
                    '',
                    '
', data[i].name, ' (', data[i].fairPlayPoints, ')
',
                    '',
                    '
'
                ].join(''));
            }

        }

    }, PluginElement.prototype);
});
<|endoftext|>


<commit_before>console.log('started');
var https = require('https'),
    http = require('http'),
    util  = require('util'),
    path  = require('path'),
    url = require('url');
    fs    = require('fs'),
    httpProxy = require('http-proxy'),
    log4js = require('log4js'),
    testDir = path.join(__dirname, 'test', 'ssl');
console.log("configure log4js");
var logDir = "./logs";
if (!fs.existsSync(logDir)) {
    console.log("no log folder");
    fs.mkdirSync(logDir);
}
log4js.configure({
    appenders: [
        { type: 'console' },
        {
            type: 'file',
            filename: 'logs/startup.log',
            "maxLogSize": 20480,
            "backups": 3
            //category: ['startup','console']
        }
    ],
    replaceConsole: true
});
var logger = log4js.getLogger('testing');
//logger.setLevel('INFO');
console.log("logger retrieved");
logger.info("requires loaded");
//var port = 80;
var port = process.env.port || 1333;
var options = {
    target: {
        host: 'maps.ngdc.noaa.gov'//,
        //port: 80
    },
    headers: {
        host: 'maps.ngdc.noaa.gov'
    }//,
    //ssl: {
    //    key: fs.readFileSync(path.join(testDir, 'agent2-key.pem'), 'utf8'),
    //    cert: fs.readFileSync(path.join(testDir, 'agent2-cert.pem'), 'utf8')
    //}
};
var proxy = httpProxy.createServer(options).listen(port);
proxy.on("error", function() {
   logger.error("error!!!");
});
proxy.on('proxyReq', function() {
   logger.info("proxy inbound");
});
logger.info('listening port: '+ port);
<commit_msg>working version<commit_after>console.log('started');
var https = require('https'),
    http = require('http'),
    util  = require('util'),
    path  = require('path'),
    url = require('url');
    fs    = require('fs'),
    httpProxy = require('http-proxy'),
    log4js = require('log4js'),
    testDir = path.join(__dirname, 'test', 'ssl');
console.log("configure log4js");
var logDir = "./logs";
if (!fs.existsSync(logDir)) {
    console.log("no log folder");
    fs.mkdirSync(logDir);
}
log4js.configure({
    appenders: [
        { type: 'console' },
        {
            type: 'file',
            filename: 'logs/startup.log',
            "maxLogSize": 20480,
            "backups": 3
            //category: ['startup','console']
        }
    ],
    replaceConsole: true
});
var logger = log4js.getLogger('testing');
//logger.setLevel('INFO');
console.log("logger retrieved");
logger.info("requires loaded");
//var port = 80;
var port = process.env.port || 1333;
var options = {
    target: {
        host: 'maps.ngdc.noaa.gov'//,
    },
    headers: {
        host: 'maps.ngdc.noaa.gov'
    }//,
    //ssl: {
    //    key: fs.readFileSync(path.join(testDir, 'agent2-key.pem'), 'utf8'),
    //    cert: fs.readFileSync(path.join(testDir, 'agent2-cert.pem'), 'utf8')
    //}
};
//var proxy = httpProxy.createServer(options).listen(port);
var proxies = {
  'ngdc': { site: 'maps.ngdc.noaa.gov' },
  'test': { site: 'google.com' }
};
for (context in proxies) {
  var url = proxies[context].site;
  proxies[context].proxyServer = new httpProxy.createProxyServer({
    target: {
        host: url
    },
    headers: {
        host: url
    }
  });
}
// E.g. localhost:1333/ngdc/arcgis/rest/services
var proxy = http.createServer(function (req, res) {
  logger.info(req.url);
  //grab the first thing in the url. This will tell us what to proxy
  // E.g. With localhost:1333/ngdc/arcgis/rest/services the context will be ngdc
  var urlArray = req.url.split('/');
      context = urlArray[1];
  logger.info(req.url);
  if (proxies[context]) {
    //remove the part of the url that tells us what to proxy
    // E.g. With localhost:1333/ngdc/arcgis/rest/services has the url /ngdc/arcgis/rest/services but we want to proxy /arcgis/rest/services
    urlArray.splice(0,2);
    var proxyUrl = "/" + urlArray.join('/');
    logger.info("proxyUrl:"+ proxyUrl);
    req.url = proxyUrl;
    proxies[context].proxyServer.web(req,res);
  }
  else {
    var allowedContexts = "";
    for (proxyContext in proxies) {
      allowedContexts += " " + proxyContext;
    }
    logger.error("invalid request context(" + context + "). It has to be one of the following:" + allowedContexts);
  }
}).listen(port);
proxy.on("error", function() {
   logger.error("error!!!");
});
proxy.on('proxyReq', function() {
   logger.info("proxy inbound");
});
logger.info('listening port: '+ port);
<|endoftext|>


<commit_before>
"use strict";

var Scale = function () {};

Scale.ionian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["11", 5],
	["5", 7],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.dorian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.phrygian = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.lydian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["#11", 6],
	["P5", 7],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.mixolydian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["11", 5],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.aeolian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.locrian = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["b3", 3],
	["11", 5],
	["b5", 6],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.melodicMinor = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.harmonicMinor = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["b6", 8],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.harmonicMinorPerfect5thBelow = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["3", 4],
	["11", 5],
	["P5", 7],
	["b6", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.altered = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["#9", 3],
	["3", 4],
	["#11", 6],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.symmetricDiminished = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["b3", 3],
	["3", 4],
	["#11", 6],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.lydian7th = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["#11", 6],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.wholeTone = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["#11", 6],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.getData = function (root, degrees) {
    var dic = {};
    degrees.forEach(function (degree) {
	var pitch = Pitch.getPitchName(root, degree[1]);
	dic[pitch] = degree[0];
    });
    return dic;
};

if (window && window.module) {
    module.exports = Scale;
}
<commit_msg>fix half whole diminished scale<commit_after>
"use strict";

var Scale = function () {};

Scale.ionian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["11", 5],
	["5", 7],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.dorian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.phrygian = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.lydian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["#11", 6],
	["P5", 7],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.mixolydian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["11", 5],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.aeolian = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.locrian = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["b3", 3],
	["11", 5],
	["b5", 6],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.melodicMinor = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.harmonicMinor = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["P5", 7],
	["b6", 8],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.harmonicMinorPerfect5thBelow = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["3", 4],
	["11", 5],
	["P5", 7],
	["b6", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.altered = function (root) {
    var degrees = [
	["1", 0],
	["b9", 1],
	["#9", 3],
	["3", 4],
	["#11", 6],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.symmetricDiminished = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["b3", 3],
	["11", 5],
	["#11", 6],
	["b13", 8],
	["13", 9],
	["7", 11]
    ];
    return Scale.getData(root, degrees);
};

Scale.lydian7th = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["#11", 6],
	["P5", 7],
	["13", 9],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.wholeTone = function (root) {
    var degrees = [
	["1", 0],
	["9", 2],
	["3", 4],
	["#11", 6],
	["b13", 8],
	["b7", 10]
    ];
    return Scale.getData(root, degrees);
};

Scale.getData = function (root, degrees) {
    var dic = {};
    degrees.forEach(function (degree) {
	var pitch = Pitch.getPitchName(root, degree[1]);
	dic[pitch] = degree[0];
    });
    return dic;
};

if (window && window.module) {
    module.exports = Scale;
}
<|endoftext|>


<commit_before>/*
 * Gritter for jQuery
 * http://www.boedesign.com/
 *
 * Copyright (c) 2012 Jordan Boesch
 * Dual licensed under the MIT and GPL licenses.
 *
 * Date: February 24, 2012
 * Version: 1.7.4
 */

(function($){
    /**
     * Set it up as an object under the jQuery namespace
     */
    $.gritter = {};
    var Gritter;

    /**
     * Set up global options that the user can over-ride
     */
    $.gritter.options = {
        position: '',
        class_name: '', // set on the gritter-item
        fade_in_speed: 'medium', // how fast notifications fade in
        fade_out_speed: 800, // how fast the notices fade out
        append: true,
        time: 6000 // hang on the screen for...
    };

    /**
     * Add a gritter notification to the screen
     * @see Gritter#add();
     */
    $.gritter.add = function(params)
    {
        try
        {
            return Gritter.add(params || {});
        }
        catch(e)
        {
            var err = 'Gritter Error: ' + e;
            (typeof(console) != 'undefined' && console.error) ?
                console.error(err, params) :
                alert(err);
        }
    };

    /**
     * Remove a gritter notification from the screen
     * @see Gritter#removeSpecific();
     */
    $.gritter.remove = function(id, params)
    {
        Gritter.removeSpecific(id, params || {});
    };

    /**
     * Remove all notifications
     * @see Gritter#stop();
     */
    $.gritter.removeAll = function(params)
    {
        Gritter.stop(params || {});
    };

    /**
     * Get notice wrapper
     * @see Gritter#noticeWrapper();
     */
    $.gritter.noticeWrapper = function()
    {
        return Gritter.noticeWrapper();
    };

    /**
     * @constructor
     */
    Gritter = {

        // Public - options to over-ride with $.gritter.options in "add"
        position: '',
        fade_in_speed: '',
        fade_out_speed: '',
        time: '',

        // Private - no touchy the private parts
        _custom_timer: 0,
        _item_count: 0,
        _is_setup: 0,
        _tpl_close: 'Close Notification',
        _tpl_drag: 'Enable Drag',
        _tpl_title: '[[title]]',
        _tpl_item: '

[[drag]][[close]][[image]][[title]][[text]]

',
        _tpl_wrap: '

',

        /**
         * Add a gritter notification to the screen
         * @param {Object} params The object that contains all the options for drawing the notification
         * @return {int} The specific numeric id to that gritter notification
         */
        add: function(params)
        {
            // Handle straight text
            if (typeof(params) == 'string')
            {
                params = {text:params};
            }

            // We might have some issues if we don't have a title or text!
            if (params.text === null)
            {
                throw 'You must supply "text" parameter.';
            }

            // Check the options and set them once
            if (!this._is_setup)
            {
                this._runSetup();
            }

            // Basics
            var title = params.title,
                text = params.text,
                append = params.append,
                image = params.image || '',
                sticky = params.sticky || false,
                item_class = params.class_name || $.gritter.options.class_name,
                position = $.gritter.options.position,
                time_alive = params.time || '';

            this._verifyWrapper();
            this._item_count++;
            var number = this._item_count, tmp = this._tpl_item;

            // Assign callbacks
            $(['before_open', 'after_open', 'before_close', 'after_close']).each(function(i, val)
            {
                Gritter['_' + val + '_' + number] = ($.isFunction(params[val])) ? params[val] : function(){}
            });

            // Reset
            this._custom_timer = 0;

            // A custom fade time set
            if (time_alive)
            {
                this._custom_timer = time_alive;
            }

            var image_str = (image != '') ? '' : '';

            // String replacements on the template
            title = title ? this._str_replace('[[title]]', title, this._tpl_title) : '';

            tmp = this._str_replace(
                ['[[title]]', '[[text]]', '[[drag]]', '[[close]]', '[[image]]', '[[number]]', '[[class_name]]', '[[item_class]]'],
                [title, text, this._tpl_drag, this._tpl_close, image_str, this._item_count, '', item_class], tmp
            );

            var popup = $('#gritter-notice-wrapper').addClass(position);
            if (append)
            {
                popup.append(tmp);
            }
            else
            {
                popup.prepend(tmp);
            }
            var item = $('#gritter-item-' + this._item_count);

            item.fadeIn(this.fade_in_speed, function()
            {
                Gritter['_after_open_' + number]($(this));
            });

            if (!sticky)
            {
                this._setFadeTimer(item, number);
            }

            // Bind the hover/unhover states
            $(item).bind('mouseenter mouseleave', function(event)
            {
                if (event.type == 'mouseenter')
                {
                    if (!sticky)
                    {
                        Gritter._restoreItemIfFading($(this), number);
                    }
                }
                else
                {
                    if (!sticky)
                    {
                        Gritter._setFadeTimer($(this), number);
                    }
                }
                Gritter._hoverState($(this), event.type);
            });

            // Clicking (X) makes it close
            $(item).find('.gritter-close').click(function()
            {
                Gritter.removeSpecific(number, {}, null, true);
                return false;
            });

            item.draggable({
                containment: 'body',
                stack: '#gritter-notice-wrapper div'
            });
            item.draggable('disable');
            $(item).find('.gritter-drag').click(function() {
                var offset, width;
                if (item.parent().is('body')) {
                    item.detach();
                    $('#gritter-notice-wrapper').append(item);
                    item.css({position:'', top:'', left:'', width:''});
                    item.draggable('disable');
                } else {
                    offset = item.offset();
                    width = item.width();
                    item.detach();
                    $('body').append(item);
                    item.css({position: 'absolute', top: offset.top, left: offset.left, width: width});
                    item.draggable('enable');
                }
            });

            return number;

        },

        /**
         * If we don't have any more gritter notifications, get rid of the wrapper using this check
         * @private
         * @param {int} unique_id The ID of the element that was just deleted, use it for a callback
         * @param {Object} e The jQuery element that we're going to perform the remove() action on
         * @param {Boolean} manual_close Did we close the gritter dialog with the (X) button
         */
        _countRemoveWrapper: function(unique_id, e, manual_close)
        {
            // Remove it then run the callback function
            e.remove();
            this['_after_close_' + unique_id](e, manual_close);

            // Check if the wrapper is empty, if it is.. remove the wrapper
            if (!$('.gritter-item-wrapper').length)
            {
                $('#gritter-notice-wrapper').remove();
            }

        },

        /**
         * Fade out an element after it's been on the screen for x amount of time
         * @private
         * @param {Object} e The jQuery element to get rid of
         * @param {int} unique_id The id of the element to remove
         * @param {Object} params An optional list of params to set fade speeds etc.
         * @param {Boolean} unbind_events Unbind the mouseenter/mouseleave events if they click (X)
         */
        _fade: function(e, unique_id, params, unbind_events)
        {
            var params = params || {},
                fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
                fade_out_speed = params.speed || this.fade_out_speed,
                manual_close = unbind_events;

            this['_before_close_' + unique_id](e, manual_close);

            // If this is true, then we are coming from clicking the (X)
            if (unbind_events)
            {
                e.unbind('mouseenter mouseleave');
            }

            // Fade it out or remove it
            if (fade)
            {
                e.animate({
                    opacity: 0
                }, fade_out_speed, function()
                {
                    e.animate({ height: 0 }, 300, function()
                    {
                        Gritter._countRemoveWrapper(unique_id, e, manual_close);
                    })
                })
            }
            else
            {
                this._countRemoveWrapper(unique_id, e);
            }
        },

        /**
         * Perform actions based on the type of bind (mouseenter, mouseleave)
         * @private
         * @param {Object} e The jQuery element
         * @param {String} type The type of action we're performing: mouseenter or mouseleave
         */
        _hoverState: function(e, type)
        {
            // Change the border styles and add the (X) close button when you hover
            if (type == 'mouseenter')
            {
                e.addClass('hover');

                // Show close button
                e.find('.gritter-close, .gritter-drag').show();

            }
            // Remove the border styles and hide (X) close button when you mouse out
            else
            {
                e.removeClass('hover');

                // Hide close button
                e.find('.gritter-close, .gritter-drag').hide();
            }
        },

        /**
         * Remove a specific notification based on an ID
         * @param {Integer} unique_id The ID used to delete a specific notification
         * @param {Object} params A set of options passed in to determine how to get rid of it
         * @param {Object} e The jQuery element that we're "fading" then removing
         * @param {Boolean} unbind_events If we clicked on the (X) we set this to true to unbind mouseenter/mouseleave
         */
        removeSpecific: function(unique_id, params, e, unbind_events)
        {
            if (!e)
            {
                e = $('#gritter-item-' + unique_id);
            }

            // We set the fourth param to let the _fade function know to
            // unbind the "mouseleave" event.  Once you click (X) there's no going back!
            this._fade(e, unique_id, params || {}, unbind_events);
        },

        /**
         * If the item is fading out and we hover over it, restore it!
         * @private
         * @param e The HTML element to remove
         * @param unique_id The ID of the element
         */
        _restoreItemIfFading: function(e, unique_id)
        {
            clearTimeout(this['_int_id_' + unique_id]);
            e.stop().css({ opacity: '', height: '' });

        },

        /**
         * Setup the global options - only once
         * @private
         */
        _runSetup: function()
        {
            for (var opt in $.gritter.options)
            {
                this[opt] = $.gritter.options[opt];
            }
            this._is_setup = 1;

        },

        /**
         * Set the notification to fade out after a certain amount of time
         * @private
         * @param e The HTML element we're dealing with
         * @param unique_id The ID of the element
         */
        _setFadeTimer: function(e, unique_id)
        {
            var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
            this['_int_id_' + unique_id] = setTimeout(function()
            {
                Gritter._fade(e, unique_id);
            }, timer_str);
        },

        /**
         * Bring everything to a halt
         * @param {Object} params A list of callback functions to pass when all notifications are removed
         */
        stop: function(params)
        {
            // callbacks (if passed)
            var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
            var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};

            var wrap = $('#gritter-notice-wrapper');
            before_close(wrap);
            wrap.fadeOut(function()
            {
                $(this).remove();
                after_close();
            });
        },

        /**
         * Get notice wrapper
         * @return e The notice wrapper element.
         */
        noticeWrapper: function()
        {
            return $('#gritter-notice-wrapper');
        },

        /**
         * An extremely handy PHP function ported to JS, works well for templating
         * @private
         * @param {String/Array} search A list of things to search for
         * @param {String/Array} replace A list of things to replace the searches with
         * @return {String} sa The output
         */
        _str_replace: function(search, replace, subject, count)
        {
            var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
                f = [].concat(search),
                r = [].concat(replace),
                s = subject,
                ra = r instanceof Array, sa = s instanceof Array;
            s = [].concat(s);

            if (count)
            {
                this.window[count] = 0;
            }

            for (i = 0, sl = s.length; i < sl; i++)
            {
                if (s[i] === '')
                {
                    continue;
                }

                for (j = 0, fl = f.length; j < fl; j++)
                {
                    temp = s[i] + '';
                    repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
                    s[i] = (temp).split(f[j]).join(repl);

                    if (count && s[i] !== temp)
                    {
                        this.window[count] += (temp.length-s[i].length) / f[j].length;
                    }
                }
            }

            return sa ? s : s[0];
        },

        /**
         * A check to make sure we have something to wrap our notices with
         * @private
         */
        _verifyWrapper: function()
        {
            if ($('#gritter-notice-wrapper').length == 0)
            {
                $('body').append(this._tpl_wrap);
            }
        }
    }
})(jQuery);<commit_msg>Gritter would not scroll with large text when draggable.<commit_after>/*
 * Gritter for jQuery
 * http://www.boedesign.com/
 *
 * Copyright (c) 2012 Jordan Boesch
 * Dual licensed under the MIT and GPL licenses.
 *
 * Date: February 24, 2012
 * Version: 1.7.4
 */

(function($){
    /**
     * Set it up as an object under the jQuery namespace
     */
    $.gritter = {};
    var Gritter;

    /**
     * Set up global options that the user can over-ride
     */
    $.gritter.options = {
        position: '',
        class_name: '', // set on the gritter-item
        fade_in_speed: 'medium', // how fast notifications fade in
        fade_out_speed: 800, // how fast the notices fade out
        append: true,
        time: 6000 // hang on the screen for...
    };

    /**
     * Add a gritter notification to the screen
     * @see Gritter#add();
     */
    $.gritter.add = function(params)
    {
        try
        {
            return Gritter.add(params || {});
        }
        catch(e)
        {
            var err = 'Gritter Error: ' + e;
            (typeof(console) != 'undefined' && console.error) ?
                console.error(err, params) :
                alert(err);
        }
    };

    /**
     * Remove a gritter notification from the screen
     * @see Gritter#removeSpecific();
     */
    $.gritter.remove = function(id, params)
    {
        Gritter.removeSpecific(id, params || {});
    };

    /**
     * Remove all notifications
     * @see Gritter#stop();
     */
    $.gritter.removeAll = function(params)
    {
        Gritter.stop(params || {});
    };

    /**
     * Get notice wrapper
     * @see Gritter#noticeWrapper();
     */
    $.gritter.noticeWrapper = function()
    {
        return Gritter.noticeWrapper();
    };

    /**
     * @constructor
     */
    Gritter = {

        // Public - options to over-ride with $.gritter.options in "add"
        position: '',
        fade_in_speed: '',
        fade_out_speed: '',
        time: '',

        // Private - no touchy the private parts
        _custom_timer: 0,
        _item_count: 0,
        _is_setup: 0,
        _tpl_close: 'Close Notification',
        _tpl_drag: 'Enable Drag',
        _tpl_title: '[[title]]',
        _tpl_item: '

[[drag]][[close]][[image]][[title]][[text]]

',
        _tpl_wrap: '

',

        /**
         * Add a gritter notification to the screen
         * @param {Object} params The object that contains all the options for drawing the notification
         * @return {int} The specific numeric id to that gritter notification
         */
        add: function(params)
        {
            // Handle straight text
            if (typeof(params) == 'string')
            {
                params = {text:params};
            }

            // We might have some issues if we don't have a title or text!
            if (params.text === null)
            {
                throw 'You must supply "text" parameter.';
            }

            // Check the options and set them once
            if (!this._is_setup)
            {
                this._runSetup();
            }

            // Basics
            var title = params.title,
                text = params.text,
                append = params.append,
                image = params.image || '',
                sticky = params.sticky || false,
                item_class = params.class_name || $.gritter.options.class_name,
                position = $.gritter.options.position,
                time_alive = params.time || '';

            this._verifyWrapper();
            this._item_count++;
            var number = this._item_count, tmp = this._tpl_item;

            // Assign callbacks
            $(['before_open', 'after_open', 'before_close', 'after_close']).each(function(i, val)
            {
                Gritter['_' + val + '_' + number] = ($.isFunction(params[val])) ? params[val] : function(){}
            });

            // Reset
            this._custom_timer = 0;

            // A custom fade time set
            if (time_alive)
            {
                this._custom_timer = time_alive;
            }

            var image_str = (image != '') ? '' : '';

            // String replacements on the template
            title = title ? this._str_replace('[[title]]', title, this._tpl_title) : '';

            tmp = this._str_replace(
                ['[[title]]', '[[text]]', '[[drag]]', '[[close]]', '[[image]]', '[[number]]', '[[class_name]]', '[[item_class]]'],
                [title, text, this._tpl_drag, this._tpl_close, image_str, this._item_count, '', item_class], tmp
            );

            var popup = $('#gritter-notice-wrapper').addClass(position);
            if (append)
            {
                popup.append(tmp);
            }
            else
            {
                popup.prepend(tmp);
            }
            var item = $('#gritter-item-' + this._item_count);

            item.fadeIn(this.fade_in_speed, function()
            {
                Gritter['_after_open_' + number]($(this));
            });

            if (!sticky)
            {
                this._setFadeTimer(item, number);
            }

            // Bind the hover/unhover states
            $(item).bind('mouseenter mouseleave', function(event)
            {
                if (event.type == 'mouseenter')
                {
                    if (!sticky)
                    {
                        Gritter._restoreItemIfFading($(this), number);
                    }
                }
                else
                {
                    if (!sticky)
                    {
                        Gritter._setFadeTimer($(this), number);
                    }
                }
                Gritter._hoverState($(this), event.type);
            });

            // Clicking (X) makes it close
            $(item).find('.gritter-close').click(function()
            {
                Gritter.removeSpecific(number, {}, null, true);
                return false;
            });

            item.draggable({
                containment: 'body',
                stack: '#gritter-notice-wrapper div'
            });
            item.draggable('disable');
            $(item).find('.gritter-drag').on('click', function() {
                var offset, width;
                if (item.parent().is('body')) {
                    item.detach();
                    $('#gritter-notice-wrapper').append(item);
                    item.css({position:'', top:'', left:'', width:'', 'overflow-y':'', 'max-height':''});
                    item.draggable('disable');
                } else {
                    offset = item.offset();
                    width = item.width();
                    item.detach();
                    $('body').append(item);
                    item.css({
                        position: 'absolute',
                        top: offset.top,
                        left: offset.left,
                        width: width,
                        'overflow-y': 'auto',
                        'max-height': 450
                    });
                    item.draggable('enable');
                }
            });

            return number;

        },

        /**
         * If we don't have any more gritter notifications, get rid of the wrapper using this check
         * @private
         * @param {int} unique_id The ID of the element that was just deleted, use it for a callback
         * @param {Object} e The jQuery element that we're going to perform the remove() action on
         * @param {Boolean} manual_close Did we close the gritter dialog with the (X) button
         */
        _countRemoveWrapper: function(unique_id, e, manual_close)
        {
            // Remove it then run the callback function
            e.remove();
            this['_after_close_' + unique_id](e, manual_close);

            // Check if the wrapper is empty, if it is.. remove the wrapper
            if (!$('.gritter-item-wrapper').length)
            {
                $('#gritter-notice-wrapper').remove();
            }

        },

        /**
         * Fade out an element after it's been on the screen for x amount of time
         * @private
         * @param {Object} e The jQuery element to get rid of
         * @param {int} unique_id The id of the element to remove
         * @param {Object} params An optional list of params to set fade speeds etc.
         * @param {Boolean} unbind_events Unbind the mouseenter/mouseleave events if they click (X)
         */
        _fade: function(e, unique_id, params, unbind_events)
        {
            var params = params || {},
                fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
                fade_out_speed = params.speed || this.fade_out_speed,
                manual_close = unbind_events;

            this['_before_close_' + unique_id](e, manual_close);

            // If this is true, then we are coming from clicking the (X)
            if (unbind_events)
            {
                e.unbind('mouseenter mouseleave');
            }

            // Fade it out or remove it
            if (fade)
            {
                e.animate({
                    opacity: 0
                }, fade_out_speed, function()
                {
                    e.animate({ height: 0 }, 300, function()
                    {
                        Gritter._countRemoveWrapper(unique_id, e, manual_close);
                    })
                })
            }
            else
            {
                this._countRemoveWrapper(unique_id, e);
            }
        },

        /**
         * Perform actions based on the type of bind (mouseenter, mouseleave)
         * @private
         * @param {Object} e The jQuery element
         * @param {String} type The type of action we're performing: mouseenter or mouseleave
         */
        _hoverState: function(e, type)
        {
            // Change the border styles and add the (X) close button when you hover
            if (type == 'mouseenter')
            {
                e.addClass('hover');

                // Show close button
                e.find('.gritter-close, .gritter-drag').show();

            }
            // Remove the border styles and hide (X) close button when you mouse out
            else
            {
                e.removeClass('hover');

                // Hide close button
                e.find('.gritter-close, .gritter-drag').hide();
            }
        },

        /**
         * Remove a specific notification based on an ID
         * @param {Integer} unique_id The ID used to delete a specific notification
         * @param {Object} params A set of options passed in to determine how to get rid of it
         * @param {Object} e The jQuery element that we're "fading" then removing
         * @param {Boolean} unbind_events If we clicked on the (X) we set this to true to unbind mouseenter/mouseleave
         */
        removeSpecific: function(unique_id, params, e, unbind_events)
        {
            if (!e)
            {
                e = $('#gritter-item-' + unique_id);
            }

            // We set the fourth param to let the _fade function know to
            // unbind the "mouseleave" event.  Once you click (X) there's no going back!
            this._fade(e, unique_id, params || {}, unbind_events);
        },

        /**
         * If the item is fading out and we hover over it, restore it!
         * @private
         * @param e The HTML element to remove
         * @param unique_id The ID of the element
         */
        _restoreItemIfFading: function(e, unique_id)
        {
            clearTimeout(this['_int_id_' + unique_id]);
            e.stop().css({ opacity: '', height: '' });

        },

        /**
         * Setup the global options - only once
         * @private
         */
        _runSetup: function()
        {
            for (var opt in $.gritter.options)
            {
                this[opt] = $.gritter.options[opt];
            }
            this._is_setup = 1;

        },

        /**
         * Set the notification to fade out after a certain amount of time
         * @private
         * @param e The HTML element we're dealing with
         * @param unique_id The ID of the element
         */
        _setFadeTimer: function(e, unique_id)
        {
            var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
            this['_int_id_' + unique_id] = setTimeout(function()
            {
                Gritter._fade(e, unique_id);
            }, timer_str);
        },

        /**
         * Bring everything to a halt
         * @param {Object} params A list of callback functions to pass when all notifications are removed
         */
        stop: function(params)
        {
            // callbacks (if passed)
            var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
            var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};

            var wrap = $('#gritter-notice-wrapper');
            before_close(wrap);
            wrap.fadeOut(function()
            {
                $(this).remove();
                after_close();
            });
        },

        /**
         * Get notice wrapper
         * @return e The notice wrapper element.
         */
        noticeWrapper: function()
        {
            return $('#gritter-notice-wrapper');
        },

        /**
         * An extremely handy PHP function ported to JS, works well for templating
         * @private
         * @param {String/Array} search A list of things to search for
         * @param {String/Array} replace A list of things to replace the searches with
         * @return {String} sa The output
         */
        _str_replace: function(search, replace, subject, count)
        {
            var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
                f = [].concat(search),
                r = [].concat(replace),
                s = subject,
                ra = r instanceof Array, sa = s instanceof Array;
            s = [].concat(s);

            if (count)
            {
                this.window[count] = 0;
            }

            for (i = 0, sl = s.length; i < sl; i++)
            {
                if (s[i] === '')
                {
                    continue;
                }

                for (j = 0, fl = f.length; j < fl; j++)
                {
                    temp = s[i] + '';
                    repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
                    s[i] = (temp).split(f[j]).join(repl);

                    if (count && s[i] !== temp)
                    {
                        this.window[count] += (temp.length-s[i].length) / f[j].length;
                    }
                }
            }

            return sa ? s : s[0];
        },

        /**
         * A check to make sure we have something to wrap our notices with
         * @private
         */
        _verifyWrapper: function()
        {
            if ($('#gritter-notice-wrapper').length == 0)
            {
                $('body').append(this._tpl_wrap);
            }
        }
    }
})(jQuery);<|endoftext|>


<commit_before>/**
 * This file is dependent on gulp which automate tasks.
 *Author : Collins
 */

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload'),
    cleanCSS = require('gulp-clean-css'),
    jshint = require('gulp-jshint'),
    livereload = require('gulp-livereload');

var browserSync1 = require("browser-sync").create();
var browserSync2 = require("browser-sync").create();
var browserSync = require("browser-sync");

gulp.task("default", ["front","test"]);

gulp.task('css', function() {
  gulp.src('public/design/css/*.css')
    .pipe(cleanCSS())
    .pipe(gulp.dest('css'))
    .pipe(livereload(".public/index.html"));
});

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch('public/design/css/*.css', ['css']);
});

// A task that ensures the javascript task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('front', function () {

    browserSync1.init({
        server : {
            baseDir: "./public"
        },
        port : 3001,
        ui: {
            port:3070
        }
    });
    // tracks html,js and css changes
    gulp.watch("./public/**/*.{html,js,css}").on("change", browserSync1.reload);
});

gulp.task("test", function () {

    browserSync2.init({
        server: {
          baseDir: ["./public/src/", "./jasmine"],
          port: 3080,
          ui: {
              port: 3090
          }
      }
    });

    gulp.watch('./jasmine/spec/*.js').on("change",browserSync2.reload);
    gulp.watch("./public/src/*.js").on("change", browserSync2.reload);
}); <commit_msg>Modified the contents of variable browserSync<commit_after>/**
 * This file is dependent on gulp which automate tasks.
 *Author : Collins
 */

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload'),
    cleanCSS = require('gulp-clean-css'),
    jshint = require('gulp-jshint'),
    livereload = require('gulp-livereload');

var browserSync1 = require("browser-sync").create();
var browserSync2 = require("browser-sync").create();
var browserSync = require("browser-sync").create();

gulp.task("default", ["front","test"]);

gulp.task('css', function() {
  gulp.src('public/design/css/*.css')
    .pipe(cleanCSS())
    .pipe(gulp.dest('css'))
    .pipe(livereload(".public/index.html"));
});

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch('public/design/css/*.css', ['css']);
});

// A task that ensures the javascript task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('front', function () {

    browserSync1.init({
        server : {
            baseDir: "./public"
        },
        port : 3001,
        ui: {
            port:3070
        }
    });
    // tracks html,js and css changes
    gulp.watch("./public/**/*.{html,js,css}").on("change", browserSync1.reload);
});

gulp.task("test", function () {

    browserSync2.init({
        server: {
          baseDir: ["./public/src/", "./jasmine"],
          port: 3080,
          ui: {
              port: 3090
          }
      }
    });

    gulp.watch('./jasmine/spec/*.js').on("change",browserSync2.reload);
    gulp.watch("./public/src/*.js").on("change", browserSync2.reload);
}); <|endoftext|>


<commit_before>var $ = require('jquery')
var ajax = require('./ajax.js')

	function appendPosts() {
		ajax.postFromServer(appendCallback)
	}

	function appendCallback (err, res) {
		var parsedData = JSON.parse(res.text)
		var posts = parsedData.post
		posts.forEach(function (post) {
		$('.blog').append('

' + post.title + '

' + post.datestamp + '

' + post.postcontent + '

')
		})
	}

  function addPostToDatabase (newPost) {
    ajax.postFromServer(function(err, res) {
      if (err) { console.log('ERROR: reading while trying to write post'); return }
      var parsedData = JSON.parse(res.text)
      parsedData.post.push(newPost)
      var objectToPost = JSON.stringify(parsedData)
      ajax.postToServer(objectToPost, refreshPosts)

    })
  }

  function refreshPosts () {
  	console.log('I should refresh!')
    $('.blog').empty()
    $('#title').val("")
    $('#postcontent').val("")

    appendPosts()
  }

// function listen() {
//   $('#save').click(() => {
//   	console.log("listening")
//     formatObjectToSend()
//   })
// }

document.getElementById("save").addEventListener("click", formatObjectToSend);

function formatObjectToSend(){
	var title = $('#title').val()
  var postcontent = $('#postcontent').val()
  var datestamp = new Date();
  var object =  {
		"title": title,
		"postcontent": postcontent,
		"datestamp": datestamp
	}
	console.log("object", object)
	addPostToDatabase(object)
}

	appendPosts()<commit_msg>Minor cleanups<commit_after>var $ = require('jquery')
var ajax = require('./ajax.js')

	function appendPosts() {
		ajax.postFromServer(appendCallback)
	}

	function appendCallback (err, res) {
		var parsedData = JSON.parse(res.text)
		var posts = parsedData.post
		posts.forEach(function (post) {
		$('.blog').append('

' + post.title + '

' + post.datestamp + '

' + post.postcontent + '

')
		})
	}

  function addPostToDatabase (newPost) {
    ajax.postFromServer(function(err, res) {
      if (err) { console.log('ERROR: reading while trying to write post'); return }
      var parsedData = JSON.parse(res.text)
      parsedData.post.push(newPost)
      var objectToPost = JSON.stringify(parsedData)
      ajax.postToServer(objectToPost, refreshPosts)

    })
  }

  function refreshPosts () {
    $('.blog').empty()
    $('#title').val("")
    $('#postcontent').val("")

    appendPosts()
  }

document.getElementById("save").addEventListener("click", formatObjectToSend);

function formatObjectToSend(){
  var title = $('#title').val()
  var postcontent = $('#postcontent').val()
  var datestamp = new Date();
  var object =  {
		"title": title,
		"postcontent": postcontent,
		"datestamp": datestamp
	}
	addPostToDatabase(object)
}

	appendPosts()<|endoftext|>


<commit_before>import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import SubmissionTitle from '../submission-title';

const submission = {
  lesson_path: 'test_path',
  lesson_title: 'Test Title',
  user_name: 'TestUser',
};

describe('Dashboard view true', () => {
  it('shows the lesson title in dashboard view', () => {
    render(<SubmissionTitle submission={submission} isDashboardView={true} />);
    expect(screen.getByText('Test Title')).toBeInTheDocument();
  });
  it('has a link to the project in dashboard view', () => {
    render(<SubmissionTitle submission={submission} isDashboardView={true} />);
    expect(screen.getByText('Test Title')).toHaveAttribute('href', 'test_path');
  });
});

describe('Dashboard view false', () => {
  it('returns username if not in dashboard mode', () => {
    render(<SubmissionTitle submission={submission} />);
    expect(screen.getByText('TestUser')).toBeInTheDocument();
  });
});
<commit_msg>Fixed imperative verbs, multi-lined components with multiple props passed<commit_after>import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import SubmissionTitle from '../submission-title';

const submission = {
  lesson_path: 'test_path',
  lesson_title: 'Test Title',
  user_name: 'TestUser',
};

describe('Submission title', () => {
  it('displays the lesson title in dashboard view', () => {
    render(<SubmissionTitle
    submission={submission}
    isDashboardView={true} />);
    expect(screen.getByText('Test Title')).toBeInTheDocument();
  });
  it('displays a link to the project in dashboard view', () => {
    render(<SubmissionTitle
      submission={submission}
      isDashboardView={true} />);
    expect(screen.getByText('Test Title')).toHaveAttribute('href', 'test_path');
  });
  it('displays username if not in dashboard mode', () => {
    render(<SubmissionTitle submission={submission} />);
    expect(screen.getByText('TestUser')).toBeInTheDocument();
  });
});
<|endoftext|>


<commit_before>var cloak = require('cloak');
var _ = require('underscore');

cloak.configure({
  port: 8090,
  roomLife: 1000*60*60*3,

  autoJoinLobby: false,
  minRoomMembers: 1,
  pruneEmptyRooms: 1000,
  reconnectWait: 0,

  messages: {
    registerUsername: function(arg, user) {
      var users = cloak.getUsers();
      var username = arg.username;
      var usernames = _.pluck(users, 'name');
      var success = false;
      console.log(users);
      console.log(usernames);
      if (_.indexOf(usernames, username) === -1) {
        success = true;
        user.name = username;
        user.message('registerUsernameResponse', [success, username]);
      }else{
        //resume so add back to the lobby
        var successadd = cloak.getLobby().addMember(user);
        user.message('joinLobbyResponse', successadd);
        if(successadd)
          cloak.messageAll('refreshAll');
      }
    },

    joinLobby: function(arg, user) {
      var success = cloak.getLobby().addMember(user);
      user.message('joinLobbyResponse', success);
      if(success)
        cloak.messageAll('refreshAll');
    },

    listUsers: function(arg, user){
    	user.message('refreshLobby', {
        users: user.room.getMembers(true),
        inLobby: user.room.isLobby,
        roomCount: user.room.getMembers().length,
        roomSize: user.room.size
      });
    },

    listRooms: function(arg, user){
      user.message('refreshRooms', cloak.getRooms(true));
    },

    createRoom: function(arg, user) {
      var room = cloak.createRoom(arg.name, 2);
      var success = room.addMember(user);
      user.message('roomCreated', {
        success: success,
        roomId: room.id
      });
      cloak.messageAll('refreshAll');
    },

    joinRoom: function(id, user) {
      var room = cloak.getRoom(id)
      if (room.getMembers().length < 2)
      {
        room.addMember(user);
        user.message('joinRoomResponse', {
          id: id,
          success: true
        });
      } else {
        user.message('joinRoomResponse', {
          id: id,
          success: false
        });
      }

    },

    leaveRoom: function(arg, user) {
      user.leaveRoom();
    },

    disconnectUser: function(arg,user){
      user.delete();
    },

    chat: function(msg, user) {
      user.getRoom().messageMembers('chat', [msg, user.name]);
    },

    refreshRoom: function(arg, user) {
      user.message('refreshRoomResponse', user.room.getMembers(true));
    },

    turnDone: function(move, user){
      //move[0] is from and move[1] is to
      // If it's currently the turn of the user and they say they're done, advance the turn
      if (user.team === user.room.turn) {
        user.room.turn = (user.room.turn === 'muon') ? 'antimuon' : 'muon';
      }
      // let the other player know
      var otherPlayer = _.reject(user.room.members, function(member) {
        return member.id === user.id;
      });
      console.log("sending move to player:", otherPlayer[0]);
      user.room.lastMove = {from: move[0], to: move[1]};
      otherPlayer[0].message('performOpponentMove', [move[0],move[1]]);

      user.room.messageMembers('turn', user.room.turn);

    },
    proposeDraw: function(arg, user){
      user.room.messageMembers('proposeDrawResponse', [user.name]);
    },
    respondToDraw: function(accept, user){
      user.room.messageMembers('respondToDrawResponse', [accept]);
    },
    proposeRematch: function(arg, user){
      user.room.messageMembers('proposeRematchResponse', [user.name]);
    },
    respondToRematch: function(accept, user){
      user.room.messageMembers('respondToRematchResponse', [accept]);
    }
  },

  room: {
    init: function() {
      this.turn = 'muon';
      this.lastMove = {};

      this.teams = {
        muon: '',
        antimuon: ''
      };

      console.log('created room ' + this.id);
      this.data.lastReportedAge = 0;
    },

    newMember: function(user) {
      if (this.teams.muon === '') { //host
        this.teams.muon = user.id;
        user.team = 'muon';
        user.message('userMessage', 'your are muons and your id is ' + user.id);
      }
      else if (this.teams.antimuon === '') { //client
        this.teams.antimuon = user.id;
        user.team = 'antimuon';
        user.message('userMessage', 'your team is antimuons and your id is ' + user.id);
      }
      else {
        var msg = 'Um, we tried to assign a team member but all teams were taken for this room.';
        console.log(msg);
        user.team = 'none';
        user.message('userMessage', msg);
      }
      user.message('assignTeam', {
        team: user.team,
        turn: this.turn
      });
    },

    memberLeaves: function(user) {
      // if we have 0 people in the room, close the room
      if (this.getMembers().length <= 0) {
        this.delete();
      }
    },

    pulse: function() {
      // add timed turn stuff here
    },

    close: function() {
      this.messageMembers('you have left ' + this.name);
    }

  }

});

cloak.run();
<commit_msg>fixed reconnect wait, added timer.<commit_after>var cloak = require('cloak');
var _ = require('underscore');

cloak.configure({
  port: 8090,
  roomLife: 1000*60*60*3,

  autoJoinLobby: false,
  minRoomMembers: 1,
  pruneEmptyRooms: 1000,

  messages: {
    registerUsername: function(arg, user) {
      var users = cloak.getUsers();
      var username = arg.username;
      var usernames = _.pluck(users, 'name');
      var success = false;
      console.log(users);
      console.log(usernames);
      if (_.indexOf(usernames, username) === -1) {
        success = true;
        user.name = username;
        user.message('registerUsernameResponse', [success, username]);
      }else{
        //resume so add back to the lobby
        var successadd = cloak.getLobby().addMember(user);
        user.message('joinLobbyResponse', successadd);
        if(successadd)
          cloak.messageAll('refreshAll');
      }
    },

    joinLobby: function(arg, user) {
      var success = cloak.getLobby().addMember(user);
      user.message('joinLobbyResponse', success);
      if(success)
        cloak.messageAll('refreshAll');
    },

    listUsers: function(arg, user){
    	user.message('refreshLobby', {
        users: user.room.getMembers(true),
        inLobby: user.room.isLobby,
        roomCount: user.room.getMembers().length,
        roomSize: user.room.size
      });
    },

    listRooms: function(arg, user){
      user.message('refreshRooms', cloak.getRooms(true));
    },

    createRoom: function(arg, user) {
      var room = cloak.createRoom(arg.name, 2);
      var success = room.addMember(user);
      user.message('roomCreated', {
        success: success,
        roomId: room.id
      });
      cloak.messageAll('refreshAll');
    },

    joinRoom: function(id, user) {
      var room = cloak.getRoom(id)
      var memCount = room.getMembers().length;
      if (memCount < 2)
      {
        room.addMember(user);
        user.message('joinRoomResponse', {
          id: id,
          success: true
        });
        if(memCount == 2){
          //start the timer.
          room.timer.start()
        }

        room.timer.sync(user);
      } else {
        user.message('joinRoomResponse', {
          id: id,
          success: false
        });
      }

    },

    leaveRoom: function(arg, user) {
      user.leaveRoom();
    },

    disconnectUser: function(arg,user){
      user.delete();
    },

    chat: function(msg, user) {
      user.getRoom().messageMembers('chat', [msg, user.name]);
    },

    refreshRoom: function(arg, user) {
      user.message('refreshRoomResponse', user.room.getMembers(true));
    },

    turnDone: function(move, user){
      //move[0] is from and move[1] is to
      // If it's currently the turn of the user and they say they're done, advance the turn
      if (user.team === user.room.turn) {
        user.room.turn = (user.room.turn === 'muon') ? 'antimuon' : 'muon';
      }
      // let the other player know
      var otherPlayer = _.reject(user.room.members, function(member) {
        return member.id === user.id;
      });
      console.log("sending move to player:", otherPlayer[0]);
      user.room.lastMove = {from: move[0], to: move[1]};
      otherPlayer[0].message('performOpponentMove', [move[0],move[1]]);

      user.room.messageMembers('turn', user.room.turn);

    },
    proposeDraw: function(arg, user){
      user.room.messageMembers('proposeDrawResponse', [user.name]);
    },
    respondToDraw: function(accept, user){
      user.room.messageMembers('respondToDrawResponse', [accept]);
    },
    proposeRematch: function(arg, user){
      user.room.messageMembers('proposeRematchResponse', [user.name]);
    },
    respondToRematch: function(accept, user){
      user.room.messageMembers('respondToRematchResponse', [accept]);
    }
  },

  room: {
    init: function() {
      this.turn = 'muon';
      this.lastMove = {};
      this.timer = cloak.createTimer('timer' + this.id);

      this.teams = {
        muon: '',
        antimuon: ''
      };

      console.log('created room ' + this.id);
      this.data.lastReportedAge = 0;
    },

    newMember: function(user) {
      if (this.teams.muon === '') { //host
        this.teams.muon = user.id;
        user.team = 'muon';
        user.message('userMessage', 'your are muons and your id is ' + user.id);
      }
      else if (this.teams.antimuon === '') { //client
        this.teams.antimuon = user.id;
        user.team = 'antimuon';
        user.message('userMessage', 'your team is antimuons and your id is ' + user.id);
      }
      else {
        var msg = 'Um, we tried to assign a team member but all teams were taken for this room.';
        console.log(msg);
        user.team = 'none';
        user.message('userMessage', msg);
      }
      user.message('assignTeam', {
        team: user.team,
        turn: this.turn
      });
    },

    memberLeaves: function(user) {
      // if we have 0 people in the room, close the room
      if (this.getMembers().length <= 0) {
        this.delete();
      }
    },

    pulse: function() {
      // add timed turn stuff here
    },

    close: function() {
      this.messageMembers('you have left ' + this.name);
    }

  }

});

cloak.run();
<|endoftext|>


<commit_before>/* jshint undef: false */

(function($, pt) {

   if (typeof configureLinksInMessage === 'function') {
      var configureLinksInMessageOld = configureLinksInMessage;

      configureLinksInMessage = function() {
         configureLinksInMessageOld();

         if (jsxc.restoreCompleted) {
            jsxc.gui.detectEmail($('div#messageContent'));
            jsxc.gui.detectUriScheme($('div#messageContent'));
         }
      };
   }

   if (typeof loadContact === 'function') {
      var loadContactOld = loadContact;

      loadContact = function(idx) {
         var available = typeof cachedContacts[Contact.currentAddressBook + "/" + idx] !== 'undefined';
         loadContactOld(idx);

         if (available && jsxc.restoreCompleted) {
            jsxc.gui.detectEmail($('div#contactView'));
         }
      };

      var contactLoadCallbackOld = contactLoadCallback;

      contactLoadCallback = function(http) {
         contactLoadCallbackOld(http);

         if (http.readyState === 4 && http.status === 200 && jsxc.restoreCompleted) {
            jsxc.gui.detectEmail($('div#contactView'));
         }
      };
   }

   function onRosterToggle(event, state, duration) {
      var wrapper = $('#rightPanel');
      var control = $('#toolbar');
      var roster_width = (state === 'shown') ? $('#jsxc_roster').outerWidth() : 0;

      wrapper.animate({
         marginRight: (roster_width) + 'px'
      }, duration);

      control.animate({
         marginRight: (roster_width) + 'px'
      }, duration, 'swing', function() {
         if (typeof SOGoResizableTableInterface !== 'undefined') {
            SOGoResizableTableInterface.resize.call(pt('messageListHeader'));
         }
      });
   }

   function onRosterReady() {

      var roster_right = parseFloat($('#jsxc_roster').css('right'));
      var mr = (204 + ($.isNumeric(roster_right) ? roster_right : 0));

      $('#toolbar').css('marginRight', mr + 'px');
      $('#rightPanel').css('marginRight', mr + 'px');

      if (typeof SOGoResizableTableInterface !== 'undefined') {
         SOGoResizableTableInterface.resize.call(pt('messageListHeader'));
      }
   }

   function lazyLoadCss(val) {
      var files = ($.isArray(val)) ? val : [ val ];

      var f = null;
      for (f in files) {
         if (files.hasOwnProperty(f)) {
            $("head").append($("<link rel='stylesheet' href='/SOGo.woa/WebServerResources/sjsxc/css/" + files[f] + ".css' type='text/css' media='screen' />"));
         }
      }
   }

   lazyLoadCss([ 'jquery-ui.min', 'jquery.colorbox', 'jsxc.sogo' ]);

   function addOption() {
      $('
Chat Options
').attr('target', 'chatView').appendTo('#preferencesTabs ul:first');

      var tab = $('
').addClass('tab').attr('id', 'chatView');
      tab.appendTo('#preferencesTabs .tabs:first');

      tab.append('<input type="checkbox"/> Enable chat
Change will take effect on next login.
This information is stored per browser.
');
      var checkbox = tab.find('input');

      checkbox[0].checked = sjsxc.config.enable;
      checkbox.change(function() {
         localStorage.setItem('sjsxc.enable', this.checked);
      });

      initPreferences();
   }

   var sjsxc_start = function() {

      if ($('#linkBanner').length === 0) {
         return;
      }

      $(document).on('ready.roster.jsxc', onRosterReady);
      $(document).on('toggle.roster.jsxc', onRosterToggle);

      if (jsxc.storage.getItem("abort")) {
         return;
      }

      jsxc.init($.extend({
         app_name: 'SOGo',
         loginForm: {
            form: '#connectForm',
            jid: '#userName',
            pass: '#password'
         },
         logoutElement: $('#logoff'),
         checkFlash: false,
         rosterAppend: 'body',
         root: ResourcesURL + '/sjsxc/js/jsxc',
         turnCredentialsPath: '/SOGo.woa/WebServerResources/sjsxc/ajax/getturncredentials.php',
         formFound: function() {
            var submit = pt("submit");
            submit.stopObserving("click", onLoginClick);

            var userName = pt("userName");
            userName.stopObserving("keydown", onFieldKeyDown);

            var passw = pt("password");
            passw.stopObserving("keydown", onFieldKeyDown);

            $('#connectForm').submit(onLoginClick);
            $('#submit').click(function() {
               $('#connectForm').submit();
            });
            $('#userName, #password').keypress(function(ev) {
               if (ev.which !== 13) {
                  return;
               }

               $('#connectForm').submit();
            });
         },
         loadSettings: function() {
            return sjsxc.config;
         },
         displayRosterMinimized: function() {
             return $('#logoff').length > 0;
         }
      }, sjsxc.config.jsxc || {}));

      // Add submit link without chat functionality
      if (jsxc.el_exists($('#loginCell'))) {

         var link = $('').text($.t('Log_in_without_chat')).click(function() {
            jsxc.submitLoginForm();
         });

         var alt = $('
').append(link);
         $('#loginCell').append('
').append(alt);
      }
   };

   var sjsxc_init = function() {
      if ($('#jsxc_sogo_test').css('background-color') !== '' && $('#jsxc_sogo_test').css('position') === 'absolute') {
         $('#jsxc_sogo_test').remove();
         sjsxc_start();
      } else {
         setTimeout(sjsxc_init, 50);
      }
   };

   $(function() {

      if (typeof sjsxc === 'undefined' || typeof sjsxc.config === 'undefined') {
         console.error('No config for sjsxc found! Look at sjsxc.config.sample.js.');
         return;
      }

      $.extend(true, sjsxc.config, sjsxc.config[document.domain] || {});

      var el = $('
').attr('class', 'jsxc_window').attr('id', 'jsxc_sogo_test');
      $('body').append(el);

      var enable = JSON.parse(localStorage.getItem('sjsxc.enable'));
      sjsxc.config.enable = (typeof enable === 'undefined' || enable === null) ? sjsxc.config.enable : enable;

      if (window.location.pathname.match(/\/preferences$/)) {
         addOption();
         return;
      }

      if (sjsxc.config.enable === true) {
         setTimeout(sjsxc_init, 20);
      }
   });

})(jQuery, $);
<commit_msg>fix preferences (fix jsxc/jsxc#168)<commit_after>/* jshint undef: false */

(function($, pt) {

   if (typeof configureLinksInMessage === 'function') {
      var configureLinksInMessageOld = configureLinksInMessage;

      configureLinksInMessage = function() {
         configureLinksInMessageOld();

         if (jsxc.restoreCompleted) {
            jsxc.gui.detectEmail($('div#messageContent'));
            jsxc.gui.detectUriScheme($('div#messageContent'));
         }
      };
   }

   if (typeof loadContact === 'function') {
      var loadContactOld = loadContact;

      loadContact = function(idx) {
         var available = typeof cachedContacts[Contact.currentAddressBook + "/" + idx] !== 'undefined';
         loadContactOld(idx);

         if (available && jsxc.restoreCompleted) {
            jsxc.gui.detectEmail($('div#contactView'));
         }
      };

      var contactLoadCallbackOld = contactLoadCallback;

      contactLoadCallback = function(http) {
         contactLoadCallbackOld(http);

         if (http.readyState === 4 && http.status === 200 && jsxc.restoreCompleted) {
            jsxc.gui.detectEmail($('div#contactView'));
         }
      };
   }

   function onRosterToggle(event, state, duration) {
      var wrapper = $('#rightPanel');
      var control = $('#toolbar');
      var roster_width = (state === 'shown') ? $('#jsxc_roster').outerWidth() : 0;

      wrapper.animate({
         marginRight: (roster_width) + 'px'
      }, duration);

      control.animate({
         marginRight: (roster_width) + 'px'
      }, duration, 'swing', function() {
         if (typeof SOGoResizableTableInterface !== 'undefined') {
            SOGoResizableTableInterface.resize.call(pt('messageListHeader'));
         }
      });
   }

   function onRosterReady() {

      var roster_right = parseFloat($('#jsxc_roster').css('right'));
      var mr = (204 + ($.isNumeric(roster_right) ? roster_right : 0));

      $('#toolbar').css('marginRight', mr + 'px');
      $('#rightPanel').css('marginRight', mr + 'px');

      if (typeof SOGoResizableTableInterface !== 'undefined') {
         SOGoResizableTableInterface.resize.call(pt('messageListHeader'));
      }
   }

   function lazyLoadCss(val) {
      var files = ($.isArray(val)) ? val : [ val ];

      var f = null;
      for (f in files) {
         if (files.hasOwnProperty(f)) {
            $("head").append($("<link rel='stylesheet' href='/SOGo.woa/WebServerResources/sjsxc/css/" + files[f] + ".css' type='text/css' media='screen' />"));
         }
      }
   }

   lazyLoadCss([ 'jquery-ui.min', 'jquery.colorbox', 'jsxc.sogo' ]);

   function addOption() {
      $('
Chat Options
').attr('target', 'chatView').appendTo('#preferencesTabs ul:first');

      var tab = $('
').addClass('tab').attr('id', 'chatView');
      tab.appendTo('#preferencesTabs .tabs:first');

      tab.append('<input type="checkbox"/> Enable chat
Change will take effect on next login.
This information is stored per browser.
');
      var checkbox = tab.find('input');

      checkbox[0].checked = sjsxc.config.enable;
      checkbox.change(function() {
         localStorage.setItem('sjsxc.enable', this.checked);
      });

      var tabsContainer = pt("preferencesTabs");
      var controller = new SOGoTabsController();
      controller.attachToTabsContainer(tabsContainer);
   }

   var sjsxc_start = function() {

      if ($('#linkBanner').length === 0) {
         return;
      }

      $(document).on('ready.roster.jsxc', onRosterReady);
      $(document).on('toggle.roster.jsxc', onRosterToggle);

      if (jsxc.storage.getItem("abort")) {
         return;
      }

      jsxc.init($.extend({
         app_name: 'SOGo',
         loginForm: {
            form: '#connectForm',
            jid: '#userName',
            pass: '#password'
         },
         logoutElement: $('#logoff'),
         checkFlash: false,
         rosterAppend: 'body',
         root: ResourcesURL + '/sjsxc/js/jsxc',
         turnCredentialsPath: '/SOGo.woa/WebServerResources/sjsxc/ajax/getturncredentials.php',
         formFound: function() {
            var submit = pt("submit");
            submit.stopObserving("click", onLoginClick);

            var userName = pt("userName");
            userName.stopObserving("keydown", onFieldKeyDown);

            var passw = pt("password");
            passw.stopObserving("keydown", onFieldKeyDown);

            $('#connectForm').submit(onLoginClick);
            $('#submit').click(function() {
               $('#connectForm').submit();
            });
            $('#userName, #password').keypress(function(ev) {
               if (ev.which !== 13) {
                  return;
               }

               $('#connectForm').submit();
            });
         },
         loadSettings: function() {
            return sjsxc.config;
         },
         displayRosterMinimized: function() {
             return $('#logoff').length > 0;
         }
      }, sjsxc.config.jsxc || {}));

      // Add submit link without chat functionality
      if (jsxc.el_exists($('#loginCell'))) {

         var link = $('').text($.t('Log_in_without_chat')).click(function() {
            jsxc.submitLoginForm();
         });

         var alt = $('
').append(link);
         $('#loginCell').append('
').append(alt);
      }
   };

   var sjsxc_init = function() {
      if ($('#jsxc_sogo_test').css('background-color') !== '' && $('#jsxc_sogo_test').css('position') === 'absolute') {
         $('#jsxc_sogo_test').remove();
         sjsxc_start();
      } else {
         setTimeout(sjsxc_init, 50);
      }
   };

   $(function() {

      if (typeof sjsxc === 'undefined' || typeof sjsxc.config === 'undefined') {
         console.error('No config for sjsxc found! Look at sjsxc.config.sample.js.');
         return;
      }

      $.extend(true, sjsxc.config, sjsxc.config[document.domain] || {});

      var el = $('
').attr('class', 'jsxc_window').attr('id', 'jsxc_sogo_test');
      $('body').append(el);

      var enable = JSON.parse(localStorage.getItem('sjsxc.enable'));
      sjsxc.config.enable = (typeof enable === 'undefined' || enable === null) ? sjsxc.config.enable : enable;

      if (window.location.pathname.match(/\/preferences$/)) {
         addOption();
         return;
      }

      if (sjsxc.config.enable === true) {
         setTimeout(sjsxc_init, 20);
      }
   });

})(jQuery, $);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var exec = require('child_process').exec;
var fs = require('fs');
var homedir = require('os-homedir');
var os = require('os');

gulp.task('setup', function(callback) {
    var username = process.env.PARTICLE_USERNAME;
    var accessToken = process.env.PARTICLE_ACCESSTOKEN;
    var createdInBuild = process.env.BUILD_BUILDNUMBER;

    var particleConfiguration = {
      username: username,
      access_token: accessToken,
      created_in_build: createdInBuild
    };

    var particleConfigurationFileContents = JSON.stringify(
        particleConfiguration,
        null,
        '\t'
        );

    fs.mkdir(homedir() + '/.particle', function () {
        fs.writeFile(homedir() + '/.particle/particle.config.json', particleConfigurationFileContents, function (err) {
            callback(err);
        });
    });
});

gulp.task('compile', ['setup'], function (callback) {
    if (os.type() == 'win32') {
        var command = 'node_modules/.bin/particle.cmd';
    } else {
        var command = 'node_modules/.bin/particle';
    }

    exec(command + ' compile photon firmware.ino', function(err) {
        callback(err);
    });
});

gulp.task('default', ['compile']);<commit_msg>Windows_NT or win32?<commit_after>var gulp = require('gulp');
var exec = require('child_process').exec;
var fs = require('fs');
var homedir = require('os-homedir');
var os = require('os');

gulp.task('setup', function(callback) {
    var username = process.env.PARTICLE_USERNAME;
    var accessToken = process.env.PARTICLE_ACCESSTOKEN;
    var createdInBuild = process.env.BUILD_BUILDNUMBER;

    var particleConfiguration = {
      username: username,
      access_token: accessToken,
      created_in_build: createdInBuild
    };

    var particleConfigurationFileContents = JSON.stringify(
        particleConfiguration,
        null,
        '\t'
        );

    fs.mkdir(homedir() + '/.particle', function () {
        fs.writeFile(homedir() + '/.particle/particle.config.json', particleConfigurationFileContents, function (err) {
            callback(err);
        });
    });
});

gulp.task('compile', ['setup'], function (callback) {
    if (os.type() == 'Windows_NT') {
        var command = 'node_modules/.bin/particle.cmd';
    } else {
        var command = 'node_modules/.bin/particle';
    }

    exec(command + ' compile photon firmware.ino', function(err) {
        callback(err);
    });
});

gulp.task('default', ['compile']);<|endoftext|>