Inspired by https://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json/4816258
327916
function simpleStringify (object) {
	var simpleObject = {};
	for (var prop in object) {
		if (!object.hasOwnProperty(prop) ||
			typeof(object[prop]) === 'function') {
			continue;
		}
		simpleObject[prop] = object[prop];
	}
	return JSON.stringify(simpleObject, censor(simpleObject),2);
}
1061519
function serveRemoteJson(request, response, next) {
	if (request.path !== '/remote') {
		return next();
	}
	var options = {
		url: request.query.url,
		headers: request.query.headers
	};
	var error;

	if (!options.url || typeof options.url !== 'string') {
		error = new Error('Invalid query parameter: url');
		error.status = 400;
		return next(error);
	}

	if (options.headers && typeof options.headers !== 'string') {
		error = new Error('Invalid query parameter: headers');
		error.status = 400;
		return next(error);
	}

	options.headers = parseHeaders(options.headers);

	loadRemoteJson(options, function (error, json) {
		if (error) {
			return next(error);
		}
		response.writeHead(200, {
			'Content-Type': 'application/x-shunter+json'
		});
		response.end(JSON.stringify(json, null, 4));
	});
}
899306
function (request, xhr, callback) {

            var model = request.model;

            var cb = function (err) {
                if (callback) {
                    callback(err, model, request.options);
                }
            };

            var self = this;

            try { // get location header
                var location = xhr.getResponseHeader('Location');

                if (location) {

                    if (self._parsePayloadOnCreate(request, xhr)) {
                        self._parseModelPayload(xhr, model, request.options);
                    }

                    // extract id
                    var id = this.extractIdFromLocation(location, request);

                    if (id || id === 0) {
                        model.set(model.idField, id);
                        if (model.hrefField) {
                            model.set(model.hrefField, location);
                        }
                        var schema = model.schema, schemaType;
                        for (var schemaKey in schema) {
                            if (schema.hasOwnProperty(schemaKey)) {
                                schemaType = schema[schemaKey];
                                if (schemaType.classof && schemaType.classof(Collection)) {
                                    var contextForChildren = model.getContextForChild(schemaType);
                                    model.set(schemaKey, contextForChildren.createCollection(schemaType, null));
                                }

                            }
                        }

                        model.$context.addEntityToCache(model);

                        // TODO: ask processor if i should call save again to put content
                        cb(null);
                    } else {
                        cb("Id couldn't be extracted");
                    }

                } else {
                    cb('Location header not found');
                }

            } catch (e) {
                cb(e || true);
            }
        }
982234
function(link, cb){
            var options = {
                host: urlArr.hostname,
                port: urlArr.port,
                path: urlArr.path+"?link="+encodeURIComponent(link),
                method: 'GET'
            };
            
            var getRequest = protocol.request(options, function(res){
                var result = "";
                
                if(res.statusCode === 200){
                    res.on('error', function(error) {
                        if(typeof cb === "function")
                            cb(error);
                    });

                    res.on('data', function (chunk) {
                        result += chunk;
                    });

                    res.on('end', function (chunk) {
                        if(typeof cb === "function"){
                            var resultObj = JSON.parse(result);
                            var err = (resultObj.status === "error") ? resultObj["msg"] : null
                            cb(err, resultObj);
                        }                        
                    });
                }
                else{
                    if(typeof cb === "function")
                        cb("Request return HTTP "+res.statusCode);
                }
            });
            
            getRequest.end();
        }
363617
function toText (obj) {
  if (obj instanceof Error) {
    return {
      isJSON: false,
      text: obj.message + "\n\n" + obj.stack
    };
  }
  else {
    try {
      return {
        isJSON: true,
        text: JSON.stringify(obj, null, 2)
      };
    }
    catch (e) {
      return {
        isJSON: false,
        text: "This API is valid, but it cannot be shown because it contains circular references\n\n" + e.stack
      };
    }
  }
}
515666
function sendJson(data, options, callback) {
  var jsonData = JSON.stringify(data);
  return this.send(jsonData, options, callback);
}
1233029
function(path, callbackSuccess, callbackError) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        callbackSuccess(xhr.responseText);
      } else {
        callbackError();
      }
    }
  };
  xhr.open('GET', path, false);
  try {
    xhr.send();
  } catch (e) {
    callbackError();
  }
}
1013458
function() {
      var delay = Math.random() * 20000;
      var sendTopic = allTopics[Math.floor(Math.random() * allTopics.length)];
      var sendCallback = function(err, msg) {
        if (err) {
          console.error('Problem with send request: ' + err.toString());
          process.exit(0);
        } else {
          if (messageCount === 0) {
            console.log('Sending messages');
          }
          ++messageCount;
          if (messageCount % 10 === 0) {
            console.log('Sent ' + messageCount + ' messages');
          }
        }
      };

      setTimeout(function() {
        var start = Math.floor(Math.random() * (loremIpsumWords.length - 15));
        var end = start + 5 + Math.floor(Math.random() * 10);
        var message =
            loremIpsum.substring(loremIpsumWords[start], loremIpsumWords[end]);
        client.send(sendTopic, message, sendCallback);
        sendMessages();
      },delay);
    }
