<commit_before>var fs = require('fs');
var q  = require('querystring');

/**
 * set credentials and create new client
 * @param  {Object} config credential data
 */
function dmmClient(config) {
  if (!(this instanceof dmmClient)) {
    return new dmmClient(config);
  }

  this.credentials = {
    api_id       : config.api_id,
    affiliate_id : config.affiliate_id
  } || {};
}

var request;
var run_env;

module.exports = {
  Client: dmmClient,

  request: function(req) {
    request = req;
  },

  set_env: function(env) {
    run_env = env;
  }
}

var baseURL = 'https://api.dmm.com/affiliate/v3';
var version = require('../package.json').version;

dmmClient.prototype.actress = function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/ActressSearch', options, callback);
}

dmmClient.prototype.author = function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/AuthorSearch', options, callback);
}

dmmClient.prototype.floor = function (callback) {
    this._get('/FloorList', null, callback);
}

dmmClient.prototype.genre = function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/GenreSearch', options, callback);
}

dmmClient.prototype.maker = function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/MakerSearch', options, callback);
}

dmmClient.prototype.product = function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/ItemList', options, callback);
}

dmmClient.prototype.series = function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/SeriesSearch', options, callback);
}

dmmClient.prototype._get = function (path, params, callback) {
    params              = params || {};
    params.api_id       = this.credentials.api_id;
    params.affiliate_id = this.credentials.affiliate_id;

    request.get({
      url: baseURL + path + '?' + q.stringify(params),
      json: true,
      followRedirect: false
    }, requestCallback(callback));
}

function requestCallback(callback) {
  if (!callback) return undefined;
  return function (err, response, body) {
    if (err) return callback(err);
    if (run_env == "browser") {
      if (response && response.body) {
        var res = JSON.parse(response.body);
        var result = (res && res.result) ? res.result : res;
        return callback(null, result);
      } else {
        return callback(new Error('API error (malformed API response): ' + response));
      }
    } else {
      if (response.statusCode >= 400) {
        var errString = body.meta ? body.meta.msg : body.error;
        return callback(new Error('API error: ' + response.statusCode + ' ' + errString));
      }
      if (body && body.response) {
        return callback(null, body.response);
      } else {
        return callback(new Error('API error (malformed API response): ' + body));
      }
    }
  };
}

function isFunction(value) {
  return Object.prototype.toString.call(value) == '[object Function]';
}<commit_msg>fix indents<commit_after>var fs = require('fs');
var q  = require('querystring');

/**
 * set credentials and create new client
 * @param  {Object} config credential data
 */
function dmmClient(config) {
  if (!(this instanceof dmmClient)) {
    return new dmmClient(config);
  }

  this.credentials = {
    api_id       : config.api_id,
    affiliate_id : config.affiliate_id
  } || {};
}

var request;
var run_env;

module.exports = {
  Client: dmmClient,

  request: function(req) {
    request = req;
  },

  set_env: function(env) {
    run_env = env;
  }
}

var baseURL = 'https://api.dmm.com/affiliate/v3';
var version = require('../package.json').version;

dmmClient.prototype.actress = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/ActressSearch', options, callback);
}

dmmClient.prototype.author = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/AuthorSearch', options, callback);
}

dmmClient.prototype.floor = function (callback) {
  this._get('/FloorList', null, callback);
}

dmmClient.prototype.genre = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/GenreSearch', options, callback);
}

dmmClient.prototype.maker = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/MakerSearch', options, callback);
}

dmmClient.prototype.product = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/ItemList', options, callback);
}

dmmClient.prototype.series = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/SeriesSearch', options, callback);
}

dmmClient.prototype._get = function (path, params, callback) {
  params              = params || {};
  params.api_id       = this.credentials.api_id;
  params.affiliate_id = this.credentials.affiliate_id;

  request.get({
    url: baseURL + path + '?' + q.stringify(params),
    json: true,
    followRedirect: false
  }, requestCallback(callback));
}

function requestCallback(callback) {
  if (!callback) return undefined;
  return function (err, response, body) {
    if (err) return callback(err);
    if (run_env == "browser") {
      if (response && response.body) {
        var res = JSON.parse(response.body);
        var result = (res && res.result) ? res.result : res;
        return callback(null, result);
      } else {
        return callback(new Error('API error (malformed API response): ' + response));
      }
    } else {
      if (response.statusCode >= 400) {
        var errString = body.meta ? body.meta.msg : body.error;
        return callback(new Error('API error: ' + response.statusCode + ' ' + errString));
      }
      if (body && body.response) {
        return callback(null, body.response);
      } else {
        return callback(new Error('API error (malformed API response): ' + body));
      }
    }
  };
}

function isFunction(value) {
  return Object.prototype.toString.call(value) == '[object Function]';
}<|endoftext|>


<commit_before>var fs = require('fs');
var q  = require('querystring');

/**
 * Sets credentials and create new client
 * @param  {Object} config credential data
 * @sample
 * var client = new dmm.Client({
 *     api_id: "YOUR-API-ID",
 *     affiliate_id: "YOUR-AFFILIATE-ID"
 * });
 */
function dmmClient(config) {
  if (!(this instanceof dmmClient)) {
    return new dmmClient(config);
  }

  this.credentials = {
    api_id       : config.api_id,
    affiliate_id : config.affiliate_id
  } || {};
}

var request;
var run_env;

module.exports = {
  Client: dmmClient,

  request: function(req) {
    request = req;
  },

  set_env: function(env) {
    run_env = env;
  }
}

var baseURL = 'https://api.dmm.com/affiliate/v3';
var version = require('../package.json').version;

/**
 * Requests Actress API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.actress({
 *   initial: "あ",
 *   keyword: "あさみ",
 *   bust: 90,
 *   waist: -60,
 *   hip: "85-90",
 *   height: 160,
 *   birthday: "19900101",
 *   sort: "-name",
 *   hits: 20,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.actress = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/ActressSearch', options, callback);
}

/**
 * Requests Author API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.author({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.author = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/AuthorSearch', options, callback);
}

/**
 * Requests Floor API
 *
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.floor(function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.floor = function (callback) {
  this._get('/FloorList', null, callback);
}

/**
 * Requests Genre API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.genre({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.genre = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/GenreSearch', options, callback);
}

/**
 * Requests Maker API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.maker({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.maker = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/MakerSearch', options, callback);
}

/**
 * Requests Product API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.product({
 *   site: "DMM.R18",
 *   service: "mono",
 *   floor: "dvd",
 *   sort: "date",
 *   hits: 20,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.product = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/ItemList', options, callback);
}

/**
 * Requests Series API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.series({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.series = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/SeriesSearch', options, callback);
}

/**
 * Requests API
 *
 * @param  {string}   path     url path for the request
 * @param  {Object}   params   request parameters
 * @param  {function} callback callback function that receives the response
 * client._get("/ItemList", {
 *   site: "DMM.R18",
 *   service: "mono",
 *   floor: "dvd",
 *   sort: "date",
 *   hits: 20,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype._get = function (path, params, callback) {
  params              = params || {};
  params.api_id       = this.credentials.api_id;
  params.affiliate_id = this.credentials.affiliate_id;

  request.get({
    url: baseURL + path + '?' + q.stringify(params),
    json: true,
    followRedirect: false
  }, requestCallback(callback));
}

function requestCallback(callback) {
  if (!callback) return undefined;
  return function (err, response, body) {
    if (err) return callback(err);
    if (run_env == "browser") {
      if (response && response.body) {
        var res = JSON.parse(response.body);
        var result = (res && res.result) ? res.result : res;
        return callback(null, result);
      } else {
        return callback(new Error('API error (malformed API response): ' + response));
      }
    } else {
      if (response.statusCode >= 400) {
        var errString = body.meta ? body.meta.msg : body.error;
        return callback(new Error('API error: ' + response.statusCode + ' ' + errString));
      }
      if (body && body.response) {
        return callback(null, body.response);
      } else {
        return callback(new Error('API error (malformed API response): ' + body));
      }
    }
  };
}

/**
 * Check the retrieved paramter is function or not.
 *
 * @param {mixed} value
 */
function isFunction(value) {
  return Object.prototype.toString.call(value) == '[object Function]';
}<commit_msg>fix requestCallback bug when use nodejs<commit_after>var fs = require('fs');
var q  = require('querystring');

/**
 * Sets credentials and create new client
 * @param  {Object} config credential data
 * @sample
 * var client = new dmm.Client({
 *     api_id: "YOUR-API-ID",
 *     affiliate_id: "YOUR-AFFILIATE-ID"
 * });
 */
function dmmClient(config) {
  if (!(this instanceof dmmClient)) {
    return new dmmClient(config);
  }

  this.credentials = {
    api_id       : config.api_id,
    affiliate_id : config.affiliate_id
  } || {};
}

var request;
var run_env;

module.exports = {
  Client: dmmClient,

  request: function(req) {
    request = req;
  },

  set_env: function(env) {
    run_env = env;
  }
}

var baseURL = 'https://api.dmm.com/affiliate/v3';
var version = require('../package.json').version;

/**
 * Requests Actress API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.actress({
 *   initial: "あ",
 *   keyword: "あさみ",
 *   bust: 90,
 *   waist: -60,
 *   hip: "85-90",
 *   height: 160,
 *   birthday: "19900101",
 *   sort: "-name",
 *   hits: 20,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.actress = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/ActressSearch', options, callback);
}

/**
 * Requests Author API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.author({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.author = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/AuthorSearch', options, callback);
}

/**
 * Requests Floor API
 *
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.floor(function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.floor = function (callback) {
  this._get('/FloorList', null, callback);
}

/**
 * Requests Genre API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.genre({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.genre = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/GenreSearch', options, callback);
}

/**
 * Requests Maker API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.maker({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.maker = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/MakerSearch', options, callback);
}

/**
 * Requests Product API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.product({
 *   site: "DMM.R18",
 *   service: "mono",
 *   floor: "dvd",
 *   sort: "date",
 *   hits: 20,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.product = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/ItemList', options, callback);
}

/**
 * Requests Series API
 *
 * @param  {Object}   options  request parameters
 * @param  {function} callback callback function that receives the response
 * @sample
 * client.series({
 *   floor_id: 40,
 *   initial: "あ",
 *   hits: 100,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype.series = function (options, callback) {
  if (isFunction(options)) { callback = options; options = {}; }
  this._get('/SeriesSearch', options, callback);
}

/**
 * Requests API
 *
 * @param  {string}   path     url path for the request
 * @param  {Object}   params   request parameters
 * @param  {function} callback callback function that receives the response
 * client._get("/ItemList", {
 *   site: "DMM.R18",
 *   service: "mono",
 *   floor: "dvd",
 *   sort: "date",
 *   hits: 20,
 *   offset: 1
 * }, function(err, data){
 *   console.log(data);
 * });
 */
dmmClient.prototype._get = function (path, params, callback) {
  params              = params || {};
  params.api_id       = this.credentials.api_id;
  params.affiliate_id = this.credentials.affiliate_id;

  request.get({
    url: baseURL + path + '?' + q.stringify(params),
    json: true,
    followRedirect: false
  }, requestCallback(callback));
}

function requestCallback(callback) {
  if (!callback) return undefined;
  return function (err, response, body) {
    if (err) return callback(err);
    if (run_env == "browser") {
      if (response && response.body) {
        var res = JSON.parse(response.body);
        var result = (res && res.result) ? res.result : res;
        return callback(null, result);
      } else {
        return callback(new Error('API error (malformed API response): ' + response));
      }
    } else {
      if (response.statusCode >= 400) {
        var errString = body.message ? body.message : 'unknown error';
        return callback(new Error('API error: ' + response.statusCode + ' ' + errString));
      }
      if (body) {
        return callback(null, body);
      } else {
        return callback(new Error('API error (malformed API response): ' + body));
      }
    }
  };
}

/**
 * Check the retrieved paramter is function or not.
 *
 * @param {mixed} value
 */
function isFunction(value) {
  return Object.prototype.toString.call(value) == '[object Function]';
}
<|endoftext|>


<commit_before>/*
 jsonml-dom.js
 HTML to JsonML utility

 Created: 2007-02-15-2235

 Copyright (c)2006-2012 Stephen M. McKamey
 Distributed under The MIT License: http://jsonml.org/license
*/

'use strict';

const jsdom = require('jsdom').jsdom;

var addChildren = function(/*DOM*/ elem, /*function*/ filter, /*JsonML*/ jml) {
  if (elem.hasChildNodes()) {
    for (var i=0; i<elem.childNodes.length; i++) {
      var child = elem.childNodes[i];
      child = fromHTML(child, filter);
      if (child) {
	jml.push(child);
      }
    }
    return true;
  }
  return false;
};

/**
 * @param {Node} elem
 * @param {function} filter
 * @return {array} JsonML
 */
var fromHTML = exports.fromHTML = function(elem, filter) {
  if (!elem || !elem.nodeType) {
    // free references
    return (elem = null);
  }

  var i, jml;
  switch (elem.nodeType) {
  case 1:  // element
  case 9:  // document
  case 11: // documentFragment
    jml = [elem.tagName.toLowerCase()||''];

    var attr = elem.attributes,
	props = {},
	hasAttrib = false;

    for (i=0; attr && i<attr.length; i++) {
      if (attr[i].specified) {
	if (attr[i].name === 'style') {
	  props.style = elem.style.cssText || attr[i].value;
	} else if ('string' === typeof attr[i].value) {
	  props[attr[i].name] = attr[i].value;
	}
	hasAttrib = true;
      }
    }
    if (hasAttrib) {
      jml.push(props);
    }

    var child;
    switch (jml[0].toLowerCase()) {
    case 'frame':
    case 'iframe':
      try {
	if ('undefined' !== typeof elem.contentDocument) {
	  // W3C
	  child = elem.contentDocument;
	} else if ('undefined' !== typeof elem.contentWindow) {
	  // Microsoft
	  child = elem.contentWindow.document;
	} else if ('undefined' !== typeof elem.document) {
	  // deprecated
	  child = elem.document;
	}

	child = fromHTML(child, filter);
	if (child) {
	  jml.push(child);
	}
      } catch (ex) {}
      break;
    case 'style':
      child = elem.styleSheet && elem.styleSheet.cssText;
      if (child && 'string' === typeof child) {
	// unwrap comment blocks
	child = child.replace('<!--', '').replace('-->', '');
	jml.push(child);
      } else if (elem.hasChildNodes()) {
	for (i=0; i<elem.childNodes.length; i++) {
	  child = elem.childNodes[i];
	  child = fromHTML(child, filter);
	  if (child && 'string' === typeof child) {
	    // unwrap comment blocks
	    child = child.replace('<!--', '').replace('-->', '');
	    jml.push(child);
	  }
	}
      }
      break;
    case 'input':
      addChildren(elem, filter, jml);
      child = (elem.type !== 'password') && elem.value;
      if (child) {
	if (!hasAttrib) {
	  // need to add an attribute object
	  jml.shift();
	  props = {};
	  jml.unshift(props);
	  jml.unshift(elem.tagName.toLowerCase()||'');
	}
	props.value = child;
      }
      break;
    case 'textarea':
      if (!addChildren(elem, filter, jml)) {
	child = elem.value || elem.innerHTML;
	if (child && 'string' === typeof child) {
	  jml.push(child);
	}
      }
      break;
    default:
      addChildren(elem, filter, jml);
      break;
    }

    // filter result
    if ('function' === typeof filter) {
      jml = filter(jml, elem);
    }

    // free references
    elem = null;
    return jml;
  case 3: // text node
  case 4: // CDATA node
    var str = String(elem.nodeValue);
    // free references
    elem = null;
    return str;
  case 10: // doctype
    jml = ['!'];

    var type = ['DOCTYPE', (elem.name || 'html').toLowerCase()];

    if (elem.publicId) {
      type.push('PUBLIC', '"' + elem.publicId + '"');
    }

    if (elem.systemId) {
      type.push('"' + elem.systemId + '"');
    }

    jml.push(type.join(' '));

    // filter result
    if ('function' === typeof filter) {
      jml = filter(jml, elem);
    }

    // free references
    elem = null;
    return jml;
  case 8: // comment node
    if ((elem.nodeValue||'').indexOf('DOCTYPE') !== 0) {
      // free references
      elem = null;
      return null;
    }

    jml = ['!',
	   elem.nodeValue];

    // filter result
    if ('function' === typeof filter) {
      jml = filter(jml, elem);
    }

    // free references
    elem = null;
    return jml;
  default: // etc.
    // free references
    return (elem = null);
  }
};

const doc = typeof document === 'undefined' ?
      jsdom(undefined, {}) :
      document;

/**
 * @param {string} html HTML text
 * @param {function} filter
 * @return {array} JsonML
 */
exports.fromHTMLText = function(html, filter) {
  var elem = doc.createElement('div');
  elem.innerHTML = html;

  var jml = fromHTML(elem, filter);

  // free references
  elem = null;

  if (jml.length === 2) {
    return jml[1];
  }

  // make wrapper a document fragment
  jml[0] = '';
  return jml;
};
<commit_msg>fix: ignore empty string<commit_after>/*
 jsonml-dom.js
 HTML to JsonML utility

 Created: 2007-02-15-2235

 Copyright (c)2006-2012 Stephen M. McKamey
 Distributed under The MIT License: http://jsonml.org/license
*/

'use strict';

const jsdom = require('jsdom').jsdom;

var addChildren = function(/*DOM*/ elem, /*function*/ filter, /*JsonML*/ jml) {
  if (elem.hasChildNodes()) {
    for (var i=0; i<elem.childNodes.length; i++) {
      var child = elem.childNodes[i];
      child = fromHTML(child, filter);
      if (child) {
	jml.push(child);
      }
    }
    return true;
  }
  return false;
};

/**
 * @param {Node} elem
 * @param {function} filter
 * @return {array} JsonML
 */