1198280
function requestHandler(req, res, next) {
  const start = Date.now();
  let source;

  return Promise.try(() => {
    source = core.getPublicSource(req.params.src);
    return source.getHandler().getInfoAsync().then(info => [info, infoHeaders]);
  }).spread((data, dataHeaders) => {
    core.setResponseHeaders(res, source, dataHeaders);

    if (req.query && req.query.format) {
      const escapedText = JSON.stringify(data, null, ' ').replace(/&/g, '&amp;').replace(/</g, '&lt;');
      res.send(`<pre>${escapedText}</pre>`);
    } else {
      res.json(data);
    }

    const mx = util.format('req.%s.info', req.params.src);
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
725603
function get ( url, async, cb, cbError ) {
        var data,
            request = new XMLHttpRequest;

        request.open( 'GET', url, async );

        request.onload = function () {
            if ( this.status >= 200 && this.status < 400 ) {
                // Success!
                data = this.response;
            } else {
                // We reached our target server, but it returned an error. Most likely, the bower.json file is missing.
                // We just return undefined here.
                data = undefined;
            }
            cb( data );
        };

        request.onerror = function ( err ) {
            // There was a connection error of some sort.
            if ( cbError ) cbError( err );
        };

        request.send();
    }
979904
function RequestBase () {
    // `_baseUrl` and `self` are private variables
    var _baseUrl,
        self = this;

    this.getBaseUrl = function () {
      if (_baseUrl) {
        return _baseUrl;
      }
    };

    this.setBaseUrl = function (baseUrl) {
      _baseUrl = baseUrl;
    };

    /**
     * Checks to make sure the request was a success
     * @param  {Object}  res   A response object
     * @return {Boolean}       A boolean denoting whether the request was a success
     */
    this.isSuccess = function (res) {
      var success = function (status) {
        return status >= 200 && status < 300;
      };
      if (res && success(res.statusCode)) {
        return true;
      }
      return false;
    };

    this.buildOptions = function (path, method, payload) {
      var options,
          accessToken = this.getAccessToken(),
          relayIdentifier = this.getRelayIdentifier(),
          baseUrl = self.getBaseUrl(),
          url = self.constructUrl(baseUrl, path);

      options = {
        uri: url,
        method: method,
        headers: {}
      };

      if (accessToken) {
        options.headers.Authorization = 'Access-Token ' + accessToken;
      } else {
        throw new Error('The required Access Token is missing or malformed');
      }

      if (relayIdentifier) {
        options.headers['Relay-Identifier'] = relayIdentifier;
      }

      if (method && method.toUpperCase() === 'GET') {
        options.qs = payload;
      } else {
        options.json = payload;
      }
      return options;
    };

    this.constructUrl = function (url, path) {
      if (url.slice(-1) === '/' && path.slice(0, 1) === '/') {
        return url.slice(0, -1) + path;
      } else if (url.slice(-1) !== '/' && path.slice(0, 1) !== '/') {
        return url + '/' + path;
      }
      return url + path;
    };

    this.sendRequest = function (path, method, payload) {
      var options = self.buildOptions(path, method, payload),
          reqHandle = request(options).spread(function (response, body) {
            var resp = {},
                responseBody;
            try {
              if (typeof body === 'string') {
                responseBody = JSON.parse(body);
              } else {
                responseBody = body;
              }
            } catch (err) {
              throw new Error('An error occurred parsing the following response from the server: ' + body);
            }
            resp.body = responseBody;
            if (self.isSuccess(response)) {
              resp.getData = function () {
                return resp.body.data;
              };
              resp.isEmpty = function () {
                return Object.getOwnPropertyNames(resp.getData()).length === 0;
              };
              resp.getDataLength = function () {
                var data = resp.getData();
                if (resp.isEmpty()) {
                  return 0;
                } else if (!(data instanceof Array)) {
                  return 1;
                } else {
                  return data.length;
                }
              };
              if (method === 'GET' && resp.body.paging) {
                var pageSize, thisPage, prevPage, nextPage, pageFunc;
                pageSize = resp.body.paging['per_page'];
                thisPage = resp.body.paging.page;
                prevPage = (thisPage === 1 ? thisPage : thisPage - 1);
                nextPage = thisPage + 1;
                pageFunc = function (pageNum) {
                  var _pageNum;
                  _pageNum = pageNum;
                  return function () {
                    payload = (payload === undefined || !payload) ? {} : payload;
                    payload.page = _pageNum;
                    payload['per_page'] = pageSize;
                    return self.sendRequest(path, method, payload);
                  };
                };
                resp.nextPage = pageFunc(nextPage);
                resp.prevPage = pageFunc(prevPage);
              }
              return resp;
            } else {
              throw new error.ApiError(resp);
            }
          });
      return reqHandle;
    };
  }
706126
function RAgent_send(name, body, cb) {
  if (!this._session) return

  var reqID = this._nextReqID()

  this._requestCBs.set(reqID, cb)

  var message = {
    type: "request",
    name: name,
    to:   this.info.id,
    id:   reqID,
    body: body
  }

  this._session._sendMessage(message)
}
1154957
function connectionToJson(object) {
        var pointerNames = theCore.getPointerNames(object);
        var src = null;
        var dst = null;
        if (pointerNames.indexOf('source') !== -1) {
            src = theCore.loadPointer(object, 'source');
        }
        if (pointerNames.indexOf('target') !== -1) {
            dst = theCore.loadPointer(object, 'target');
        }
        return TASYNC.call(function (s, d) {
            var jsonObject = initJsonObject(object);
            if (s !== null) {
                if (theCore.getRegistry(s, 'metameta') === 'refport') {
                    var sA = theCore.getParent(s);
                    jsonObject._children.push({
                        _type: 'connpoint',
                        _empty: true,
                        _attr: {
                            role: "src",
                            target: theCore.getRegistry(s, 'id'),
                            refs: theCore.getRegistry(sA, 'id')
                        }
                    });
                } else {
                    jsonObject._children.push({
                        _type: 'connpoint',
                        _empty: true,
                        _attr: {
                            role: "src",
                            target: theCore.getRegistry(s, 'id')
                        }
                    });
                }
            }
            if (d !== null) {
                if (theCore.getRegistry(d, 'metameta') === 'refport') {
                    var dA = theCore.getParent(d);
                    jsonObject._children.push({
                        _type: 'connpoint',
                        _empty: true,
                        _attr: {
                            role: "dst",
                            target: theCore.getRegistry(d, 'id'),
                            refs: theCore.getRegistry(dA, 'id')
                        }
                    });
                } else {
                    jsonObject._children.push({
                        _type: 'connpoint',
                        _empty: true,
                        _attr: {
                            role: "dst",
                            target: theCore.getRegistry(d, 'id')
                        }
                    });
                }
            }
            return jsonObject;
        }, src, dst);
    }
771844
function stringify(obj) {
    var cache = [];

    return JSON.stringify(obj, function (key, value) {
        if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                return '[Circular]';
            }
            cache.push(value);
        }
        return value;
    });
}
271099
async function _json(req, res) {
  const { queueName, queueHost, state } = req.params;
  const {Queues} = req.app.locals;
  const queue = await Queues.get(queueName, queueHost);
  if (!queue) return res.status(404).json({ message: 'Queue not found' });

  if (!isValidState(state, queue.IS_BEE)) return res.status(400).json({ message: `Invalid state requested: ${state}` });

  let jobs;
  if (queue.IS_BEE) {
    jobs = await queue.getJobs(state, { size: 1000 });
    jobs = jobs.map((j) => _.pick(j, 'id', 'progress', 'data', 'options', 'status'));
  } else {
    jobs = await queue[`get${_.capitalize(state)}`](0, 1000);
    jobs = jobs.map((j) => j.toJSON());
  }

  const filename = `${queueName}-${state}-dump.json`;

  res.setHeader('Content-disposition', `attachment; filename=${filename}`);
  res.setHeader('Content-type', 'application/json');
  res.write(JSON.stringify(jobs, null, 2), () => res.end());
}
595018
function destroyCircular(from, seen) {
	const to = Array.isArray(from) ? [] : {};

	seen.push(from);

	for (const key of Object.keys(from)) {
		const value = from[key];

		if (typeof value === 'function') {
			continue;
		}

		if (!value || typeof value !== 'object') {
			to[key] = value;
			continue;
		}

		if (seen.indexOf(from[key]) === -1) {
			to[key] = destroyCircular(from[key], seen.slice(0));
			continue;
		}

		to[key] = '[Circular]';
	}

	if (typeof from.name === 'string') {
		to.name = from.name;
	}

	if (typeof from.message === 'string') {
		to.message = from.message;
	}

	if (typeof from.stack === 'string') {
		to.stack = from.stack;
	}

	return to;
}
670747
function validateJSonStructure(filePath, cb) {
  fs.readFile(filePath, function(err, data) {
    if (err) {
      return cb(err);
    }

    try {
      var jsonObject = JSON.parse(data);
      cb(null, jsonObject);
    } catch (e) {
      cb('Invalid JSON file: ' + path.basename(filePath));
    }
  });
}