var fromHTML = exports.fromHTML = function(elem, filter) {
  if (!elem || !elem.nodeType) {
    // free references
    return (elem = null);
  }

  var i, jml;
  switch (elem.nodeType) {
  case 1:  // element
  case 9:  // document
  case 11: // documentFragment
    jml = [elem.tagName.toLowerCase()||''];

    var attr = elem.attributes,
	props = {},
	hasAttrib = false;

    for (i=0; attr && i<attr.length; i++) {
      if (attr[i].specified) {
	if (attr[i].name === 'style') {
	  props.style = elem.style.cssText || attr[i].value;
	} else if ('string' === typeof attr[i].value) {
	  props[attr[i].name] = attr[i].value;
	}
	hasAttrib = true;
      }
    }
    if (hasAttrib) {
      jml.push(props);
    }

    var child;
    switch (jml[0].toLowerCase()) {
    case 'frame':
    case 'iframe':
      try {
	if ('undefined' !== typeof elem.contentDocument) {
	  // W3C
	  child = elem.contentDocument;
	} else if ('undefined' !== typeof elem.contentWindow) {
	  // Microsoft
	  child = elem.contentWindow.document;
	} else if ('undefined' !== typeof elem.document) {
	  // deprecated
	  child = elem.document;
	}

	child = fromHTML(child, filter);
	if (child) {
	  jml.push(child);
	}
      } catch (ex) {}
      break;
    case 'style':
      child = elem.styleSheet && elem.styleSheet.cssText;
      if (child && 'string' === typeof child) {
	// unwrap comment blocks
	child = child.replace('<!--', '').replace('-->', '');
	jml.push(child);
      } else if (elem.hasChildNodes()) {
	for (i=0; i<elem.childNodes.length; i++) {
	  child = elem.childNodes[i];
	  child = fromHTML(child, filter);
	  if (child && 'string' === typeof child) {
	    // unwrap comment blocks
	    child = child.replace('<!--', '').replace('-->', '');
	    jml.push(child);
	  }
	}
      }
      break;
    case 'input':
      addChildren(elem, filter, jml);
      child = (elem.type !== 'password') && elem.value;
      if (child) {
	if (!hasAttrib) {
	  // need to add an attribute object
	  jml.shift();
	  props = {};
	  jml.unshift(props);
	  jml.unshift(elem.tagName.toLowerCase()||'');
	}
	props.value = child;
      }
      break;
    case 'textarea':
      if (!addChildren(elem, filter, jml)) {
	child = elem.value || elem.innerHTML;
	if (child && 'string' === typeof child) {
	  jml.push(child);
	}
      }
      break;
    default:
      addChildren(elem, filter, jml);
      break;
    }

    // filter result
    if ('function' === typeof filter) {
      jml = filter(jml, elem);
    }

    // free references
    elem = null;
    return jml;
  case 3: // text node
  case 4: // CDATA node
    var str = String(elem.nodeValue);
    // free references
    elem = null;
    return /^(\n|\s)+$/.test(str) ? null : str;
  case 10: // doctype
    jml = ['!'];

    var type = ['DOCTYPE', (elem.name || 'html').toLowerCase()];

    if (elem.publicId) {
      type.push('PUBLIC', '"' + elem.publicId + '"');
    }

    if (elem.systemId) {
      type.push('"' + elem.systemId + '"');
    }

    jml.push(type.join(' '));

    // filter result
    if ('function' === typeof filter) {
      jml = filter(jml, elem);
    }

    // free references
    elem = null;
    return jml;
  case 8: // comment node
    if ((elem.nodeValue||'').indexOf('DOCTYPE') !== 0) {
      // free references
      elem = null;
      return null;
    }

    jml = ['!',
	   elem.nodeValue];

    // filter result
    if ('function' === typeof filter) {
      jml = filter(jml, elem);
    }

    // free references
    elem = null;
    return jml;
  default: // etc.
    // free references
    return (elem = null);
  }
};

const doc = typeof document === 'undefined' ?
      jsdom(undefined, {}) :
      document;

/**
 * @param {string} html HTML text
 * @param {function} filter
 * @return {array} JsonML
 */
exports.fromHTMLText = function(html, filter) {
  var elem = doc.createElement('div');
  elem.innerHTML = html;

  var jml = fromHTML(elem, filter);

  // free references
  elem = null;

  if (jml.length === 2) {
    return jml[1];
  }

  // make wrapper a document fragment
  jml[0] = '';
  return jml;
};
<|endoftext|>


<commit_before>import Grid from '../grid';

frappe.ui.form.ControlTable = frappe.ui.form.Control.extend({
	make: function() {
		this._super();

		// add title if prev field is not column / section heading or html
		this.grid = new Grid({
			frm: this.frm,
			df: this.df,
			perm: this.perm || (this.frm && this.frm.perm) || this.df.perm,
			parent: this.wrapper,
			control: this
		});
		if(this.frm) {
			this.frm.grids[this.frm.grids.length] = this;
		}
		this.$wrapper.on('paste',':text', function(e) {
			var cur_table_field =$(e.target).closest('div [data-fieldtype="Table"]').data('fieldname');
			var cur_field = $(e.target).data('fieldname');
			var cur_grid= cur_frm.get_field(cur_table_field).grid;
			var cur_grid_rows = cur_grid.grid_rows;
			var cur_doctype = cur_grid.doctype;
			var cur_row_docname =$(e.target).closest('div .grid-row').data('name');
			var row_idx = locals[cur_doctype][cur_row_docname].idx;
			var clipboardData, pastedData;
			// Get pasted data via clipboard API
			clipboardData = e.clipboardData || window.clipboardData || e.originalEvent.clipboardData;
			pastedData = clipboardData.getData('Text');
			if (!pastedData) return;
			var data = frappe.utils.csv_to_array(pastedData,'\t');
			if (data.length === 1 & data[0].length === 1) return;
			if (data.length > 100){
				data = data.slice(0, 100);
				frappe.msgprint(__('For performance, only the first 100 rows were processed.'));
			}
			var fieldnames = [];
			var get_field = function(name_or_label){
				var fieldname;
				$.each(cur_grid.meta.fields,(ci,field)=>{
					name_or_label = name_or_label.toLowerCase()
					if (field.fieldname.toLowerCase() === name_or_label ||
						(field.label && field.label.toLowerCase() === name_or_label)){
						  fieldname = field.fieldname;
						  return false;
						}
				});
				return fieldname;
			}
			if (get_field(data[0][0])){ // for raw data with column header
				$.each(data[0], (ci, column)=>{fieldnames.push(get_field(column));});
				data.shift();
			}
			else{ // no column header, map to the existing visible columns
				var visible_columns = cur_grid_rows[0].get_visible_columns();
				var find;
				$.each(visible_columns, (ci, column)=>{
					if (column.fieldname === cur_field) find = true;
					find && fieldnames.push(column.fieldname);
				})
			}
			$.each(data, function(i, row) {
				var blank_row = true;
				$.each(row, function(ci, value) {
					if(value) {
						blank_row = false;
						return false;
					}
				});
				if(!blank_row) {
					if (row_idx > cur_frm.doc[cur_table_field].length){
						cur_grid.add_new_row();
					}
					var cur_row = cur_grid_rows[row_idx - 1];
					row_idx ++;
					var row_name = cur_row.doc.name;
					$.each(row, function(ci, value) {
						if (fieldnames[ci]) frappe.model.set_value(cur_doctype, row_name, fieldnames[ci], value);
					});
					frappe.show_progress(__('Processing'), i, data.length);
				}
			});
			frappe.hide_progress();
			return false; // Prevent the default handler from running.
		});
	},
	refresh_input: function() {
		this.grid.refresh();
	},
	get_value: function() {
		if(this.grid) {
			return this.grid.get_data();
		}
	},
	set_input: function( ) {
		//
	},
	validate: function() {
		return this.get_value();
	},
	check_all_rows() {
		this.$wrapper.find('.grid-row-check')[0].click();
	}
});
<commit_msg>fix: copy paste rows more than 50 (one page) (bp #12548) (#12736)<commit_after>import Grid from '../grid';

frappe.ui.form.ControlTable = frappe.ui.form.Control.extend({
	make: function() {
		this._super();

		// add title if prev field is not column / section heading or html
		this.grid = new Grid({
			frm: this.frm,
			df: this.df,
			perm: this.perm || (this.frm && this.frm.perm) || this.df.perm,
			parent: this.wrapper,
			control: this
		});
		if(this.frm) {
			this.frm.grids[this.frm.grids.length] = this;
		}
		this.$wrapper.on('paste',':text', function(e) {
			var cur_table_field =$(e.target).closest('div [data-fieldtype="Table"]').data('fieldname');
			var cur_field = $(e.target).data('fieldname');
			var cur_grid= cur_frm.get_field(cur_table_field).grid;
			var grid_pagination = cur_grid.grid_pagination;
			var cur_grid_rows = cur_grid.grid_rows;
			var cur_doctype = cur_grid.doctype;
			var cur_row_docname =$(e.target).closest('div .grid-row').data('name');
			var row_idx = locals[cur_doctype][cur_row_docname].idx;
			var clipboardData, pastedData;
			// Get pasted data via clipboard API
			clipboardData = e.clipboardData || window.clipboardData || e.originalEvent.clipboardData;
			pastedData = clipboardData.getData('Text');
			if (!pastedData) return;
			var data = frappe.utils.csv_to_array(pastedData,'\t');
			if (data.length === 1 & data[0].length === 1) return;
			if (data.length > 500) {
				data = data.slice(0, 500);
				frappe.msgprint(__('For performance, only the first 500 rows were processed.'));
			}
			var fieldnames = [];
			var get_field = function(name_or_label) {
				var fieldname;
				$.each(cur_grid.meta.fields,(ci,field)=>{
					name_or_label = name_or_label.toLowerCase()
					if (field.fieldname.toLowerCase() === name_or_label ||
						(field.label && !in_list(frappe.model.no_value_type, field.fieldtype) &&
						field.label.toLowerCase() === name_or_label)) {
						  fieldname = field.fieldname;
						  return false;
						}
				});
				return fieldname;
			}
			if (get_field(data[0][0])){ // for raw data with column header
				$.each(data[0], (ci, column)=>{fieldnames.push(get_field(column));});
				data.shift();
			}
			else{ // no column header, map to the existing visible columns
				var visible_columns = cur_grid_rows[0].get_visible_columns();
				var find;
				$.each(visible_columns, (ci, column)=>{
					if (column.fieldname === cur_field) find = true;
					find && fieldnames.push(column.fieldname);
				})
			}
			$.each(data, function(i, row) {
				var blank_row = true;
				$.each(row, function(ci, value) {
					if(value) {
						blank_row = false;
						return false;
					}
				});
				if(!blank_row) {
					if (row_idx > cur_frm.doc[cur_table_field].length){
						cur_grid.add_new_row();
					}
					if (row_idx > 1 && (row_idx - 1) % grid_pagination.page_length === 0) {
						grid_pagination.go_to_page(grid_pagination.page_index + 1);
					}
					var cur_row = cur_grid_rows[row_idx - 1];
					row_idx ++;
					var row_name = cur_row.doc.name;
					$.each(row, function(ci, value) {
						if (fieldnames[ci]) frappe.model.set_value(cur_doctype, row_name, fieldnames[ci], value);
					});
					frappe.show_progress(__('Processing'), i, data.length);
				}
			});
			frappe.hide_progress();
			return false; // Prevent the default handler from running.
		});
	},
	refresh_input: function() {
		this.grid.refresh();
	},
	get_value: function() {
		if(this.grid) {
			return this.grid.get_data();
		}
	},
	set_input: function( ) {
		//
	},
	validate: function() {
		return this.get_value();
	},
	check_all_rows() {
		this.$wrapper.find('.grid-row-check')[0].click();
	}
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var _ = require( 'underscore' );

// DOCUMENT-TERM MATRIX //

/**
* Creates a term-document matrix object.
*
* @constructor
* @param {Object} corpus - an instance of class Corpus
*/
function DocumentTermMatrix( corpus ) {

	if( !( this instanceof DocumentTermMatrix ) ) {
		return new DocumentTermMatrix(corpus);
	}

	var self = this;

	this.vocabulary = [];
	this.dtm = [];

	Object.defineProperty( this, "nDocs", {
		get: function() {
			return this.dtm.length;
		},
		enumerable: true
	});

	Object.defineProperty( this, "nTerms", {
		get: function() {
			return this.vocabulary.length;
		},
		enumerable: true
	});

	this.fill_zeros = function() {
		for ( var doc = 0; doc < self.dtm.length; doc++ ) {
			for ( var word = 0; word < self.dtm[0].length; word++ ) {
				if ( self.dtm[doc][word] === undefined ) {
					self.dtm[doc][word] = 0;
				}
			}
		}
		return self;
	};

	function _wordFreq( wordIndex ) {
		var mapping = self.dtm.map( function( doc ) {
			return doc[wordIndex] || 0;
		});
		var reducing = mapping.reduce( function( a, b ) {
			return a + b;
		});
		return reducing;
	}

	this.findFreqTerms = function findFreqTerms( n ) {
		var wordArray = [];
		for ( var w = 0; w < self.vocabulary.length; w++ ) {
			var wordCount = _wordFreq(w);
			var obj = {};
			obj.word = self.vocabulary[w];
			obj.count = wordCount;
			if ( wordCount >= n ) {
				wordArray.push(obj);
			}
		}

		var sortedWordArray = _.sortBy( wordArray, function( obj ) {
			return obj.word;
		});
		return sortedWordArray;
	};

	this.removeSparseTerms = function removeSparseTerms( percent ) {

		var flaggedForKeeping = [];
		for ( var w = 0; w < self.vocabulary.length; w++ ) {
			var counter = 0;
			for ( var d = 0; d < self.dtm.length; d++ ){
				var doc = self.dtm[d];
				if ( doc !== undefined && doc[w] !== undefined ) {
					counter++;
				}
			}
			if ( counter / self.dtm.length >= percent ) {
				flaggedForKeeping.push(w);
			}
		}

		var newVocabulary = [];
		for ( var i = 0; i < flaggedForKeeping.length; i++ ) {
			newVocabulary.push( self.vocabulary[ flaggedForKeeping[i] ] );
		}

		for ( var d2 = 0; d2 < self.dtm.length; d2++ ) {
			var newVec = [];
			for ( var j = 0; j < flaggedForKeeping.length; j++ ) {
				newVec.push( self.dtm[d2][ flaggedForKeeping[j] ] );
			}
			self.dtm[d2] = newVec;
		}

		self.vocabulary = newVocabulary;
		return self;
	};

	this.weighting = function weighting( fun ) {
		self.dtm = fun(self.dtm);
		return self;
	};

	// initialization
	this.init = function init( corpus ) {
		var i;
		var j;
		var doc;
		for ( i = 0; i < corpus.nDocs; i++ ) {
			doc = corpus.documents[ i ];
			var wordArray = doc.text.split( ' ' );
			var words = [];
			for ( j = 0; j < wordArray.length; j++ ) {
				var current_word = wordArray[ j ];
				var index = self.vocabulary.indexOf( current_word );
				if ( index > -1 ) {
						words[ index ] = words[ index ] + 1 || 1;
				} else {
					words[ self.vocabulary.length ] = 1;
					self.vocabulary.push( current_word );
				}
			}
			self.dtm.push( words );
		}
		for ( i = 0; i < self.dtm.length; i++ ) {
			doc = self.dtm[ i ];
			doc.length = self.vocabulary.length; // ensure that all rows in dtm have same length
		}
	};
	self.init( corpus );
} // end FUNCTION DocumentTermMatrix()

// EXPORTS //

module.exports = DocumentTermMatrix;
<commit_msg>Fix findFreqTerms method<commit_after>'use strict';

// MODULES //

var _ = require( 'underscore' );

// DOCUMENT-TERM MATRIX //

/**
* Creates a document-term matrix object.
*
* @constructor
* @param {Object} corpus - an instance of class Corpus
*/
function DocumentTermMatrix( corpus ) {

	if( !( this instanceof DocumentTermMatrix ) ) {
		return new DocumentTermMatrix(corpus);
	}

	var self = this;

	this.vocabulary = [];
	this.data = [];

	Object.defineProperty( this, "nDocs", {
		get: function() {
			return this.data.length;
		},
		enumerable: true
	});

	Object.defineProperty( this, "nTerms", {
		get: function() {
			return this.vocabulary.length;
		},
		enumerable: true
	});

	this.removeSparseTerms = function removeSparseTerms( percent ) {

		var flaggedForKeeping = [];
		for ( var w = 0; w < self.vocabulary.length; w++ ) {
			var counter = 0;
			for ( var d = 0; d < self.data.length; d++ ){
				var doc = self.data[d];
				if ( doc !== undefined && doc[w] !== undefined ) {
					counter++;
				}
			}
			if ( counter / self.data.length >= percent ) {
				flaggedForKeeping.push(w);
			}
		}

		var newVocabulary = [];
		for ( var i = 0; i < flaggedForKeeping.length; i++ ) {
			newVocabulary.push( self.vocabulary[ flaggedForKeeping[i] ] );
		}

		for ( var d2 = 0; d2 < self.data.length; d2++ ) {
			var newVec = [];
			for ( var j = 0; j < flaggedForKeeping.length; j++ ) {
				newVec.push( self.data[d2][ flaggedForKeeping[j] ] );
			}
			self.data[d2] = newVec;
		}

		self.vocabulary = newVocabulary;
		return self;
	};

	this.weighting = function weighting( fun ) {
		self.data = fun(self.data);
		return self;
	};

	/**
	* Function called upon creating a DocumentTermMatrix instances
	*
	* @param  {Corpus} corpus - input corpus
	* @return {DocumentTermMatrix} created document-term matrix
	*/
	this.init = function init( corpus ) {
		var i;
		var j;
		var doc;
		for ( i = 0; i < corpus.nDocs; i++ ) {
			doc = corpus.documents[ i ];
			var wordArray = doc.text.split( ' ' );
			var words = [];
			for ( j = 0; j < wordArray.length; j++ ) {
				var current_word = wordArray[ j ];
				var index = self.vocabulary.indexOf( current_word );
				if ( index > -1 ) {
						words[ index ] = words[ index ] + 1 || 1;
				} else {
					words[ self.vocabulary.length ] = 1;
					self.vocabulary.push( current_word );
				}
			}
			self.data.push( words );
		}
		for ( i = 0; i < self.data.length; i++ ) {
			doc = self.data[ i ];
			// Ensure that all rows in data have same length:
			doc.length = self.vocabulary.length;
		}
	};
	self.init( corpus );
} // end FUNCTION DocumentTermMatrix()

// PROTOTYPE METHODS //

DocumentTermMatrix.prototype.fill_zeros = require( './fill_zeros.js' );

/**
* Find the `n` most frequent terms in the terms matrix and return them as a sorted array
* of objects with `word` and `count` keys.
*
* @param  {Number} n - number indicating how many terms should be returned
* @return {Array} array of objects with `word` and `count` keys
*/
DocumentTermMatrix.prototype.findFreqTerms = function findFreqTerms( n ) {
	var count;
	var obj;
	var wordArray = [];
	var sortedWordArray;
	var w;
	var d;

	for ( w = 0; w < this.nTerms; w++ ) {
		count = 0;
		for ( d = 0; d < this.nDocs; d++ ) {
			if ( this.data[ d ][ w ] ) {
				count += this.data[ d ][ w ];
			}
		}
		obj = {};
		obj.word = this.vocabulary[ w ];
		obj.count = count;
		if ( count >= n ) {
			wordArray.push( obj );
		}
	}

	sortedWordArray = _.sortBy( wordArray, function( obj ) {
		return obj.word;
	});
	return sortedWordArray;
}; // end METHOD findFreqTerms()

// EXPORTS //

module.exports = DocumentTermMatrix;
<|endoftext|>


<commit_before>//Trying out a more friendly and dynamic configuration utility.  Currently being
//used mainly for mocha tests but could potentially replace our older config.js
//going forward.

function Environment() {

    this.SCHEMES = {
        HTTP: 'http',
        HTTPS: 'https',
        WEBSOCKET: 'ws',
        MONGO: 'mongodb'
    };
    this.defaultScheme = this.SCHEMES.HTTP;

    this.HOSTNAMES = {
        LOCALHOST: 'localhost',
        DOCKER_LOCAL: '192.168.99.100',
        DEV: 'dev.voyent.cloud',
        PROD: 'api.voyent.cloud',
        INTERNAL_PROXY: 'web1'
    };
    this.hostname = process.env.VOYENT_HOST || this.HOSTNAMES.DOCKER_LOCAL;

    this.useAuthProxy = false;
    this.useInternalProxy = this.hostname !== this.HOSTNAMES.DOCKER_LOCAL;

    this.services = {};
}

Environment.prototype.isLocalhost = function () {
    return this.hostname === this.HOSTNAMES.LOCALHOST;
};

Environment.prototype.isLocalDocker = function () {
    return this.hostname === this.HOSTNAMES.DOCKER_LOCAL;
};

Environment.prototype.isProduction = function () {
    return process.env.NODE_ENV === 'production';
};

Environment.prototype.getHostname = function () {
    return this.hostname;
};

Environment.prototype.setHostname = function (hostname) {
    this.hostname = hostname;
};

Environment.prototype.usingAuthProxy = function () {
    return this.useAuthProxy;
};

Environment.prototype.setUsingAuthProxy = function (useAuthProxy) {
    this.useAuthProxy = useAuthProxy;
};

Environment.prototype.addService = function (service) {
    this.services[service.getName()] = service;
};

Environment.prototype.getService = function (name) {
    return this.services[name];
};

var env = new Environment();
module.exports = env;

function Service(name, servicePort) {
    this.name = name;
    this.servicePort = servicePort || 80;
    this.scheme = env.defaultScheme;
    this.internalProxy = env.HOSTNAMES.INTERNAL_PROXY;
}

Service.prototype.getName = function () {
    return this.name;
};

Service.prototype.getScheme = function () {
    return this.scheme;
};

Service.prototype.setScheme = function (scheme) {
    this.scheme = scheme;
};

Service.prototype.usingAuthProxy = function () {
    if(this.useAuthProxy === true || this.useAuthProxy === false){
        return this.useAuthProxy;
    }
    return env.usingAuthProxy();
};

Service.prototype.setUsingAuthProxy = function (useAuthProxy) {
    this.useAuthProxy = useAuthProxy;
};

Service.prototype.getHostname = function () {
    if (this.hostname) {
        return this.hostname;
    }

    return env.getHostname();
};

Service.prototype.setHostname = function (hostname) {
    this.hostname = hostname;
};

Service.prototype.getInternalHostname = function () {

    if (env.isLocalhost()) {
        return env.HOSTNAMES.LOCALHOST;
    }

    if (this.internalHostname) {
        return this.internalHostname;
    }

    return env.HOSTNAMES.INTERNAL_PROXY;
};

Service.prototype.setInternalHostname = function (internalHostname) {
    this.internalHostname = internalHostname;
};

Service.prototype.getServicePort = function () {

    if (env.isLocalhost()) {

        if (this.usingAuthProxy()) {
            return env.services.proxy.servicePort;
        }
    }

    return this.servicePort;
};

Service.prototype.setServicePort = function (servicePort) {
    this.servicePort = servicePort;
};

Service.prototype.getServicePath = function () {
    if (this.servicePath) {
        if (this.servicePath === '/') {
            return '';
        }
        return this.servicePath;
    }
    return '/' + this.name;
};

Service.prototype.getServicePathForRealm = function (account, realm) {
    return this.getServicePath() + '/' + account + '/realms/' + realm;
};

Service.prototype.setServicePath = function (servicePath) {
    this.servicePath = servicePath;
};

Service.prototype.getReferrer = function () {
    return this.getScheme() + '://' + this.getHostname();
};

Service.prototype.getExternalHost = function () {
    var thePort = this.getServicePort();
    var theHostname = this.getHostname();
    var theHost = this.getScheme() + '://' + this.getHostname();
    if (thePort === 80 || theHostname !== env.HOSTNAMES.LOCALHOST) {
        return theHost;
    }

    return theHost + ':' + thePort;
};

Service.prototype.getInternalHost = function () {
    var thePort = this.getServicePort();
    var theHostname = this.getInternalHostname();
    var theHost = this.getScheme() + '://' + this.getInternalHostname();
    if (thePort === 80 || theHostname === env.HOSTNAMES.INTERNAL_PROXY) {
        return theHost;
    }

    return theHost + ':' + thePort;
};

Service.prototype.getExternalURL = function () {
    return this.getExternalHost() + this.getServicePath();
};

Service.prototype.getInternalURL = function () {
    return this.getInternalHost() + this.getServicePath();
};

Service.prototype.getExternalURLForRealm = function (account, realm) {
    return this.getExternalHost() + this.getServicePathForRealm(account, realm);
};

Service.prototype.getInternalURLForRealm = function (account, realm) {
    return this.getInternalHost() + this.getServicePathForRealm(account, realm);
};

var proxyService = new Service('proxy', 55010);
proxyService.setServicePath('/');
env.addService(proxyService);

var authService = new Service('auth', 55010);
env.addService(authService);

var authAdminService = new Service('authadmin', 55010);
env.addService(authAdminService);

var locateService = new Service('locate', 55020);
env.addService(locateService);

var contextService = new Service('context', 55060);
env.addService(contextService);

var docsService = new Service('docs', 55080);
env.addService(docsService);

var pushService = new Service('push', 8080);
pushService.setServicePath('/push/rest');
env.addService(pushService);

var dbService = new Service('db', 27017);
dbService.setScheme(env.SCHEMES.MONGO);
dbService.setServicePath('/');
dbService.setInternalHostname('db1');
dbService.setUsingAuthProxy(false);
env.addService(dbService);
<commit_msg>NTFY-87 Add the Scheduling service.<commit_after>//Trying out a more friendly and dynamic configuration utility.  Currently being
//used mainly for mocha tests but could potentially replace our older config.js
//going forward.

function Environment() {

    this.SCHEMES = {
        HTTP: 'http',
        HTTPS: 'https',
        WEBSOCKET: 'ws',
        MONGO: 'mongodb'
    };
    this.defaultScheme = this.SCHEMES.HTTP;

    this.HOSTNAMES = {
        LOCALHOST: 'localhost',
        DOCKER_LOCAL: '192.168.99.100',
        DEV: 'dev.voyent.cloud',
        PROD: 'api.voyent.cloud',
        INTERNAL_PROXY: 'web1'
    };
    this.hostname = process.env.VOYENT_HOST || this.HOSTNAMES.DOCKER_LOCAL;

    this.useAuthProxy = false;
    this.useInternalProxy = this.hostname !== this.HOSTNAMES.DOCKER_LOCAL;

    this.services = {};
}

Environment.prototype.isLocalhost = function () {
    return this.hostname === this.HOSTNAMES.LOCALHOST;
};

Environment.prototype.isLocalDocker = function () {
    return this.hostname === this.HOSTNAMES.DOCKER_LOCAL;
};

Environment.prototype.isProduction = function () {
    return process.env.NODE_ENV === 'production';
};

Environment.prototype.getHostname = function () {
    return this.hostname;
};

Environment.prototype.setHostname = function (hostname) {
    this.hostname = hostname;
};

Environment.prototype.usingAuthProxy = function () {
    return this.useAuthProxy;
};

Environment.prototype.setUsingAuthProxy = function (useAuthProxy) {
    this.useAuthProxy = useAuthProxy;
};

Environment.prototype.addService = function (service) {
    this.services[service.getName()] = service;
};

Environment.prototype.getService = function (name) {
    return this.services[name];
};

var env = new Environment();
module.exports = env;

function Service(name, servicePort) {
    this.name = name;
    this.servicePort = servicePort || 80;
    this.scheme = env.defaultScheme;
    this.internalProxy = env.HOSTNAMES.INTERNAL_PROXY;
}

Service.prototype.getName = function () {
    return this.name;
};

Service.prototype.getScheme = function () {
    return this.scheme;
};

Service.prototype.setScheme = function (scheme) {
    this.scheme = scheme;
};

Service.prototype.usingAuthProxy = function () {
    if(this.useAuthProxy === true || this.useAuthProxy === false){
        return this.useAuthProxy;
    }
    return env.usingAuthProxy();
};

Service.prototype.setUsingAuthProxy = function (useAuthProxy) {
    this.useAuthProxy = useAuthProxy;
};

Service.prototype.getHostname = function () {
    if (this.hostname) {
        return this.hostname;
    }

    return env.getHostname();
};

Service.prototype.setHostname = function (hostname) {
    this.hostname = hostname;
};

Service.prototype.getInternalHostname = function () {

    if (env.isLocalhost()) {
        return env.HOSTNAMES.LOCALHOST;
    }

    if (this.internalHostname) {
        return this.internalHostname;
    }

    return env.HOSTNAMES.INTERNAL_PROXY;
};

Service.prototype.setInternalHostname = function (internalHostname) {
    this.internalHostname = internalHostname;
};

Service.prototype.getServicePort = function () {

    if (env.isLocalhost()) {

        if (this.usingAuthProxy()) {
            return env.services.proxy.servicePort;
        }
    }

    return this.servicePort;
};

Service.prototype.setServicePort = function (servicePort) {
    this.servicePort = servicePort;
};

Service.prototype.getServicePath = function () {
    if (this.servicePath) {
        if (this.servicePath === '/') {
            return '';
        }
        return this.servicePath;
    }
    return '/' + this.name;
};

Service.prototype.getServicePathForRealm = function (account, realm) {
    return this.getServicePath() + '/' + account + '/realms/' + realm;
};

Service.prototype.setServicePath = function (servicePath) {
    this.servicePath = servicePath;
};

Service.prototype.getReferrer = function () {
    return this.getScheme() + '://' + this.getHostname();
};

Service.prototype.getExternalHost = function () {
    var thePort = this.getServicePort();
    var theHostname = this.getHostname();
    var theHost = this.getScheme() + '://' + this.getHostname();
    if (thePort === 80 || theHostname !== env.HOSTNAMES.LOCALHOST) {
        return theHost;
    }

    return theHost + ':' + thePort;
};

Service.prototype.getInternalHost = function () {
    var thePort = this.getServicePort();
    var theHostname = this.getInternalHostname();
    var theHost = this.getScheme() + '://' + this.getInternalHostname();
    if (thePort === 80 || theHostname === env.HOSTNAMES.INTERNAL_PROXY) {
        return theHost;
    }

    return theHost + ':' + thePort;
};

Service.prototype.getExternalURL = function () {
    return this.getExternalHost() + this.getServicePath();
};

Service.prototype.getInternalURL = function () {
    return this.getInternalHost() + this.getServicePath();
};

Service.prototype.getExternalURLForRealm = function (account, realm) {
    return this.getExternalHost() + this.getServicePathForRealm(account, realm);
};

Service.prototype.getInternalURLForRealm = function (account, realm) {
    return this.getInternalHost() + this.getServicePathForRealm(account, realm);
};

var proxyService = new Service('proxy', 55010);
proxyService.setServicePath('/');
env.addService(proxyService);

var authService = new Service('auth', 55010);
env.addService(authService);

var authAdminService = new Service('authadmin', 55010);
env.addService(authAdminService);

var locateService = new Service('locate', 55020);
env.addService(locateService);

var contextService = new Service('context', 55060);
env.addService(contextService);

var docsService = new Service('docs', 55080);
env.addService(docsService);

var schedulingService = new Service('scheduling', 55080);
env.addService(schedulingService);

var pushService = new Service('push', 8080);
pushService.setServicePath('/push/rest');
env.addService(pushService);

var dbService = new Service('db', 27017);
dbService.setScheme(env.SCHEMES.MONGO);
dbService.setServicePath('/');
dbService.setInternalHostname('db1');
dbService.setUsingAuthProxy(false);
env.addService(dbService);
<|endoftext|>


<commit_before>function HostDetailsControl($scope, $routeParams, $location, resourcesService, authService, statsService) {
    // Ensure logged in
    authService.checkLogin($scope);

    $scope.name = "hostdetails";
    $scope.params = $routeParams;

    $scope.visualization = zenoss.visualization;
    $scope.visualization.url = $location.protocol() + "://" + $location.host() + ':' + $location.port();
    $scope.visualization.urlPath = '/metrics/static/performance/query/';
    $scope.visualization.urlPerformance = '/metrics/api/performance/query/';
    $scope.visualization.debug = false;

    $scope.breadcrumbs = [
        { label: 'breadcrumb_hosts', url: '#/hosts' }
    ];

    // Also ensure we have a list of hosts
    refreshHosts($scope, resourcesService, true);

    $scope.running = buildTable('Name', [
        { id: 'Name', name: 'running_tbl_running' },
        { id: 'StartedAt', name: 'running_tbl_start' },
        { id: 'View', name: 'running_tbl_actions' }
    ]);

    $scope.ip_addresses = buildTable('Interface', [
        { id: 'Interface', name: 'ip_addresses_interface' },
        { id: 'Ip', name: 'ip_addresses_ip' }
    ]);

    $scope.graph = buildTable('Name', [
        { id: 'CPU', name: 'graph_tbl_cpu'},
        { id: 'Memory', name: 'graph_tbl_mem'}
    ]);

    $scope.viewConfig = function(running) {
        $scope.editService = $.extend({}, running);
        $scope.editService.config = 'TODO: Implement';
        $('#editConfig').modal('show');
    };

    $scope.viewLog = function(running) {
        $scope.editService = $.extend({}, running);
        resourcesService.get_service_state_logs(running.ServiceID, running.Id, function(log) {
            $scope.editService.log = log.Detail;
            $('#viewLog').modal('show');
        });
    };

    $scope.click_app = function(instance) {
        $location.path('/services/' + instance.ServiceID);
    };

    $scope.killRunning = function(running) {
        resourcesService.kill_running(running.HostID, running.Id, function() {
            refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
        });
    };

    refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
    refreshHosts($scope, resourcesService, true, function() {
        if ($scope.hosts.current) {
            $scope.breadcrumbs.push({ label: $scope.hosts.current.Name, itemClass: 'active' });
        }
    });

    statsService.is_collecting(function(status) {
        if (status == 200) {
            $scope.collectingStats = true;
        } else {
            $scope.collectingStats = false;
        }
    });

    $scope.cpuconfig = function( hostId) {
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "color": "#aec7e8",
                  "expression": null,
                  "fill": false,
                  "format": "%6.2f",
                  "id": "system",
                  "legend": "CPU (System)",
                  "metric": "CpuacctStat.system",
                  "name": "CPU (System)",
                  "rate": true,
                  "rateOptions": {},
                  "type": "line"
              },
              {
                  "aggregator": "avg",
                  "color": "#98df8a",
                  "expression": null,
                  "fill": false,
                  "format": "%6.2f",
                  "id": "user",
                  "legend": "CPU (User)",
                  "metric": "CpuacctStat.user",
                  "name": "CPU (User)",
                  "rate": true,
                  "rateOptions": {},
                  "type": "line"
              }
          ],
          "footer": false,
          "format": "%6.2f",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "returnset": "EXACT",
          "tags": {
            "controlplane_host_id": [hostId]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    $scope.ofdconfig = function (hostId) {
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "color": "#aec7e8",
                  "expression": null,
                  "fill": false,
                  "format": "%6.2f",
                  "id": "ofd",
                  "legend": "Serviced Open File Descriptors",
                  "metric": "Serviced.OpenFileDescriptors",
                  "name": "Serviced Open File Descriptors",
                  "rate": false,
                  "rateOptions": {},
                  "type": "line"
              },
          ],
          "footer": false,
          "format": "%d",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "returnset": "EXACT",
          "tags": {
            "controlplane_host_id": [hostId]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    $scope.memconfig = function( hostId) {
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "color": "#aec7e8",
                  "expression": null,
                  "expression": null,
                  "fill": false,
                  "format": "%d",
                  "id": "pgfault",
                  "legend": "Page Faults",
                  "metric": "MemoryStat.pgfault",
                  "name": "Page Faults",
                  "rate": true,
                  "rateOptions": {},
                  "type": "line"
              }
          ],
          "footer": false,
          "format": "%6.2f",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "returnset": "EXACT",
          "tags": {
            "controlplane_host_id": [hostId]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    $scope.rssconfig = function( hostId){
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "expression": "rpn:1024,/,1024,/",
                  "fill": false,
                  "format": "%6.2f",
                  "id": "rssmemory",
                  "legend": "RSS Memory",
                  "metric": "MemoryStat.rss",
                  "name": "RSS Memory",
                  "rateOptions": {},
                  "type": "line",
                  "fill": true
              }
          ],
          "footer": false,
          "format": "%6.2f",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "yAxisLabel": "MB",
          "returnset": "EXACT",
          height: 300,
          width: 300,
          "tags": {
            "controlplane_host_id": [hostId]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    // XXX prevent the graphs from being drawn multiple times
    //     by angular's processing engine
    $scope.drawn = {};

    //id: div id prefix for drawing graph
    //config: generator for graph config using hostId
    $scope.viz = function(id, config) {

        // XXX angular renders the host details page prior
        //     to the call to refreshHosts.  angular will
        //     also render after refreshHosts is called
        if ($scope.hosts.current === undefined) {
          return
        }

        //create unique configs and ids for the current host
        var _config = config( $scope.hosts.current.ID)

        // _id must align with a div for the graph
        var _id = id + '-' + $scope.hosts.current.ID

        if (!$scope.drawn[_id]) {
            if (window.zenoss === undefined) {
                return "Not collecting stats, graphs unavailable";
            } else {
                zenoss.visualization.chart.create(_id, _config);
                $scope.drawn[_id] = true;
            }
        }
    };
}
<commit_msg>pass in host to graph config generators<commit_after>function HostDetailsControl($scope, $routeParams, $location, resourcesService, authService, statsService) {
    // Ensure logged in
    authService.checkLogin($scope);

    $scope.name = "hostdetails";
    $scope.params = $routeParams;

    $scope.visualization = zenoss.visualization;
    $scope.visualization.url = $location.protocol() + "://" + $location.host() + ':' + $location.port();
    $scope.visualization.urlPath = '/metrics/static/performance/query/';
    $scope.visualization.urlPerformance = '/metrics/api/performance/query/';
    $scope.visualization.debug = false;

    $scope.breadcrumbs = [
        { label: 'breadcrumb_hosts', url: '#/hosts' }
    ];

    // Also ensure we have a list of hosts
    refreshHosts($scope, resourcesService, true);

    $scope.running = buildTable('Name', [
        { id: 'Name', name: 'running_tbl_running' },
        { id: 'StartedAt', name: 'running_tbl_start' },
        { id: 'View', name: 'running_tbl_actions' }
    ]);

    $scope.ip_addresses = buildTable('Interface', [
        { id: 'Interface', name: 'ip_addresses_interface' },
        { id: 'Ip', name: 'ip_addresses_ip' }
    ]);

    $scope.graph = buildTable('Name', [
        { id: 'CPU', name: 'graph_tbl_cpu'},
        { id: 'Memory', name: 'graph_tbl_mem'}
    ]);

    $scope.viewConfig = function(running) {
        $scope.editService = $.extend({}, running);
        $scope.editService.config = 'TODO: Implement';
        $('#editConfig').modal('show');
    };

    $scope.viewLog = function(running) {
        $scope.editService = $.extend({}, running);
        resourcesService.get_service_state_logs(running.ServiceID, running.Id, function(log) {
            $scope.editService.log = log.Detail;
            $('#viewLog').modal('show');
        });
    };

    $scope.click_app = function(instance) {
        $location.path('/services/' + instance.ServiceID);
    };

    $scope.killRunning = function(running) {
        resourcesService.kill_running(running.HostID, running.Id, function() {
            refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
        });
    };

    refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
    refreshHosts($scope, resourcesService, true, function() {
        if ($scope.hosts.current) {
            $scope.breadcrumbs.push({ label: $scope.hosts.current.Name, itemClass: 'active' });
        }
    });

    statsService.is_collecting(function(status) {
        if (status == 200) {
            $scope.collectingStats = true;
        } else {
            $scope.collectingStats = false;
        }
    });

    $scope.cpuconfig = function( host) {
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "color": "#aec7e8",
                  "expression": null,
                  "fill": false,
                  "format": "%6.2f",
                  "id": "system",
                  "legend": "CPU (System)",
                  "metric": "CpuacctStat.system",
                  "name": "CPU (System)",
                  "rate": true,
                  "rateOptions": {},
                  "type": "line"
              },
              {
                  "aggregator": "avg",
                  "color": "#98df8a",
                  "expression": null,
                  "fill": false,
                  "format": "%6.2f",
                  "id": "user",
                  "legend": "CPU (User)",
                  "metric": "CpuacctStat.user",
                  "name": "CPU (User)",
                  "rate": true,
                  "rateOptions": {},
                  "type": "line"
              }
          ],
          "footer": false,
          "format": "%6.2f",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "returnset": "EXACT",
          "tags": {
            "controlplane_host_id": [host.ID]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    $scope.ofdconfig = function (host) {
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "color": "#aec7e8",
                  "expression": null,
                  "fill": false,
                  "format": "%6.2f",
                  "id": "ofd",
                  "legend": "Serviced Open File Descriptors",
                  "metric": "Serviced.OpenFileDescriptors",
                  "name": "Serviced Open File Descriptors",
                  "rate": false,
                  "rateOptions": {},
                  "type": "line"
              },
          ],
          "footer": false,
          "format": "%d",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "returnset": "EXACT",
          "tags": {
            "controlplane_host_id": [host.ID]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    $scope.memconfig = function( host) {
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "color": "#aec7e8",
                  "expression": null,
                  "expression": null,
                  "fill": false,
                  "format": "%d",
                  "id": "pgfault",
                  "legend": "Page Faults",
                  "metric": "MemoryStat.pgfault",
                  "name": "Page Faults",
                  "rate": true,
                  "rateOptions": {},
                  "type": "line"
              }
          ],
          "footer": false,
          "format": "%6.2f",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "returnset": "EXACT",
          "tags": {
            "controlplane_host_id": [host.ID]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    $scope.rssconfig = function( host){
      return {
          "datapoints": [
              {
                  "aggregator": "avg",
                  "expression": "rpn:1024,/,1024,/",
                  "fill": false,
                  "format": "%6.2f",
                  "id": "rssmemory",
                  "legend": "RSS Memory",
                  "metric": "MemoryStat.rss",
                  "name": "RSS Memory",
                  "rateOptions": {},
                  "type": "line",
                  "fill": true
              }
          ],
          "footer": false,
          "format": "%6.2f",
          "maxy": null,
          "miny": 0,
          "range": {
              "end": "0s-ago",
              "start": "1h-ago"
          },
          "yAxisLabel": "MB",
          "returnset": "EXACT",
          height: 300,
          width: 300,
          "tags": {
            "controlplane_host_id": [host.ID]
          },
          "type": "line",
          "downsample": "1m-avg",
          "timezone": jstz.determine().name()
      };
    }

    // XXX prevent the graphs from being drawn multiple times
    //     by angular's processing engine
    $scope.drawn = {};

    //id: div id prefix for drawing graph
    //config: generator for graph config using hostId
    $scope.viz = function(id, config) {

        // XXX angular renders the host details page prior
        //     to the call to refreshHosts.  angular will
        //     also render after refreshHosts is called
        if ($scope.hosts.current === undefined) {
          return
        }

        //create unique configs and ids for the current host
        var _config = config( $scope.hosts.current)

        // _id must align with a div for the graph
        var _id = id + '-' + $scope.hosts.current.ID

        if (!$scope.drawn[_id]) {
            if (window.zenoss === undefined) {
                return "Not collecting stats, graphs unavailable";
            } else {
                zenoss.visualization.chart.create(_id, _config);
                $scope.drawn[_id] = true;
            }
        }
    };
}
<|endoftext|>


<commit_before>import React from 'react'

function ConnectionBanner(props){
  switch(props.status){
    case "CONNECTED":
      return ()
    case "NOTCONNECTED":
    case "CLOSED":
      return (

              Reconnecting...

Snap! there was a connection problem. Trying to solve.

              Reconnecting...

      )
    case "CONNECTING":
    case "RECONNECT":
    case "RECONNECTING":
      return (

              Reconnecting in {props.extra/1000} seconds

Snap! there was a connection problem. Trying to solve.

              Reconnect now

      )
    case "WILL_NOT_RECONNECT":
      return (

              Too many errors reconnecting

I will not try to reconnect automatically. You can force reconnection if you will.

              Reconnect now

      )
    default:
      console.error("Unknown status at ConnectionBanner %o", props.status)
      return (

              Unknown connection status: {props.status}

Snap! there was a connection problem. Trying to solve.

              Reconnect now

      )
  }
}

export default ConnectionBanner
<commit_msg>Updated reconnect messages i18n<commit_after>import React from 'react'
import i18n from 'app/utils/i18n'

function ConnectionBanner(props){
  switch(props.status){
    case "CONNECTED":
      return ()
    case "NOTCONNECTED":
    case "CLOSED":
      return (

              {i18n("Reconnecting...")}

{i18n("Snap! there was a connection problem. Trying to solve.")}

              {i18n("Reconnecting...")}

      )
    case "CONNECTING":
    case "RECONNECT":
    case "RECONNECTING":
      return (

              {props.extra ? (
                {i18n("Reconnecting in {seconds} seconds", {seconds: props.extra/1000})}
              ) : (
                {i18n("Reconnecting soon...")}
              )}

{i18n("Snap! there was a connection problem. Trying to solve.")}

              {i18n("Reconnect now")}

      )
    case "WILL_NOT_RECONNECT":
      return (

              {i18n("Too many errors reconnecting")}

{i18n("I will not try to reconnect automatically. You can force reconnection if you will.")}

              {i18n("Reconnect now")}

      )
    default:
      console.error("Unknown status at ConnectionBanner %o", props.status)
      return (

              {i18n("Unknown connection status: {status}", {status: props.status})}

{i18n("Snap! there was a connection problem. Trying to solve.")}

              {i18n("Reconnect now")}

      )
  }
}

export default ConnectionBanner
<|endoftext|>


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

var $ = require;

var t = module.exports = function (client, name, callback) {
  var self = this;

  var domain = $('domain').create();

  domain.on('error', function (error) {
    callback(error);
  });

  domain.run(function () {

    client.hget(self.prefix + name, 'touched', domain.intercept(function (results) {
      if ( ! results ) {
        return callback();
      }
      client.hgetall(self.prefix + name, domain.intercept(function (results) {
        results.name = name;
        callback(null, results);
      }));
    }));
  });
};<commit_msg>cleaning code<commit_after>/**

  cache.get()
  ###########

  This script is supposed to be called via `index.js`

**/

module.exports = function (
/* RedisClient */ client,     // A Redis client
/* String */      name,       // The cache entry name to get
/* Function */    callback    // Callback
) {
  var self = this;

  var domain = require('domain').create();

  domain.on('error', function (error) {
    callback(error);
  });

  domain.run(function () {

    /* Get cache */
    client.hgetall(self.prefix + name, domain.intercept(function (results) {
      results.name = name;
      callback(null, results);
    }));

  });
};<|endoftext|>


<commit_before>import React, { useState, useEffect } from 'react'
import { Page } from 'app/styleguide/components/Page'
import TopBarContainer from '../../containers/topbar'
import Bottom from '../bottom/bottom'
import PropTypes from 'prop-types'
import { injectIntl, defineMessages } from 'react-intl'
import CustomPaginationActionsTable from './task-table'

import {
  Container,
  Grid,
  withStyles,
  Typography,
  Tab,
  Tabs,
  AppBar,
} from '@material-ui/core'

import {
  Redeem as RedeemIcon,
  MonetizationOn as MoneyIcon,
  SupervisedUserCircle as ContributionIcon,
} from '@material-ui/icons'
import ProfileHead from '../../containers/profile-head'

const styles = theme => ({
  rootTabs: {
    marginRight: theme.spacing(3),
    marginBottom: theme.spacing(3),
    backgroundColor: theme.palette.primary.light
  }
})

const messages = defineMessages({
  issuesCreated: {
    id: 'task.list.lable.issuesCreated',
    defaultMessage: 'All issues created'
  },
  issuesSupported: {
    id: 'task.list.lable.issuesSupported',
    defaultMessage: 'Issues supported'
  },
  issuesList: {
    id: 'task.list.lable.issuesList',
    defaultMessage: 'Issues list'
  },
})

const TaskListUser = (props) => {
  const { classes } = props

  const [taskListState, setTaskListState] = useState({
    tab: 0,
    loading: true,
  })

  const verifyUserId = () => {
    const userId = props.match.params.usernameId.split('-')[0]

    if (isNaN(userId)) {
      props.history.push('/')

      // eslint-disable-next-line
      return
    }

    return userId
  }

  const listTasksByUserId = () => {
    const userId = verifyUserId()
    props.listTasks({ userId: userId })
    props.filterTasks('all')
  }

  const filterTasksWithOrders = () => {
    props.filterTasks('supported')
  }

  function filterTasksByState () {
    const currentTab = taskListState.tab

    switch (currentTab) {
      case 0:
        listTasksByUserId()
        break
      case 1:
        filterTasksWithOrders()
        break
      case 2:
        break
      default:
    }
  }

  useEffect(() => {
    filterTasksByState()
  }, [taskListState.tab])

  const handleTabChange = async (event, value) => {
    setTaskListState({ ...taskListState, tab: value })
  }

  const TabContainer = props => {
    return (
      <Typography component='div' style={ { padding: 8 * 3 } }>
        { props.children }
      </Typography>
    )
  }

  return (
    <React.Fragment>
      <Page>
        <TopBarContainer />
        <Container fixed maxWidth='lg'>
          <ProfileHead />
        </Container>
        <Container fixed maxWidth='lg'>
          <Grid container className={ classes.root }>
            <Grid item xs={ 12 } md={ 12 }>

                <AppBar position='static' color='default'>
                  <Tabs
                    value={ taskListState.tab }
                    onChange={ handleTabChange }
                    scrollable
                    scrollButtons='on'
                    indicatorColor='primary'
                    textColor='primary'
                  >
                    <Tab
                      value={ 0 }
                      label={ props.intl.formatMessage(messages.issuesCreated) }
                      icon={ <RedeemIcon /> }
                    />
                    <Tab
                      value={ 1 }
                      label={ props.intl.formatMessage(messages.issuesSupported) }
                      icon={ <MoneyIcon /> }
                    />
                    <Tab
                      value={ 2 }
                      label={ props.intl.formatMessage(messages.issuesList) }
                      icon={ <ContributionIcon /> }
                    />
                  </Tabs>
                </AppBar>
                <TabContainer>
                  <CustomPaginationActionsTable tasks={ props.tasks } />
                </TabContainer>

            </Grid>
          </Grid>
        </Container>
        <Bottom classes={ classes } />
      </Page>
    </React.Fragment>
  )
}

TaskListUser.propTypes = {
  classes: PropTypes.object.isRequired
}

export default injectIntl(withStyles(styles)(TaskListUser))
<commit_msg>removing issues list as option for now (#862)<commit_after>import React, { useState, useEffect } from 'react'
import { Page } from 'app/styleguide/components/Page'
import TopBarContainer from '../../containers/topbar'
import Bottom from '../bottom/bottom'
import PropTypes from 'prop-types'
import { injectIntl, defineMessages } from 'react-intl'
import CustomPaginationActionsTable from './task-table'

import {
  Container,
  Grid,
  withStyles,
  Typography,
  Tab,
  Tabs,
  AppBar,
} from '@material-ui/core'

import {
  Redeem as RedeemIcon,
  MonetizationOn as MoneyIcon
} from '@material-ui/icons'
import ProfileHead from '../../containers/profile-head'

const styles = theme => ({
  rootTabs: {
    marginRight: theme.spacing(3),
    marginBottom: theme.spacing(3),
    backgroundColor: theme.palette.primary.light
  }
})

const messages = defineMessages({
  issuesCreated: {
    id: 'task.list.lable.issuesCreated',
    defaultMessage: 'All issues created'
  },
  issuesSupported: {
    id: 'task.list.lable.issuesSupported',
    defaultMessage: 'Issues supported'
  },
  issuesList: {
    id: 'task.list.lable.issuesList',
    defaultMessage: 'Issues list'
  },
})

const TaskListUser = (props) => {
  const { classes } = props

  const [taskListState, setTaskListState] = useState({
    tab: 0,
    loading: true,
  })

  const verifyUserId = () => {
    const userId = props.match.params.usernameId.split('-')[0]

    if (isNaN(userId)) {
      props.history.push('/')

      // eslint-disable-next-line
      return
    }

    return userId
  }

  const listTasksByUserId = () => {
    const userId = verifyUserId()
    props.listTasks({ userId: userId })
    props.filterTasks('all')
  }

  const filterTasksWithOrders = () => {
    props.filterTasks('supported')
  }

  function filterTasksByState () {
    const currentTab = taskListState.tab

    switch (currentTab) {
      case 0:
        listTasksByUserId()
        break
      case 1:
        filterTasksWithOrders()
        break
      case 2:
        break
      default:
    }
  }

  useEffect(() => {
    filterTasksByState()
  }, [taskListState.tab])

  const handleTabChange = async (event, value) => {
    setTaskListState({ ...taskListState, tab: value })
  }

  const TabContainer = props => {
    return (
      <Typography component='div' style={ { padding: 8 * 3 } }>
        { props.children }
      </Typography>
    )
  }

  return (
    <React.Fragment>
      <Page>
        <TopBarContainer />
        <Container fixed maxWidth='lg'>
          <ProfileHead />
        </Container>
        <Container fixed maxWidth='lg'>
          <Grid container className={ classes.root }>
            <Grid item xs={ 12 } md={ 12 }>

                <AppBar position='static' color='default'>
                  <Tabs
                    value={ taskListState.tab }
                    onChange={ handleTabChange }
                    scrollable
                    scrollButtons='on'
                    indicatorColor='primary'
                    textColor='primary'
                  >
                    <Tab
                      value={ 0 }
                      label={ props.intl.formatMessage(messages.issuesCreated) }
                      icon={ <RedeemIcon /> }
                    />
                    <Tab
                      value={ 1 }
                      label={ props.intl.formatMessage(messages.issuesSupported) }
                      icon={ <MoneyIcon /> }
                    />
                  </Tabs>
                </AppBar>
                <TabContainer>
                  <CustomPaginationActionsTable tasks={ props.tasks } />
                </TabContainer>

            </Grid>
          </Grid>
        </Container>
        <Bottom classes={ classes } />
      </Page>
    </React.Fragment>
  )
}

TaskListUser.propTypes = {
  classes: PropTypes.object.isRequired
}

export default injectIntl(withStyles(styles)(TaskListUser))
<|endoftext|>


<commit_before>// @flow

import React, { useCallback, useContext } from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import { BridgeContext, StoreContext } from '../context';

export default function ReloadAndProfileButton() {
  const bridge = useContext(BridgeContext);
  const store = useContext(StoreContext);

  const reloadAndProfile = useCallback(() => bridge.send('reloadAndProfile'), [
    bridge,
  ]);

  if (!store.supportsReloadAndProfile) {
    return null;
  }

  return (
    <Button onClick={reloadAndProfile} title="Reload and start profiling">
      <ButtonIcon type="reload" />
    </Button>
  );
}
<commit_msg>Disable reload-and-profile button if no renderers support profiling<commit_after>// @flow

import React, { useCallback, useContext } from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import { BridgeContext, StoreContext } from '../context';

export default function ReloadAndProfileButton() {
  const bridge = useContext(BridgeContext);
  const store = useContext(StoreContext);

  const reloadAndProfile = useCallback(() => bridge.send('reloadAndProfile'), [
    bridge,
  ]);

  if (!store.supportsReloadAndProfile) {
    return null;
  }

  return (
    <Button
      disabled={!store.supportsProfiling}
      onClick={reloadAndProfile}
      title="Reload and start profiling"
    >
      <ButtonIcon type="reload" />
    </Button>
  );
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('fs');

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var baseConfig = require('./webpack.config.base.js');
var config = Object.assign({}, baseConfig);

var HTTP_PORT = 3000;

config.entry = {
    'index': './example/index.js',
    'loader-amd': './example/loader/loader-amd.js',
    'loader-standalone': './example/loader/loader-standalone.js',
    'loader-systemjs': './example/loader/loader-systemjs.js',
    'address-selector': './example/address-selector/index.js',
    'list': './example/list/index.js',
    'list-plusplus': './example/list-plusplus/index.js',
    'grid': './example/grid/index.js',
    'templator': './example/templator/index.js',
    'form': './example/form/index.js',
    'todo-app': './example/todo-app/index.js',
    'weather-app': './example/weather-app/index.js'
};

config.output = {
    path: path.join(__dirname, '_book/live'),
    filename: '[name].js'
};

config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.CommonsChunkPlugin('commons', 'commons.js'),
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('development')
    })
];

Object.keys(config.entry).forEach(function (chunk, i, all) {
    config.plugins.push(new HtmlWebpackPlugin({
        all: all,
        title: chunk,
        template: './example/template.ejs',
        inject: 'head',
        chunks: ['commons', chunk],
        filename: chunk + '.html'
    }));
});

config.devServer = {
    noInfo: false,
    hot: true,
    inline: true,
    host: '0.0.0.0',
    port: HTTP_PORT,
    watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
    }
};

module.exports = config;
<commit_msg>deactivate weather-map due none support of https<commit_after>'use strict';

var path = require('path');
var fs = require('fs');

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var baseConfig = require('./webpack.config.base.js');
var config = Object.assign({}, baseConfig);

var HTTP_PORT = 3000;

config.entry = {
    'index': './example/index.js',
    'loader-amd': './example/loader/loader-amd.js',
    'loader-standalone': './example/loader/loader-standalone.js',
    'loader-systemjs': './example/loader/loader-systemjs.js',
    'address-selector': './example/address-selector/index.js',
    'list': './example/list/index.js',
    'list-plusplus': './example/list-plusplus/index.js',
    'grid': './example/grid/index.js',
    'templator': './example/templator/index.js',
    'form': './example/form/index.js',
    'todo-app': './example/todo-app/index.js'/*,
    'weather-app': './example/weather-app/index.js'*/
};

config.output = {
    path: path.join(__dirname, '_book/live'),
    filename: '[name].js'
};

config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.CommonsChunkPlugin('commons', 'commons.js'),
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('development')
    })
];

Object.keys(config.entry).forEach(function (chunk, i, all) {
    config.plugins.push(new HtmlWebpackPlugin({
        all: all,
        title: chunk,
        template: './example/template.ejs',
        inject: 'head',
        chunks: ['commons', chunk],
        filename: chunk + '.html'
    }));
});

config.devServer = {
    noInfo: false,
    hot: true,
    inline: true,
    host: '0.0.0.0',
    port: HTTP_PORT,
    watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
    }
};

module.exports = config;
<|endoftext|>