function(data) {
            var paramArray = [],
                key, value;
            for (key in data) {
                value = data[key];
                key = ENCODE_URI_COMPONENT(key);
                paramArray.push((value === null) ? key : (key + "=" + ENCODE_URI_COMPONENT(value)));
            }
            return paramArray.join("&");
        }

function ( data ) { var paramArray = [ ] , key , value ; for ( key in data ) { value = data [ key ] ; key = ENCODE_URI_COMPONENT ( key ) ; paramArray . push ( ( value === null ) ? key : ( key + "=" + ENCODE_URI_COMPONENT ( value ) ) ) ; } return paramArray . join ( "&" ) ; }

Stringifies an object into one string with every pair separated by `&`

@method _toQueryString
@param data {Object} containing key-value pairs
@return {String} stringified presentation of the object, with every pair separated by `&`
@private

Stringifies an object into one string with every pair separated by &


function(queryString) {
            var args = queryString.split("&"),
                data = {};
            args.forEach(function(arg) {
                var item = arg.split("=");
                (item.length===2) && (data[item[0]]=item[1]);
            });
            return data;
        }

function ( queryString ) { var args = queryString . split ( "&" ) , data = { } ; args . forEach ( function ( arg ) { var item = arg . split ( "=" ) ; ( item . length === 2 ) && ( data [ item [ 0 ] ] = item [ 1 ] ) ; } ) ; return data ; }

Extracts an object based on the querystring. The object's values will be String-types.

@method _queryStringToDataObject
@param queryString {String}
@return {Object|null} stringified presentation of the object, with every pair separated by `&`
@private

Extracts an object based on the querystring . The object s values will be String - types .


function() {
            var instance = this;
            instance._runningRequests.forEach(function(promise) {
                promise.abort();
            });
            instance._runningRequests.length = 0;
        }

function ( ) { var instance = this ; instance . _runningRequests . forEach ( function ( promise ) { promise . abort ( ) ; } ) ; instance . _runningRequests . length = 0 ; }


function invokeConfigFn(tasks) {
    for (var taskName in tasks) {
      if (tasks.hasOwnProperty(taskName)) {
        tasks[taskName](grunt);
      }
    }
  }

function invokeConfigFn ( tasks ) { for ( var taskName in tasks ) { if ( tasks . hasOwnProperty ( taskName ) ) { tasks [ taskName ] ( grunt ) ; } } }

Invokes the function from a Grunt configuration module with
a single argument - the `grunt` object.

Invokes the function from a Grunt configuration module with a single argument - the grunt object .


function ensureProperties(str) {
                str = str || '';
                t.ok(hasPropertyDefinition(view, 'value'), 'has `value` property' + str);
                t.equal(typeof view.name, 'string', 'has `name` property that is a string' + str);
                t.notEqual(view.name, '', '`name` property should not be empty string' + str);
                t.ok(isFunction(view.setValue), 'has `setValue` method' + str);
                t.equal(typeof view.valid, 'boolean', 'has `valid` property that is a boolean' + str);
                t.equal(parent, view.parent, 'has same `parent` property' + str);
            }


function printEnvironment(environment, path, outputFile) {
  // print sub-objects in an environment.
  if (path) environment = traverse(environment).get(path.split('.'));
  path = path ? '.' + path : '';

  if (argv.format === 'json' || outputFile) {
    var json = JSON.stringify(environment, null, 2);
    if (outputFile) fs.writeFileSync(outputFile, json, 'utf-8');
    else console.log(JSON.stringify(environment, null, 2));
  } else {
    environment = _.mapValues(environment, function(v) {
      return util.inspect(v, {colors: true});
    });
    console.log(chalk.blue('==> ') + chalk.bold(renv.environment + path));
    console.log(columnify(environment, {showHeaders: false, config: {
      key: {minWidth: parseInt(width * 0.4), maxWidth: parseInt(width * 0.4)},
      value: {minWidth: parseInt(width * 0.6), maxWidth: parseInt(width * 0.6)},
    }}));
  }
}

function
printEnvironment
(
environment
,
path
,
outputFile
)
{
// print sub-objects in an environment.
if
(
path
)
environment
=
traverse
(
environment
)
.
get
(
path
.
split
(
'.'
)
)
;
path
=
path
'.'
+
path
:
''
;
if
(
argv
.
format
===
'json'
||
outputFile
)
{
var
json
=
JSON
.
stringify
(
environment
,
,
2
)
;
if
(
outputFile
)
fs
.
writeFileSync
(
outputFile
,
json
,
'utf-8'
)
;
else
console
.
log
(
JSON
.
stringify
(
environment
,
,
2
)
)
;
}
else
{
environment
=
_
.
mapValues
(
environment
,
function
(
v
)
{
return
util
.
inspect
(
v
,
{
colors
:
true
}
)
;
}
)
;
console
.
log
(
chalk
.
blue
(
'==> '
)
+
chalk
.
bold
(
renv
.
environment
+
path
)
)
;
console
.
log
(
columnify
(
environment
,
{
showHeaders
:
false
,
config
:
{
key
:
{
minWidth
:
parseInt
(
width
*
0.4
)
,
maxWidth
:
parseInt
(
width
*
0.4
)
}
,
value
:
{
minWidth
:
parseInt
(
width
*
0.6
)
,
maxWidth
:
parseInt
(
width
*
0.6
)
}
,
}
}
)
)
;
}
}


function rte(src, dest, data) {
  if (typeof dest === 'object') {
    data = dest; dest = src;
  }
  var rte = new Rte(src, data);
  return rte.stringify(dest);
}

function rte ( src , dest , data ) { if ( typeof dest === 'object' ) { data = dest ; dest = src ; } var rte = new Rte ( src , data ) ; return rte . stringify ( dest ) ; }

Generate a file path from properties on the given object.

**Examples:**

```js
rte(':a/:b:.c', { a: 'aaa', b: 'bbb', c: 'js' });
//=> 'aaa/bbb/c.js'
```

When a `source` file path is passed as the first argument, it will
be parsed and the resulting object will merged with the data
object (properties on the data object take precendence).

```js
rte('a/b/c.html', ':destbase/:basename', { destbase: 'foo' });
//=> 'foo/c.html'
```

@param {String} `src` Optionally pass a source file path to parse.
@param {String} `dest` Template for the destination file path with `:properties` to replace.
@param {Object} `data` Object with values to pass to the dest.
@api public

Generate a file path from properties on the given object .


function Component(domElement) {
	this.domElement = domElement;
	this.template = "";
	this.templateNodes = [];
	this.model = [];
	this.parentModel = null;
	this.built = false;
}

function Component ( domElement ) { this . domElement = domElement ; this . template = "" ; this . templateNodes = [ ] ; this . model = [ ] ; this . parentModel = null ; this . built = false ; }

Enhanced component system
Component class
It binds dynamic data to HTML element.

Enhanced component system Component class It binds dynamic data to HTML element .


function(template) {
		// unbind old models from old dom elements
		this.unbindAll();

		if(template == null) {
			// save template html
			this.template = this.domElement.innerHTML;
		}
		else {
			// set template string
			this.template = template;

			// fill element.innerHTML with the template
			//this.domElement.innerHTML = template;
			htmlToElem(this.domElement, this.template);
		}

		// set built flag as false
		this.built = false;

		// save template nodes
		this.templateNodes = [Array.prototype.slice.call(this.domElement.childNodes)];
	}

Sets a template of the component.

Argument can be template string or null - current content of the element will be used as the template.


function(newModel) {
		var oldPos;

		for(var i = 0; i < newModel.length; i++) {
			oldPos = this.model.indexOf(newModel[i]);

			if(oldPos >= 0) {
				// model already in the DOM
				if(i != oldPos) {
					// adjust template
					this.moveTemplateNodes(oldPos, i);
					// and model
					this.model.splice(i, 0, this.model.splice(oldPos, 1)[0]);
				}
			}
			else {
				// check whether current old model is in a new model array
				if(this.templateNodes[i] && newModel.indexOf(this.model[i]) == -1) {
					// just replace model at i
					this.model[i] = newModel[i];
					// bind model and template nodes
					this.bindModel(i);
				}
				else {
					// insert templateNodes at i
					this.cloneTemplateNodes(i);
					// insert model at i
					this.model.splice(i, 0, newModel[i]);
					// bind model and template nodes
					this.bindModel(i);
				}
			}
		}

		if(this.model.length > newModel.length) {
			// remove redundant template nodes
			for(var i = this.templateNodes.length-1; newModel.length <= i; i--) {
				this.unbindModel(i);
				this.removeTemplateNodes(i);
			}

			// and models
			this.model.splice(newModel.length, this.model.length-newModel.length);
		}
	}


function(position) {
		if(!this.templateNodes[0]) {
			// fill element.innerHTML with the template
			//this.domElement.innerHTML = this.template;
			htmlToElem(this.domElement, this.template);

			// save template nodes
			this.templateNodes.push(Array.prototype.slice.call(this.domElement.childNodes));

			return;
		}

		/*var clonedNode, clonedNodes = [];
		var templateNodes = this.templateNodes[0]; // need to be changed, because this.templateNodes[0] doesn't have to exist.

		if(position == null || position == this.templateNodes.length) {
			// insert at the end
			for(var i = 0; i < templateNodes.length; i++) {
				clonedNode = templateNodes[i].cloneNode(true);
				this.domElement.appendChild(clonedNode);
				clonedNodes.push(clonedNode);
			}

			this.templateNodes.push(clonedNodes);
		}
		else {
			// insert at the position (before nodes of this.templateNodes[position])
			for(var i = 0; i < templateNodes.length; i++) {
				clonedNode = templateNodes[i].cloneNode(true);
				this.domElement.insertBefore(clonedNode, this.templateNodes[position][0]);
				clonedNodes.push(clonedNode);
			}

			this.templateNodes.splice(position, 0, clonedNodes);
		}*/

		var dummyWrapper = document.createElement("div");
		//dummyWrapper.innerHTML = this.template;
		htmlToElem(dummyWrapper, this.template);

		var templateNodes = Array.prototype.slice.call(dummyWrapper.childNodes);

		if(position == null || position == this.templateNodes.length) {
			// insert at the end
			for(var i = 0; i < templateNodes.length; i++) {
				this.domElement.appendChild(templateNodes[i]);
			}

			this.templateNodes.push(templateNodes);
		}
		else {
			// insert at the position (before nodes of this.templateNodes[position])
			for(var i = 0; i < templateNodes.length; i++) {
				this.domElement.insertBefore(templateNodes[i], this.templateNodes[position][0]);
			}

			this.templateNodes.splice(position, 0, templateNodes);
		}
	}

Clone template nodes at the specified position. If ommited, template is cloned at the end.

Clone template nodes at the specified position . If ommited template is cloned at the end .


function(from, to) {
		var templateNodes = this.templateNodes[from];

		// insert at the position (before nodes of this.templateNodes[position])
		for(var i = 0; i < templateNodes.length; i++) {
			this.domElement.insertBefore(templateNodes[i], this.templateNodes[to][0]);
		}

		this.templateNodes.splice(from, 1);
		this.templateNodes.splice(to, 0, templateNodes);
	}


function BaseImporter () {
  this._schema = null;
  this._export = null;
  this._types = {};
  this._model = {
    properties:{},
    definitions:{},
    ids:{}
  };
  this.error = null;

  var baseImporter = this;

  //setup listeners
  this.on('readyStateChanged', function (readyState) {
    //state changed
    if(readyStates.complete === readyState){
      //state says loading has finished
      if(baseImporter.error){
        baseImporter.emit('failed', baseImporter.error);
      } else {
        baseImporter.emit('success', null, baseImporter.getModel());
      }

      //send general complete notification
      baseImporter.emit('complete', baseImporter.error, baseImporter.getModel());
    }
  });
}

function
BaseImporter
(
)
{
this
.
_schema
=
;
this
.
_export
=
;
this
.
_types
=
{
}
;
this
.
_model
=
{
properties
:
{
}
,
definitions
:
{
}
,
ids
:
{
}
}
;
this
.
error
=
;
var
baseImporter
=
this
;
//setup listeners
this
.
on
(
'readyStateChanged'
,
function
(
readyState
)
{
//state changed
if
(
readyStates
.
complete
===
readyState
)
{
//state says loading has finished
if
(
baseImporter
.
error
)
{
baseImporter
.
emit
(
'failed'
,
baseImporter
.
error
)
;
}
else
{
baseImporter
.
emit
(
'success'
,
,
baseImporter
.
getModel
(
)
)
;
}
//send general complete notification
baseImporter
.
emit
(
'complete'
,
baseImporter
.
error
,
baseImporter
.
getModel
(
)
)
;
}
}
)
;
}

BaseImporter psuedo class to be extended


function(nextSchema, nextScope, nextIndex, nextPath, nextCBack){
    var nSchema = nextSchema || false;
    var nScope = nextScope;
    var nIndex = nextIndex;
    var nPath = nextPath;
    var nCBack = nextCBack || function(){};

    if(false === nSchema){
      return function(){};
    }else{
      return function(){
        baseimporter.indexIDs.call(baseimporter, nSchema, nScope, nIndex, nPath, nCBack);
      };
    }
  }

function ( nextSchema , nextScope , nextIndex , nextPath , nextCBack ) { var nSchema = nextSchema || false ; var nScope = nextScope ; var nIndex = nextIndex ; var nPath = nextPath ; var nCBack = nextCBack || function ( ) { } ; if ( false === nSchema ) { return function ( ) { } ; } else { return function ( ) { baseimporter . indexIDs . call ( baseimporter , nSchema , nScope , nIndex , nPath , nCBack ) ; } ; } }

array for use in recursion
Factory function for generating next tick
Always returns a function, though passed an undefined nextSchema the
returned function will be empty

@param {object} nextSchema Object to index
@param {string} nextScope Scope to resolve against
@param {string} nextIndex Index of the property/definiton passed as nextSchema

@return {function} a function to be passed to process.nextTick()

array for use in recursion Factory function for generating next tick Always returns a function though passed an undefined nextSchema the returned function will be empty


function loadFormatter(formatterPath) {
    try {
        // @TODO: deprecate
        formatterPath = (formatterPath === 'jslint_xml') ? 'jslint' : formatterPath;
        return require('./lib/' + formatterPath + '_emitter');
    } catch (e) {
        console.error('Unrecognized format: %s', formatterPath);
        console.error('This emitter was not found on lib folder.\nYou can always create yours :)\n');
        throw e;
    }
}

Load a formatter
@param  {String} formatterPath
@return


function createDirectory(filePath, cb) {
    var dirname = path.dirname(filePath);

    mkdirp(dirname, function (err) {
        if (!err) {
            cb();
        } else {
            console.error('Error creating directory: ', err);
        }
    });
}

function
createDirectory
(
filePath
,
cb
)
{
var
dirname
=
path
.
dirname
(
filePath
)
;
mkdirp
(
dirname
,
function
(
err
)
{
if
(
!
err
)
{
cb
(
)
;
}
else
{
console
.
error
(
'Error creating directory: '
,
err
)
;
}
}
)
;
}

Creates the output dir
@param {String} filePath
@param cb


function binb_sha1 (x, len) {
  // append padding
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;
  var t, oa, ob, oc, od, oe, i = 0, j = 0;

  for (i; i < x.length; i += 16) {
    oa = a;
    ob = b;
    oc = c;
    od = d;
    oe = e;

    for (j; j < 80; j++) {
      if (j < 16) w[j] = x[i + j];
      else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = bit_rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, oa);
    b = safe_add(b, ob);
    c = safe_add(c, oc);
    d = safe_add(d, od);
    e = safe_add(e, oe);
  }

  return Array(a, b, c, d, e);
}

function
binb_sha1
(
x
,
len
)
{
// append padding
x
[
len
>>
5
]
|=
0x80
<<
(
24
len
%
32
)
;
x
[
(
(
len
+
64
>>
9
)
<<
4
)
+
15
]
=
len
;
var
w
=
Array
(
80
)
;
var
a
=
1732584193
;
var
b
=
271733879
;
var
c
=
1732584194
;
var
d
=
271733878
;
var
e
=
1009589776
;
var
t
,
oa
,
ob
,
oc
,
od
,
oe
,
i
=
0
,
j
=
0
;
for
(
i
;
i
<
x
.
length
;
i
+=
16
)
{
oa
=
a
;
ob
=
b
;
oc
=
c
;
od
=
d
;
oe
=
e
;
for
(
j
;
j
<
80
;
j
++
)
{
if
(
j
<
16
)
w
[
j
]
=
x
[
i
+
j
]
;
else
w
[
j
]
=
bit_rol
(
w
[
j
3
]
^
w
[
j
8
]
^
w
[
j
14
]
^
w
[
j
16
]
,
1
)
;
t
=
safe_add
(
safe_add
(
bit_rol
(
a
,
5
)
,
sha1_ft
(
j
,
b
,
c
,
d
)
)
,
safe_add
(
safe_add
(
e
,
w
[
j
]
)
,
sha1_kt
(
j
)
)
)
;
e
=
d
;
d
=
c
;
c
=
bit_rol
(
b
,
30
)
;
b
=
a
;
a
=
t
;
}
a
=
safe_add
(
a
,
oa
)
;
b
=
safe_add
(
b
,
ob
)
;
c
=
safe_add
(
c
,
oc
)
;
d
=
safe_add
(
d
,
od
)
;
e
=
safe_add
(
e
,
oe
)
;
}
return
Array
(
a
,
b
,
c
,
d
,
e
)
;
}

Calculate the SHA-1 of an array of big-endian words, and a bit length

Calculate the SHA - 1 of an array of big - endian words and a bit length


function Observer(fn, observerInfo) {
	// call Subscribable constructor
	Subscribable.call(this);

	this.fn = fn;
	this.dependency = [];
	this.currentValue = null;
	this.observerInfo = observerInfo;

	// hard binded callbacks
	this._dependencyGetter = this.dependencyGetter.bind(this);

	this.call();
}

function
Observer
(
fn
,
observerInfo
)
{
// call Subscribable constructor
Subscribable
.
call
(
this
)
;
this
.
fn
=
fn
;
this
.
dependency
=
[
]
;
this
.
currentValue
=
;
this
.
observerInfo
=
observerInfo
;
// hard binded callbacks
this
.
_dependencyGetter
=
this
.
dependencyGetter
.
bind
(
this
)
;
this
.
call
(
)
;
}

Observer is a subscribable which watches a function and each time some variable in it changes, it is called again and its return value is passed to subscribers.

Observer is a subscribable which watches a function and each time some variable in it changes it is called again and its return value is passed to subscribers .


function(directory) {
    var git, gitRef, packagePath, packageInfos;
    packagePath = path.join(directory, "package.json");

    // Check directory is a git repository
    return Q.nfcall(exec, "cd "+directory+" && git config --get remote.origin.url").then(function(output) {
        git = output.join("").replace(/(\r\n|\n|\r)/gm, "");

        // Check package.json exists
        if (!fs.existsSync(packagePath)) {
            return Q.reject(new Error("package.json not found"));
        } else {
            return Q();
        }
    }).then(function() {
        // Read current commit
        return Q.nfcall(exec, "cd "+directory+" && git rev-parse HEAD").then(function(output) {
            gitRef = output.join("").replace(/(\r\n|\n|\r)/gm, "");
        });
    }).then(function() {
        // Read package.json
        return Q.nfcall(fs.readFile, packagePath, 'utf8');
    }).then(function(output) {
        packageInfos = JSON.parse(output);
        return Q({
            'git': git+"#"+gitRef,
            'package': packageInfos
        });
    });
}


function (payload, next) {
				jira.getProject(options.project, handleGetProject(options, payload, next));
			}

function ( payload , next ) { jira . getProject ( options . project , handleGetProject ( options , payload , next ) ) ; }

get project, issueType, versions and components

get project issueType versions and components


function(localImagePath) {
        // Read the file in and convert it.
      var imageFile = fs.readFileSync(localImagePath);
      var mimeType = mime.lookup(localImagePath);
      var ret = "data:";
      ret += mimeType;
      ret += ";base64,";
      ret += imageFile.toString("base64");
      return ret;
  }

function
(
localImagePath
)
{
// Read the file in and convert it.
var
imageFile
=
fs
.
readFileSync
(
localImagePath
)
;
var
mimeType
=
mime
.
lookup
(
localImagePath
)
;
var
ret
=
"data:"
;
ret
+=
mimeType
;
ret
+=
";base64,"
;
ret
+=
imageFile
.
toString
(
"base64"
)
;
return
ret
;
}

Given the path for an image in the local file system, returns a data URI string
representing the data in that image file.

Given the path for an image in the local file system returns a data URI string representing the data in that image file .


function end() {
    try {
      this.queue(transformCss(filePath, data, opts));
    } catch(err) {
      this.emit("error", new Error(err));
    }

    this.queue(null);
  }

function end ( ) { try { this . queue ( transformCss ( filePath , data , opts ) ) ; } catch ( err ) { this . emit ( "error" , new Error ( err ) ) ; } this . queue ( null ) ; }


function apilist(items) {
    return ul(items.map(item => li({
        // use innerHTML to generate nested links
        innerHTML : item.replace(/(\w+)/g, apilink)
    })))
}

Gefine a template function that builds a list of links from the given list of short descriptions


function(property, callback) {
		if(typeof property !=  "string") {
			callback = property;
			property = "__all__";
		}

		this._subscribers[property] = this._subscribers[property] || [];

		if(this._subscribers[property].indexOf(callback) == -1) {
			this._subscribers[property].push(callback);
		}
	}

function ( property , callback ) { if ( typeof property != "string" ) { callback = property ; property = "__all__" ; } this . _subscribers [ property ] = this . _subscribers [ property ] || [ ] ; if ( this . _subscribers [ property ] . indexOf ( callback ) == - 1 ) { this . _subscribers [ property ] . push ( callback ) ; } }

Subscribe for changes of a property or the whole object


function(property, callback) {
		if(typeof property !=  "string") {
			callback = property;
			property = "__all__";
		}

		// empty, don't remove anything
		if(!this._subscribers[property]) return;

		// remove everything
		if(callback == null) this._subscribers[property] = [];

		// find callback and remove it
		var ind = this._subscribers[property].indexOf(callback);
		if(ind >= 0) this._subscribers[property].splice(ind, 1);
	}

function
(
property
,
callback
)
{
if
(
typeof
property
!=
"string"
)
{
callback
=
property
;
property
=
"__all__"
;
}
// empty, don't remove anything
if
(
!
this
.
_subscribers
[
property
]
)
return
;
// remove everything
if
(
callback
==
)
this
.
_subscribers
[
property
]
=
[
]
;
// find callback and remove it
var
ind
=
this
.
_subscribers
[
property
]
.
indexOf
(
callback
)
;
if
(
ind
>=
0
)
this
.
_subscribers
[
property
]
.
splice
(
ind
,
1
)
;
}

Unsubscribe for changes of a property or the whole object


function(property, val) {
		if(val === undefined) {
			// if second argument is missing, use property as value
			val = (property === undefined) ? this : property;
			property = "__all__";
		}

		if(property == "__all__") {
			// notify global subscribers
			notify(this._subscribers["__all__"], val);
		}
		else {
			// notify all subscribers of property
			notify(this._subscribers[property], val);

			// notify global subscribers as well
			this.notify(/*TODO: some usefull value*/);
		}
	}


function rowgroup(items, name) {
    return items.map(([htmlterm, ariaterm], i) => {
        htmlcount += htmlterm.split(', ').length
        ariacount += ariaterm.split(', ').length
        return tr([
            !i && th({
                rowSpan : items.length,
                children : name,
            }),
            td(htmlterm),
            td(ariaterm)
        ])
    })
}

function
rowgroup
(
items
,
name
)
{
return
items
.
map
(
(
[
htmlterm
,
ariaterm
]
,
i
)
=>
{
htmlcount
+=
htmlterm
.
split
(
', '
)
.
length
ariacount
+=
ariaterm
.
split
(
', '
)
.
length
return
tr
(
[
!
i
&&
th
(
{
rowSpan
:
items
.
length
,
children
:
name
,
}
)
,
td
(
htmlterm
)
,
td
(
ariaterm
)
]
)
}
)
}

Builds a row group from input parameters
@param items
@param name


function addStats(database, cb){
  			// If a databaseName is present, it's a single db.  No need to switch.
				var changeDB = database.databaseName ? database : db.db(database.name);

	  		// Get the stats
	  		changeDB.stats(function(err, stats){
	  			// Remove 1 from collection count, unless it's zero. Not sure why it's 1 off.
	  			if (stats.collections) {
		  			stats.collections--;
	  			}

	  			// Add the db name as the _id
	  			stats._id = stats.db;
	  			stats.name = stats.db;

	  			// Rename collections to avoid collisions on the client app.
	  			stats.collectionCount = stats.collections;
	  			delete stats.collections;
	  			// Add the stats to the corresponding database.
	  			dbList.push(stats);
		  		cb(null, database);
	  		});
	  	}

Async function to add stats to each db .


function tail(array) {
  var length = array ? array.length : 0;
  return length ? baseSlice(array, 1, length) : [];
}

function tail ( array ) { var length = array ? array . length : 0 ; return length ? baseSlice ( array , 1 , length ) : [ ] ; }

Gets all but the first element of `array`.

@static
@memberOf _
@since 4.0.0
@category Array
@param {Array} array The array to query.
@returns {Array} Returns the slice of `array`.
@example

_.tail([1, 2, 3]);
// => [2, 3]

Gets all but the first element of array .


function basePick(object, props) {
  object = Object(object);
  return basePickBy(object, props, function(value, key) {
    return key in object;
  });
}

function basePick ( object , props ) { object = Object ( object ) ; return basePickBy ( object , props , function ( value , key ) { return key in object ; } ) ; }

The base implementation of `_.pick` without support for individual
property identifiers.

@private
@param {Object} object The source object.
@param {string[]} props The property identifiers to pick.
@returns {Object} Returns the new object.

The base implementation of _ . pick without support for individual property identifiers .


function arrayAggregator(array, setter, iteratee, accumulator) {
  var index = -1,
      length = array ? array.length : 0;

  while (++index < length) {
    var value = array[index];
    setter(accumulator, value, iteratee(value), array);
  }
  return accumulator;
}

function arrayAggregator ( array , setter , iteratee , accumulator ) { var index = - 1 , length = array ? array . length : 0 ; while ( ++ index < length ) { var value = array [ index ] ; setter ( accumulator , value , iteratee ( value ) , array ) ; } return accumulator ; }

A specialized version of `baseAggregator` for arrays.

@private
@param {Array} [array] The array to iterate over.
@param {Function} setter The function to set `accumulator` values.
@param {Function} iteratee The iteratee to transform keys.
@param {Object} accumulator The initial aggregated object.
@returns {Function} Returns `accumulator`.

A specialized version of baseAggregator for arrays .


function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  var isAry = bitmask & ARY_FLAG,
      isBind = bitmask & BIND_FLAG,
      isBindKey = bitmask & BIND_KEY_FLAG,
      isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
      isFlip = bitmask & FLIP_FLAG,
      Ctor = isBindKey ? undefined : createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length;

    while (index--) {
      args[index] = arguments[index];
    }
    if (isCurried) {
      var placeholder = getHolder(wrapper),
          holdersCount = countHolders(args, placeholder);
    }
    if (partials) {
      args = composeArgs(args, partials, holders, isCurried);
    }
    if (partialsRight) {
      args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
    }
    length -= holdersCount;
    if (isCurried && length < arity) {
      var newHolders = replaceHolders(args, placeholder);
      return createRecurry(
        func, bitmask, createHybrid, wrapper.placeholder, thisArg,
        args, newHolders, argPos, ary, arity - length
      );
    }
    var thisBinding = isBind ? thisArg : this,
        fn = isBindKey ? thisBinding[func] : func;

    length = args.length;
    if (argPos) {
      args = reorder(args, argPos);
    } else if (isFlip && length > 1) {
      args.reverse();
    }
    if (isAry && ary < length) {
      args.length = ary;
    }
    if (this && this !== root && this instanceof wrapper) {
      fn = Ctor || createCtor(fn);
    }
    return fn.apply(thisBinding, args);
  }
  return wrapper;
}

function createHybrid ( func , bitmask , thisArg , partials , holders , partialsRight , holdersRight , argPos , ary , arity ) { var isAry = bitmask & ARY_FLAG , isBind = bitmask & BIND_FLAG , isBindKey = bitmask & BIND_KEY_FLAG , isCurried = bitmask & ( CURRY_FLAG | CURRY_RIGHT_FLAG ) , isFlip = bitmask & FLIP_FLAG , Ctor = isBindKey ? undefined : createCtor ( func ) ; function wrapper ( ) { var length = arguments . length , args = Array ( length ) , index = length ; while ( index -- ) { args [ index ] = arguments [ index ] ; } if ( isCurried ) { var placeholder = getHolder ( wrapper ) , holdersCount = countHolders ( args , placeholder ) ; } if ( partials ) { args = composeArgs ( args , partials , holders , isCurried ) ; } if ( partialsRight ) { args = composeArgsRight ( args , partialsRight , holdersRight , isCurried ) ; } length -= holdersCount ; if ( isCurried && length < arity ) { var newHolders = replaceHolders ( args , placeholder ) ; return createRecurry ( func , bitmask , createHybrid , wrapper . placeholder , thisArg , args , newHolders , argPos , ary , arity - length ) ; } var thisBinding = isBind ? thisArg : this , fn = isBindKey ? thisBinding [ func ] : func ; length = args . length ; if ( argPos ) { args = reorder ( args , argPos ) ; } else if ( isFlip && length > 1 ) { args . reverse ( ) ; } if ( isAry && ary < length ) { args . length = ary ; } if ( this && this !== root && this instanceof wrapper ) { fn = Ctor || createCtor ( fn ) ; } return fn . apply ( thisBinding , args ) ; } return wrapper ; }

Creates a function that wraps `func` to invoke it with optional `this`
binding of `thisArg`, partial application, and currying.

@private
@param {Function|string} func The function or method name to wrap.
@param {number} bitmask The bitmask flags. See `createWrap` for more details.
@param {*} [thisArg] The `this` binding of `func`.
@param {Array} [partials] The arguments to prepend to those provided to
the new function.
@param {Array} [holders] The `partials` placeholder indexes.
@param {Array} [partialsRight] The arguments to append to those provided
to the new function.
@param {Array} [holdersRight] The `partialsRight` placeholder indexes.
@param {Array} [argPos] The argument positions of the new function.
@param {number} [ary] The arity cap of `func`.
@param {number} [arity] The arity of `func`.
@returns {Function} Returns the new wrapped function.

Creates a function that wraps func to invoke it with optional this binding of thisArg partial application and currying .


function baseXor(arrays, iteratee, comparator) {
  var index = -1,
      length = arrays.length;

  while (++index < length) {
    var result = result
      ? arrayPush(
          baseDifference(result, arrays[index], iteratee, comparator),
          baseDifference(arrays[index], result, iteratee, comparator)
        )
      : arrays[index];
  }
  return (result && result.length) ? baseUniq(result, iteratee, comparator) : [];
}

function baseXor ( arrays , iteratee , comparator ) { var index = - 1 , length = arrays . length ; while ( ++ index < length ) { var result = result ? arrayPush ( baseDifference ( result , arrays [ index ] , iteratee , comparator ) , baseDifference ( arrays [ index ] , result , iteratee , comparator ) ) : arrays [ index ] ; } return ( result && result . length ) ? baseUniq ( result , iteratee , comparator ) : [ ] ; }

The base implementation of methods like `_.xor`, without support for
iteratee shorthands, that accepts an array of arrays to inspect.

@private
@param {Array} arrays The arrays to inspect.
@param {Function} [iteratee] The iteratee invoked per element.
@param {Function} [comparator] The comparator invoked per element.
@returns {Array} Returns the new array of values.

The base implementation of methods like _ . xor without support for iteratee shorthands that accepts an array of arrays to inspect .


function baseMean(array, iteratee) {
  var length = array ? array.length : 0;
  return length ? (baseSum(array, iteratee) / length) : NAN;
}

function baseMean ( array , iteratee ) { var length = array ? array . length : 0 ; return length ? ( baseSum ( array , iteratee ) / length ) : NAN ; }

The base implementation of `_.mean` and `_.meanBy` without support for
iteratee shorthands.

@private
@param {Array} array The array to iterate over.
@param {Function} iteratee The function invoked per iteration.
@returns {number} Returns the mean.

The base implementation of _ . mean and _ . meanBy without support for iteratee shorthands .


function baseIsTypedArray(value) {
  return isObjectLike$1(value) && isLength(value.length) && !!typedArrayTags[objectToString$1.call(value)];
}

function baseIsTypedArray ( value ) { return isObjectLike$1 ( value ) && isLength ( value . length ) && ! ! typedArrayTags [ objectToString$1 . call ( value ) ] ; }

The base implementation of `_.isTypedArray` without Node.js optimizations.

@private
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is a typed array, else `false`.

The base implementation of _ . isTypedArray without Node . js optimizations .


function baseUnset(object, path) {
  path = isKey(path, object) ? [path] : castPath(path);
  object = parent(object, path);

  var key = toKey(last(path));
  return !(object != null && hasOwnProperty.call(object, key)) || delete object[key];
}

function baseUnset ( object , path ) { path = isKey ( path , object ) ? [ path ] : castPath ( path ) ; object = parent ( object , path ) ; var key = toKey ( last ( path ) ) ; return ! ( object != null && hasOwnProperty . call ( object , key ) ) || delete object [ key ] ; }

The base implementation of `_.unset`.

@private
@param {Object} object The object to modify.
@param {Array|string} path The path of the property to unset.
@returns {boolean} Returns `true` if the property is deleted, else `false`.


function basePullAt(array, indexes) {
  var length = array ? indexes.length : 0,
      lastIndex = length - 1;

  while (length--) {
    var index = indexes[length];
    if (length == lastIndex || index !== previous) {
      var previous = index;
      if (isIndex(index)) {
        splice.call(array, index, 1);
      }
      else if (!isKey(index, array)) {
        var path = castPath(index),
            object = parent(array, path);

        if (object != null) {
          delete object[toKey(last(path))];
        }
      }
      else {
        delete array[toKey(index)];
      }
    }
  }
  return array;
}

function basePullAt ( array , indexes ) { var length = array ? indexes . length : 0 , lastIndex = length - 1 ; while ( length -- ) { var index = indexes [ length ] ; if ( length == lastIndex || index !== previous ) { var previous = index ; if ( isIndex ( index ) ) { splice . call ( array , index , 1 ) ; } else if ( ! isKey ( index , array ) ) { var path = castPath ( index ) , object = parent ( array , path ) ; if ( object != null ) { delete object [ toKey ( last ( path ) ) ] ; } } else { delete array [ toKey ( index ) ] ; } } } return array ; }

The base implementation of `_.pullAt` without support for individual
indexes or capturing the removed elements.

@private
@param {Array} array The array to modify.
@param {number[]} indexes The indexes of elements to remove.
@returns {Array} Returns `array`.

The base implementation of _ . pullAt without support for individual indexes or capturing the removed elements .


function isError(value) {
  if (!isObjectLike(value)) {
    return false;
  }
  return (objectToString.call(value) == errorTag) ||
    (typeof value.message == 'string' && typeof value.name == 'string');
}

function isError ( value ) { if ( ! isObjectLike ( value ) ) { return false ; } return ( objectToString . call ( value ) == errorTag ) || ( typeof value . message == 'string' && typeof value . name == 'string' ) ; }

Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
`SyntaxError`, `TypeError`, or `URIError` object.

@static
@memberOf _
@since 3.0.0
@category Lang
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is an error object, else `false`.
@example

_.isError(new Error);
// => true

_.isError(Error);
// => false

Checks if value is an Error EvalError RangeError ReferenceError SyntaxError TypeError or URIError object .


function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  var isBindKey = bitmask & BIND_KEY_FLAG;
  if (!isBindKey && typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var length = partials ? partials.length : 0;
  if (!length) {
    bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
    partials = holders = undefined;
  }
  ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
  arity = arity === undefined ? arity : toInteger(arity);
  length -= holders ? holders.length : 0;

  if (bitmask & PARTIAL_RIGHT_FLAG) {
    var partialsRight = partials,
        holdersRight = holders;

    partials = holders = undefined;
  }
  var data = isBindKey ? undefined : getData(func);

  var newData = [
    func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
    argPos, ary, arity
  ];

  if (data) {
    mergeData(newData, data);
  }
  func = newData[0];
  bitmask = newData[1];
  thisArg = newData[2];
  partials = newData[3];
  holders = newData[4];
  arity = newData[9] = newData[9] == null
    ? (isBindKey ? 0 : func.length)
    : nativeMax(newData[9] - length, 0);

  if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
    bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
  }
  if (!bitmask || bitmask == BIND_FLAG) {
    var result = createBind(func, bitmask, thisArg);
  } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
    result = createCurry(func, bitmask, arity);
  } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
    result = createPartial(func, bitmask, thisArg, partials);
  } else {
    result = createHybrid.apply(undefined, newData);
  }
  var setter = data ? baseSetData : setData;
  return setWrapToString(setter(result, newData), func, bitmask);
}

function createWrap ( func , bitmask , thisArg , partials , holders , argPos , ary , arity ) { var isBindKey = bitmask & BIND_KEY_FLAG ; if ( ! isBindKey && typeof func != 'function' ) { throw new TypeError ( FUNC_ERROR_TEXT ) ; } var length = partials ? partials . length : 0 ; if ( ! length ) { bitmask &= ~ ( PARTIAL_FLAG | PARTIAL_RIGHT_FLAG ) ; partials = holders = undefined ; } ary = ary === undefined ? ary : nativeMax ( toInteger ( ary ) , 0 ) ; arity = arity === undefined ? arity : toInteger ( arity ) ; length -= holders ? holders . length : 0 ; if ( bitmask & PARTIAL_RIGHT_FLAG ) { var partialsRight = partials , holdersRight = holders ; partials = holders = undefined ; } var data = isBindKey ? undefined : getData ( func ) ; var newData = [ func , bitmask , thisArg , partials , holders , partialsRight , holdersRight , argPos , ary , arity ] ; if ( data ) { mergeData ( newData , data ) ; } func = newData [ 0 ] ; bitmask = newData [ 1 ] ; thisArg = newData [ 2 ] ; partials = newData [ 3 ] ; holders = newData [ 4 ] ; arity = newData [ 9 ] = newData [ 9 ] == null ? ( isBindKey ? 0 : func . length ) : nativeMax ( newData [ 9 ] - length , 0 ) ; if ( ! arity && bitmask & ( CURRY_FLAG | CURRY_RIGHT_FLAG ) ) { bitmask &= ~ ( CURRY_FLAG | CURRY_RIGHT_FLAG ) ; } if ( ! bitmask || bitmask == BIND_FLAG ) { var result = createBind ( func , bitmask , thisArg ) ; } else if ( bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG ) { result = createCurry ( func , bitmask , arity ) ; } else if ( ( bitmask == PARTIAL_FLAG || bitmask == ( BIND_FLAG | PARTIAL_FLAG ) ) && ! holders . length ) { result = createPartial ( func , bitmask , thisArg , partials ) ; } else { result = createHybrid . apply ( undefined , newData ) ; } var setter = data ? baseSetData : setData ; return setWrapToString ( setter ( result , newData ) , func , bitmask ) ; }

Creates a function that either curries or invokes `func` with optional
`this` binding and partially applied arguments.

@private
@param {Function|string} func The function or method name to wrap.
@param {number} bitmask The bitmask flags.
The bitmask may be composed of the following flags:
1 - `_.bind`
2 - `_.bindKey`
4 - `_.curry` or `_.curryRight` of a bound function
8 - `_.curry`
16 - `_.curryRight`
32 - `_.partial`
64 - `_.partialRight`
128 - `_.rearg`
256 - `_.ary`
512 - `_.flip`
@param {*} [thisArg] The `this` binding of `func`.
@param {Array} [partials] The arguments to be partially applied.
@param {Array} [holders] The `partials` placeholder indexes.
@param {Array} [argPos] The argument positions of the new function.
@param {number} [ary] The arity cap of `func`.
@param {number} [arity] The arity of `func`.
@returns {Function} Returns the new wrapped function.

Creates a function that either curries or invokes func with optional this binding and partially applied arguments .


function forInRight(object, iteratee) {
  return object == null
    ? object
    : baseForRight(object, baseIteratee(iteratee, 3), keysIn);
}

function forInRight ( object , iteratee ) { return object == null ? object : baseForRight ( object , baseIteratee ( iteratee , 3 ) , keysIn ) ; }

This method is like `_.forIn` except that it iterates over properties of
`object` in the opposite order.

@static
@memberOf _
@since 2.0.0
@category Object
@param {Object} object The object to iterate over.
@param {Function} [iteratee=_.identity] The function invoked per iteration.
@returns {Object} Returns `object`.
@see _.forIn
@example

function Foo() {
this.a = 1;
this.b = 2;
}

Foo.prototype.c = 3;

_.forInRight(new Foo, function(value, key) {
console.log(key);
});
// => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.

This method is like _ . forIn except that it iterates over properties of object in the opposite order .


function basePickBy(object, props, predicate) {
  var index = -1,
      length = props.length,
      result = {};

  while (++index < length) {
    var key = props[index],
        value = object[key];

    if (predicate(value, key)) {
      baseAssignValue(result, key, value);
    }
  }
  return result;
}

function basePickBy ( object , props , predicate ) { var index = - 1 , length = props . length , result = { } ; while ( ++ index < length ) { var key = props [ index ] , value = object [ key ] ; if ( predicate ( value , key ) ) { baseAssignValue ( result , key , value ) ; } } return result ; }

The base implementation of  `_.pickBy` without support for iteratee shorthands.

@private
@param {Object} object The source object.
@param {string[]} props The property identifiers to pick from.
@param {Function} predicate The function invoked per property.
@returns {Object} Returns the new object.

The base implementation of _ . pickBy without support for iteratee shorthands .


function SelectQuery(request, context) {
  this.request = request;
  this.domain = new Domain({ source: request,
                             context: context });

  this.filters         = [];
  this.matchExpression = '';
  this.noResult        = false;

  this.parse();
}

function SelectQuery ( request , context ) { this . request = request ; this . domain = new Domain ( { source : request , context : context } ) ; this . filters = [ ] ; this . matchExpression = '' ; this . noResult = false ; this . parse ( ) ; }

this should be re-implemented as a class

this should be re - implemented as a class


function(fieldName) {
    var field;
    if (this.domain && fieldName) {
      field = this.domain.getIndexField(fieldName);
      if (!field.exists()) {
        this.throwValidationError(
          'CS-UnknownFieldInMatchExpression',
          'Field \'' + fieldName + '\' is not defined in the metadata for this ' +
            'collection. All fields used in the match expression must be ' +
            'defined in the metadata.'
        );
      } else if (!field.searchEnabled) {
        this.available = false;
      }
    }
    if (!field)
      field = new IndexField(fieldName).setType("text");
    return field;
  }

Get an instance of "IndexField". Unknown field works as "text, searchable" field, if it works without domain.

Get an instance of IndexField . Unknown field works as text searchable field if it works without domain .


function formatTable(table, links, notes) {
  var widths = [];
  var rows = table.map(function (row) {
    var cells = row.map(function (cell) {
      return formatSpans(cell, links, notes);
    });
    cells.forEach(function (cell, index) {
      widths[index] = Math.max(cell.length, widths[index] || 5);
      widths[index] = Math.min(widths[index], 50);
    });
    return cells.join(' & ');
  });

  var totalWidth = widths.reduce(function sum(val, width) { return val + width; }, 0);
  totalWidth = Math.max(totalWidth, 100);
  widths = widths.map(function (width) {
    var relativeWidth = width / totalWidth;
    return 'p{' + relativeWidth + '\\textwidth}';
  }).join(' | ');

  var str =
    '\\begin{longtable}{ | ' + widths + ' |}\n' +
    '\\hline\n' +
    rows.join(' \\\\\n\\hline\n') +
    ' \\\\\n' +
    '\\hline\n' +
    '\\end{longtable}';
  return str;
}

function
formatTable
(
table
,
links
,
notes
)
{
var
widths
=
[
]
;
var
rows
=
table
.
map
(
function
(
row
)
{
var
cells
=
row
.
map
(
function
(
cell
)
{
return
formatSpans
(
cell
,
links
,
notes
)
;
}
)
;
cells
.
forEach
(
function
(
cell
,
index
)
{
widths
[
index
]
=
Math
.
max
(
cell
.
length
,
widths
[
index
]
||
5
)
;
widths
[
index
]
=
Math
.
min
(
widths
[
index
]
,
50
)
;
}
)
;
return
cells
.
join
(
' & '
)
;
}
)
;
var
totalWidth
=
widths
.
reduce
(
function
sum
(
val
,
width
)
{
return
val
+
width
;
}
,
0
)
;
totalWidth
=
Math
.
max
(
totalWidth
,
100
)
;
widths
=
widths
.
map
(
function
(
width
)
{
var
relativeWidth
=
width
/
totalWidth
;
return
'p{'
+
relativeWidth
+
'\\textwidth}'
;
}
)
.
join
(
' | '
)
;
var
str
=
'\\begin{longtable}{ | '
+
widths
+
' |}\n'
+
'\\hline\n'
+
rows
.
join
(
' \\\\\n\\hline\n'
)
+
' \\\\\n'
+
'\\hline\n'
+
'\\end{longtable}'
;
return
str
;
}

table is array of rows, where row is array of cells, cell is array of spans

table is array of rows where row is array of cells cell is array of spans


function(plugins, config) {
    var self = this;
    var aliasMap = Object.keys(plugins)
      .reduce(function(aliases, pluginName) {
        if (!aliases[pluginName] || !aliases[pluginName].as) {
          aliases[pluginName] = { as: [pluginName] };
        }

        aliases[pluginName].as = self._castArray(aliases[pluginName].as);
        return aliases;
      }, config);

    var unknownConfigKeys = _.difference(Object.keys(aliasMap), Object.keys(plugins));

    if (unknownConfigKeys.length) {
      this._logUnknownPlugins(unknownConfigKeys, 'config.pipeline.alias');
    }

    return aliasMap;
  }

function ( plugins , config ) { var self = this ; var aliasMap = Object . keys ( plugins ) . reduce ( function ( aliases , pluginName ) { if ( ! aliases [ pluginName ] || ! aliases [ pluginName ] . as ) { aliases [ pluginName ] = { as : [ pluginName ] } ; } aliases [ pluginName ] . as = self . _castArray ( aliases [ pluginName ] . as ) ; return aliases ; } , config ) ; var unknownConfigKeys = _ . difference ( Object . keys ( aliasMap ) , Object . keys ( plugins ) ) ; if ( unknownConfigKeys . length ) { this . _logUnknownPlugins ( unknownConfigKeys , 'config.pipeline.alias' ) ; } return aliasMap ; }

Build up a hash of the all plugin aliases, keyed by plugin name, with the value being an array of aliases.
This hash will contain an entry for every installed plugin.

If a plugin has not been referenced in `config.pipeline.alias` then it will be added to the map
with an alias to it's original name (see `boo` below),

Example return value:

{
foo: { as: ['bar', 'baz'] },
boo: { as: ['boo'] }
}

Build up a hash of the all plugin aliases keyed by plugin name with the value being an array of aliases . This hash will contain an entry for every installed plugin .


function(aliasMap, config) {
    var aliases = this._flattenAliasMap(aliasMap);
    var allExcept = null;

    if (typeof config.allExcept !== 'undefined') {
      allExcept = this._castArray(config.allExcept);
      delete config.allExcept;
    }

    var keys = Object.keys(config);

    if (allExcept) {
      keys = keys.concat(allExcept);
    }

    var unknownConfigKeys = _.difference(keys, aliases);

    if (unknownConfigKeys.length) {
      this._logUnknownPlugins(unknownConfigKeys, 'config.pipeline.disabled');
    }

    var disabledMap = aliases.reduce(function(map, alias) {
      if (map[alias] === undefined) {
        if (allExcept && allExcept.length) {
          if (allExcept.indexOf(alias) >= 0) {
            map[alias] = false;
          } else {
            map[alias] = true;
          }
        } else {
          map[alias] = false;
        }
      }

      return map;
    }, config);

    return disabledMap;
  }

function ( aliasMap , config ) { var aliases = this . _flattenAliasMap ( aliasMap ) ; var allExcept = null ; if ( typeof config . allExcept !== 'undefined' ) { allExcept = this . _castArray ( config . allExcept ) ; delete config . allExcept ; } var keys = Object . keys ( config ) ; if ( allExcept ) { keys = keys . concat ( allExcept ) ; } var unknownConfigKeys = _ . difference ( keys , aliases ) ; if ( unknownConfigKeys . length ) { this . _logUnknownPlugins ( unknownConfigKeys , 'config.pipeline.disabled' ) ; } var disabledMap = aliases . reduce ( function ( map , alias ) { if ( map [ alias ] === undefined ) { if ( allExcept && allExcept . length ) { if ( allExcept . indexOf ( alias ) >= 0 ) { map [ alias ] = false ; } else { map [ alias ] = true ; } } else { map [ alias ] = false ; } } return map ; } , config ) ; return disabledMap ; }

Build up a hash of disabled plugin instances, keyed by alias, with the value being whether it's disabled or not
This hash will contain an entry for every installed plugin.

If a plugin has not been referenced in `config.pipeline.disabled` then it will be added to the map as `disabled: false`.

Example return value:

{
foo: true,
bar: false
}

Build up a hash of disabled plugin instances keyed by alias with the value being whether it s disabled or not This hash will contain an entry for every installed plugin .


function(config, aliasMap, pluginInstances) {
    var self = this;

    pluginInstances.forEach(function(instance) {
      if (instance.runBefore) {
        var befores = self._castArray(instance.runBefore);
        config = self._mergeAuthorProvidedOrderWithConfigOrder('before', instance.name, befores, config, aliasMap);
      }

      if (instance.runAfter) {
        var afters = self._castArray(instance.runAfter);
        config = self._mergeAuthorProvidedOrderWithConfigOrder('after', instance.name, afters, config, aliasMap);
      }
    });

    var aliases = this._flattenAliasMap(aliasMap);

    var configNames = Object.keys(config).reduce(function(arr, key) {
      arr.push(key);

      var befores = self._castArray(config[key].before);
      var afters = self._castArray(config[key].after);

      return arr.concat(befores).concat(afters);
    }, [])
    .reduce(function(arr, key) {
      if (arr.indexOf(key) === -1) {
        arr.push(key);
      }
      return arr;
    }, []);

    var unknownConfigKeys = _.difference(configNames, aliases);

    if (unknownConfigKeys.length) {
      this._logUnknownPlugins(unknownConfigKeys, 'config.pipeline.runOrder');
    }

    return config;
  }

Build up a hash of plugin instance execution order overrides.
This hash will only container an entry for instances that should run in a particular order. All other instances will be ordered by their natural
ordering.

Ordering of plugin instances can be specified by users of ember-cli-deploy via `config.pipeline.runOrder` and by plugin authors via `run{Before,After}`.
This function will attempt to merge the author defined run orders with the user defined ones.

Example return value:

{
foo: { before: ['bar'] },
baz: { after: ['boo', 'bom'] }
}

Build up a hash of plugin instance execution order overrides . This hash will only container an entry for instances that should run in a particular order . All other instances will be ordered by their natural ordering .


function(options, params) {

            // Create connection to qps
            var qpsApi = qps(options);

            // Returned object
            var task = new Task();

            // Ticket flow
            Rx.Observable
                .from(qpsApi.ticket.post(params))
                .catch((err) => {
                    if (err.match(/^Specified targetId .* was unknown$/)) {

                        // if there was a problem with the target Id, try to generate another ticket by reseting target Id
                        task.running('warning', `Wrong targetId: '${params.TargetId}', generating a ticket to default location`);
                        delete params.TargetId;

                        return Rx.Observable.from(module.exports.getTicket(options, params));
                    } else {
                        return Rx.Observable.throw(new Error(err));
                    }
                })
                .subscribe(task);

            if (returnObservable) {
                return task;
            } else {
                return task.toPromise(extPromise);
            }
        }

Generates a ticket on Qlik Sense QRS Api. If the targetId is not correct
then the ticket will redirect to the hub

@example
```javascript
utils.getTicket({
restUri: 'https://10.76.224.72',
pfx: pfx,
passPhrase: ''
},
{
UserId: 'qlikservice',
UserDirectory: '2008R2-0',
Attributes: []
}
}).then(function(retVal) {
console.log(retVal);
});
```

@memberOf Qlik

@param {options}             options     Qlik Sense connection options
@param {ticketParams}        params      the ticket parameters
@returns {Task.<ticket>}                 a Task resolving to the generated ticket

Generates a ticket on Qlik Sense QRS Api . If the targetId is not correct then the ticket will redirect to the hub


function exportCubeMixin(cubeDef) {

        var app = this;
        var task = new Task();

        promise().then(function() {

            // Start

            task.running('info', 'Starting!');

        }).then(function(reply) {

            // Create cube

            return app.createSessionObject({
                qHyperCubeDef: cubeDef,
                qInfo: {
                    qType: 'mashup'
                }
            }).then(function(reply) {
                task.running('info', 'Cube generated');
                return reply;
            })

        }).then(function(sessionObject) {

            // Get cube layout

            return promise.all([
                sessionObject,
                sessionObject.getLayout().then(function(reply) {
                    task.running('info', 'Got cube layout');
                    return reply;
                })
            ])

        }).then(function([sessionObject, cubeLayout]) {

            // Get cube pages

            var columns = cubeLayout.qHyperCube.qSize.qcx;
            var totalheight = cubeLayout.qHyperCube.qSize.qcy;
            var pageheight = Math.floor(10000 / columns);
            var numberOfPages = Math.ceil(totalheight / pageheight);

            var pages = Array.apply(null, new Array(numberOfPages)).map(function(data, index) {

                return sessionObject.getHyperCubeData(
                    '/qHyperCubeDef',
                    [{
                        qTop: (pageheight * index),
                        qLeft: 0,
                        qWidth: columns,
                        qHeight: pageheight
                    }]
                ).then((page) => {
                    task.running('page', page);
                    return page;
                });

            }, this);

            return promise.all(pages).then(function(pages) {
                return promise.all([
                    sessionObject,
                    cubeLayout,
                    pages
                ]);
            });

        }).then(function([sessionObject, cubeLayout, pages]) {

            pages = [].concat.apply([], pages.map(function(item) {
                return item[0].qMatrix;
            }));

            task.done(pages);
            return pages;

        }).fail(function(err) {

            task.failed(err);
            return promise.reject(err);

        });

        if (returnObservable) {
            return task;
        } else {
            return task.toPromise(extPromise);
        }

    }

function
exportCubeMixin
(
cubeDef
)
{
var
app
=
this
;
var
task
=
new
Task
(
)
;
promise
(
)
.
then
(
function
(
)
{
// Start
task
.
running
(
'info'
,
'Starting!'
)
;
}
)
.
then
(
function
(
reply
)
{
// Create cube
return
app
.
createSessionObject
(
{
qHyperCubeDef
:
cubeDef
,
qInfo
:
{
qType
:
'mashup'
}
}
)
.
then
(
function
(
reply
)
{
task
.
running
(
'info'
,
'Cube generated'
)
;
return
reply
;
}
)
}
)
.
then
(
function
(
sessionObject
)
{
// Get cube layout
return
promise
.
all
(
[
sessionObject
,
sessionObject
.
getLayout
(
)
.
then
(
function
(
reply
)
{
task
.
running
(
'info'
,
'Got cube layout'
)
;
return
reply
;
}
)
]
)
}
)
.
then
(
function
(
[
sessionObject
,
cubeLayout
]
)
{
// Get cube pages
var
columns
=
cubeLayout
.
qHyperCube
.
qSize
.
qcx
;
var
totalheight
=
cubeLayout
.
qHyperCube
.
qSize
.
qcy
;
var
pageheight
=
Math
.
floor
(
10000
/
columns
)
;
var
numberOfPages
=
Math
.
ceil
(
totalheight
/
pageheight
)
;
var
pages
=
Array
.
apply
(
,
new
Array
(
numberOfPages
)
)
.
map
(
function
(
data
,
index
)
{
return
sessionObject
.
getHyperCubeData
(
'/qHyperCubeDef'
,
[
{
qTop
:
(
pageheight
*
index
)
,
qLeft
:
0
,
qWidth
:
columns
,
qHeight
:
pageheight
}
]
)
.
then
(
(
page
)
=>
{
task
.
running
(
'page'
,
page
)
;
return
page
;
}
)
;
}
,
this
)
;
return
promise
.
all
(
pages
)
.
then
(
function
(
pages
)
{
return
promise
.
all
(
[
sessionObject
,
cubeLayout
,
pages
]
)
;
}
)
;
}
)
.
then
(
function
(
[
sessionObject
,
cubeLayout
,
pages
]
)
{
pages
=
[
]
.
concat
.
apply
(
[
]
,
pages
.
map
(
function
(
item
)
{
return
item
[
0
]
.
qMatrix
;
}
)
)
;
task
.
done
(
pages
)
;
return
pages
;
}
)
.
fail
(
function
(
err
)
{
task
.
failed
(
err
)
;
return
promise
.
reject
(
err
)
;
}
)
;
if
(
returnObservable
)
{
return
task
;
}
else
{
return
task
.
toPromise
(
extPromise
)
;
}
}

Exports a cube

@param cubeDef the cube definition
@returns {Task.<Array.<Page>>} a task resolving to the cube pages


function createListBoxMixin({ id, field }) {
        return this.createObject({
            qInfo: {
                qType: 'ListObject'
            },
            qListObjectDef: {
                qStateName: '$',
                qLibraryId: undef.if(id, ''),
                qDef: {
                    qFieldDefs: undef.if(field, [field], [])
                },
                qInitialDataFetch: [{
                    qTop: 0,
                    qLeft: 0,
                    qHeight: 5,
                    qWidth: 1
                }]
            }
        }).then((object) => {
            return object.getLayout();
        })
    }

function createListBoxMixin ( { id , field } ) { return this . createObject ( { qInfo : { qType : 'ListObject' } , qListObjectDef : { qStateName : '$' , qLibraryId : undef . if ( id , '' ) , qDef : { qFieldDefs : undef . if ( field , [ field ] , [ ] ) } , qInitialDataFetch : [ { qTop : 0 , qLeft : 0 , qHeight : 5 , qWidth : 1 } ] } } ) . then ( ( object ) => { return object . getLayout ( ) ; } ) }

Creates a list box on a field or on a dimension


function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function
grayTransform
(
entry
,
direction
,
x
,
dim
)
{
// :: Int -> Int -> Int -> Int
return
bitwise
.
rotateRight
(
(
x
^
entry
)
,
dim
,
0
,
direction
+
1
)
}

rotate to desired gray using entry sequence


function directionSequence(i, dim) { // :: Int -> Int -> Int
    if (i == 0) return 0
    if (i % 2 == 0) return bitwise.trailingSetBits(i - 1) % dim
    return bitwise.trailingSetBits(i) % dim
}

function
directionSequence
(
i
,
dim
)
{
// :: Int -> Int -> Int
if
(
i
==
0
)
return
0
if
(
i
%
2
==
0
)
return
bitwise
.
trailingSetBits
(
i
1
)
%
dim
return
bitwise
.
trailingSetBits
(
i
)
%
dim
}


function nthRoot(num, nArg, precArg) { // : Int -> Int -> Int -> Int
  var n = nArg || 2;
  var prec = precArg || 12;

  var x = 1; // Initial guess.
  for (var i=0; i<prec; i++) {
    x = 1/n * ((n-1)*x + (num / Math.pow(x, n-1)));
  }

  return x;
}

function
nthRoot
(
num
,
nArg
,
precArg
)
{
// : Int -> Int -> Int -> Int
var
n
=
nArg
||
2
;
var
prec
=
precArg
||
12
;
var
x
=
1
;
// Initial guess.
for
(
var
i
=
0
;
i
<
prec
;
i
++
)
{
x
=
1
/
n
*
(
(
n
1
)
*
x
+
(
num
/
Math
.
pow
(
x
,
n
1
)
)
)
;
}
return
x
;
}


function hilbertIndex(point, options) { // :: [Int, Int, ..] -> {} -> Int
    options = options || {}
    var index = 0, code,
        entry = options.entry || 0,
        direction = options.direction || 0,
        i = options.precision || bitwise.bitPrecision(Math.max.apply(null, point)) - 1,
        dim = point.length

    console.log(i)
    while (i >= 0) {

        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < point.length; k++) {
            if (point[dim - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft(entrySequence(code), dim, 0, direction + 1)
        direction = (direction + directionSequence(code, dim) + 1) % dim
        index = (index << dim) | code

        i--
    }

    return index
}

function
hilbertIndex
(
point
,
options
)
{
// :: [Int, Int, ..] -> {} -> Int
options
=
options
||
{
}
var
index
=
0
,
code
,
entry
=
options
.
entry
||
0
,
direction
=
options
.
direction
||
0
,
i
=
options
.
precision
||
bitwise
.
bitPrecision
(
Math
.
max
.
apply
(
,
point
)
)
1
,
dim
=
point
.
length
console
.
log
(
i
)
while
(
i
>=
0
)
{
var
bits
=
0
var
mask
=
1
<<
dim
1
for
(
var
k
=
0
;
k
<
point
.
length
;
k
++
)
{
if
(
point
[
dim
(
k
+
1
)
]
&
(
1
<<
i
)
)
{
bits
|=
mask
}
mask
>>>=
1
}
bits
=
grayTransform
(
entry
,
direction
,
bits
,
dim
)
code
=
grayInverse
(
bits
)
entry
=
entry
^
bitwise
.
rotateLeft
(
entrySequence
(
code
)
,
dim
,
0
,
direction
+
1
)
direction
=
(
direction
+
directionSequence
(
code
,
dim
)
+
1
)
%
dim
index
=
(
index
<<
dim
)
|
code
i
}
return
index
}

Hilbert conversions Returns Hilbert index of given cardinal point


function hilbertIndexInverse(dim, index, options) { // :: Int -> Int -> [Int, Int, ..]
    options = options || {}
    var entry = options.entry || 0,
        direction = options.direction || 0,
        m = curvePrecision(index, dim),
        p = Array.apply(null, new Array(dim)).map(Number.prototype.valueOf, 0)

    for (var i = m - 1; i >= 0; i--) {
        var mask = 1 << (i * dim), bits = 0, code

        for (var k = dim - 1; k >= 0; k--) {
            if (index & (mask << k)) {
                bits |= (1 << k)
            }
        }

        code = grayInverseTransform(entry, direction, grayCode(bits), dim)
        for (var k = 0; k < dim; k++) {
            if (code & (1 << k)) {
                p[k] |= (1 << i)
            }
        }

        entry = entry ^ bitwise.rotateLeft(entrySequence(bits), dim, 0, direction + 1)
        direction = (direction + directionSequence(bits, dim) + 1) % dim
    }
    return p
}

function
hilbertIndexInverse
(
dim
,
index
,
options
)
{
// :: Int -> Int -> [Int, Int, ..]
options
=
options
||
{
}
var
entry
=
options
.
entry
||
0
,
direction
=
options
.
direction
||
0
,
m
=
curvePrecision
(
index
,
dim
)
,
p
=
Array
.
apply
(
,
new
Array
(
dim
)
)
.
map
(
Number
.
prototype
.
valueOf
,
0
)
for
(
var
i
=
m
1
;
i
>=
0
;
i
)
{
var
mask
=
1
<<
(
i
*
dim
)
,
bits
=
0
,
code
for
(
var
k
=
dim
1
;
k
>=
0
;
k
)
{
if
(
index
&
(
mask
<<
k
)
)
{
bits
|=
(
1
<<
k
)
}
}
code
=
grayInverseTransform
(
entry
,
direction
,
grayCode
(
bits
)
,
dim
)
for
(
var
k
=
0
;
k
<
dim
;
k
++
)
{
if
(
code
&
(
1
<<
k
)
)
{
p
[
k
]
|=
(
1
<<
i
)
}
}
entry
=
entry
^
bitwise
.
rotateLeft
(
entrySequence
(
bits
)
,
dim
,
0
,
direction
+
1
)
direction
=
(
direction
+
directionSequence
(
bits
,
dim
)
+
1
)
%
dim
}
return
p
}

Returns cardinal point given Hilbert index


function getConsoleReporterOpts(opts) {
            opts = opts || {};
            opts.print = function () {
                grunt.log.write.apply(this, arguments);
            };
            // checking this here for the old name `verbose` (now alias).
            opts.verbosity = opts.verbosity === undefined
                ? opts.verbose
                : opts.verbosity;
            return opts;
        }

Extends default console reporter options


function _taskFatalHandler_(e) {
            var err = e ? (e.stack || e.message || e) : 'Unknown Error';
            grunt.fatal(err, grunt.fail.code.TASK_FAILURE);
        }

function
_taskFatalHandler_
(
e
)
{
var
err
=
e
(
e
.
stack
||
e
.
message
||
e
)
:
'Unknown Error'
;
grunt
.
fatal
(
err
,
grunt
.
fail
.
code
.
TASK_FAILURE
)
;
}

We need a named function to check whether this is previously added. Bec. since this is a "multi" task, this handler will get added every time.

We need a named function to check whether this is previously added . Bec . since this is a multi task this handler will get added every time .


function(options, cb) {

      // if no sassDir or files are not identify, error.
      if (!options.sassDir) {
        grunt.log.error('compass-multiple needs sassDir for searching scss files.');
        cb(false);
      }

      // search scss files.(Additional Implementation)
      if (options.sassFiles) {

        var pathes = options.sassFiles;
        var pathesCount = pathes.length;
        var currentCount = 0;
        var files = [];
        for (var i = 0; i < pathes.length; i++) {
          glob(pathes[i], function(error, tmpFiles) {
            if (error) {
              console.log('error: ', error);
              cb(false);
            }

            files = files.concat(tmpFiles);
            currentCount++;
            if (pathesCount === currentCount) {
              // compass compile.
              grunt.log.writeln('pathes: ', files);
              compileFiles(options, files, cb);
            }
          });
        }

      } else {  // use sassDir

        var searchPath = options.sassDir + '/**/*.scss';
        glob(searchPath, function(error, files) {
          if (error) {
            console.log('error: ', error);
            cb(false);
          }

          // compass compile.
          compileFiles(options, files, cb);
        });

      }
    }


function pageRange(selected, numPages, num) {
  let selectedPos = Math.ceil(num / 2);
  let start = (selected < selectedPos) ? 1
    : selected - selectedPos + 1;
  let len = (numPages < start + num - 1) ? numPages - start + 1
    : num;

  return Array
    .apply(null, Array(len))
    .map((u, i) => start + i);
}

function pageRange ( selected , numPages , num ) { let selectedPos = Math . ceil ( num / 2 ) ; let start = ( selected < selectedPos ) ? 1 : selected - selectedPos + 1 ; let len = ( numPages < start + num - 1 ) ? numPages - start + 1 : num ; return Array . apply ( null , Array ( len ) ) . map ( ( u , i ) => start + i ) ; }

Returns an array with the range of pages to be displayed according to the params passed
@param {Number} selected The selected page number
@param {Number} numPages The total number of pages
@param {Number} num      The number of pages to display
@return {Array<Number>}


function showTasks(tasks) {
  const taskList = Object.keys(tasks);
  if (taskList.length) {
    taskList.forEach((task) => {
      process.stdout.write(`Task Name: '${task}'`);
      if (tasks[task].description) {
        process.stdout.write(` - Description: ${tasks[task].description}`);
      }
      process.stdout.write('\n');
    });
  } else {
    process.stdout.write('No tasks available.\n');
  }
}

function
showTasks
(
tasks
)
{
const
taskList
=
Object
.
keys
(
tasks
)
;
if
(
taskList
.
length
)
{
taskList
.
forEach
(
(
task
)
=>
{
process
.
stdout
.
write
(
`
${
task
}
`
)
;
if
(
tasks
[
task
]
.
description
)
{
process
.
stdout
.
write
(
`
${
tasks
[
task
]
.
description
}
`
)
;
}
process
.
stdout
.
write
(
'\n'
)
;
}
)
;
}
else
{
process
.
stdout
.
write
(
'No tasks available.\n'
)
;
}
}

Show Tasks from a Plugin along with Description.
@param {object} tasks - Tasks object returned from plugin.

Show Tasks from a Plugin along with Description .


function sh(cmd, exitOnError, cb) {
  const child = exec(cmd, {
    encoding: 'utf8',
    timeout: 1000 * 60 * 2, // 2 min; just want to make sure nothing gets detached forever.
  });
  let stdout = '';
  child.stdout.on('data', (data) => {
    stdout += data;
    process.stdout.write(data);
  });
  child.stderr.on('data', (data) => {
    process.stdout.write(data);
  });
  child.on('close', (code) => {
    if (code > 0) {
      if (exitOnError) {
        if (typeof cb === 'function') {
          cb(new Error(`Error with code ${code} after running: ${cmd}`));
        } else {
          process.stdout.write(`Error with code ${code} after running: ${cmd} \n`);
          process.exit(code);
        }
      } else {
        notifier.notify({
          title: cmd,
          message: stdout,
          sound: true,
        });
      }
    }
    if (typeof cb === 'function') cb();
  });
}

Run shell command
@param cmd {string} - Command to run
@param exitOnError {boolean} - If that should exit non-zero or carry one.
@param cb {function} - Callback to fire when done.


function readYamlFile(file, cb) {
  fs.readFile(file, 'utf8', (err, data) => {
    if (err) throw err;
    cb(yaml.safeLoad(data));
  });
}

function readYamlFile ( file , cb ) { fs . readFile ( file , 'utf8' , ( err , data ) => { if ( err ) throw err ; cb ( yaml . safeLoad ( data ) ) ; } ) ; }

Read Yaml File into Object
@param {string} file - File path
@param {function} cb - Callback with data
@see readYamlFileSync


function writeYamlFile(file, data, cb) {
  fs.writeFile(file, yaml.safeDump(data), () => {
    if (cb) cb();
  });
}

function writeYamlFile ( file , data , cb ) { fs . writeFile ( file , yaml . safeDump ( data ) , ( ) => { if ( cb ) cb ( ) ; } ) ; }

Write Yaml string to File
@param {string} file - File path
@param {object} data - Object to turn into Yaml
@param {function} cb - Optional callback when done
@see writeYamlFileSync


function middleware(file, options) {
  var matcher = new RegExp("\\.(?:"+ middleware.extensions.join("|")+")$")
  if (!matcher.test(file)) return through();

  var input = '';
  var write = function (buffer) {
    input += buffer;
  }

  var end = function () {
    this.queue(createModule(input, options));
    this.queue(null);
  }

  return through(write, end);

}

function middleware ( file , options ) { var matcher = new RegExp ( "\\.(?:" + middleware . extensions . join ( "|" ) + ")$" ) if ( ! matcher . test ( file ) ) return through ( ) ; var input = '' ; var write = function ( buffer ) { input += buffer ; } var end = function ( ) { this . queue ( createModule ( input , options ) ) ; this . queue ( null ) ; } return through ( write , end ) ; }

create middleware for handling shader files


function createModule(body, options) {
      body = middleware.sanitize(body)
      if (String(options.parameterize) !== 'false') {
          body = middleware.parameterise(body)
      }
      if (options.module === "es6" || options.module === "es2015") {
          var module = 'export default ' + body + ';\n';
      }
      else {
          var module = 'module.exports = ' + body + ';\n';
      }
      return module
    }

function
createModule
(
body
,
options
)
{
body
=
middleware
.
sanitize
(
body
)
if
(
String
(
options
.
parameterize
)
!==
'false'
)
{
body
=
middleware
.
parameterise
(
body
)
}
if
(
options
.
module
===
"es6"
||
options
.
module
===
"es2015"
)
{
var
module
=
'export default '
+
body
+
';\n'
;
}
else
{
var
module
=
'module.exports = '
+
body
+
';\n'
;
}
return
module
}


function(schema,definition) {
        return _.reduce(schema, function(memo, field) {
           // console.log('definition normalize');console.log(definition);
            // Marshal mysql DESCRIBE to waterline collection semantics
            var attrName = field.COLUMN_NAME.toLowerCase();
            /*Comme oracle n'est pas sensible à la casse, la liste des colonnes retournées est differentes de celle enregistrée dans le schema,
             ce qui pose des problèmes à waterline*/
            Object.keys(definition).forEach(function (key){
                if(attrName === key.toLowerCase()) attrName = key;
            });
            var type = field.DATA_TYPE;

            // Remove (n) column-size indicators
            type = type.replace(/\([0-9]+\)$/, '');

            memo[attrName] = {
                type: type
                        // defaultsTo: '',
                        //autoIncrement: field.Extra === 'auto_increment'
            };

            if (field.primaryKey) {
                memo[attrName].primaryKey = field.primaryKey;
            }

            if (field.unique) {
                memo[attrName].unique = field.unique;
            }

            if (field.indexed) {
                memo[attrName].indexed = field.indexed;
            }
            return memo;
        }, {});
    }

Convert mysql format to standard javascript object


function(collectionName, values, key) {
        return sql.build(collectionName, values, sql.prepareValue, ', ', key);
    }

function
(
collectionName
,
values
,
key
)
{
return
sql
.
build
(
collectionName
,
values
,
sql
.
prepareValue
,
', '
,
key
)
;
}

Create a value csv for a DQL query key => optional, overrides the keys in the dictionary

Create a value csv for a DQL query key = > optional overrides the keys in the dictionary


function(collectionName, where, key, parentKey) {
        return sql.build(collectionName, where, sql.predicate, ' AND ', undefined, parentKey);
    }

function
(
collectionName
,
where
,
key
,
parentKey
)
{
return
sql
.
build
(
collectionName
,
where
,
sql
.
predicate
,
' AND '
,
undefined
,
parentKey
)
;
}

Starting point for predicate evaluation parentKey => if set, look for comparators and apply them to the parent key

Starting point for predicate evaluation parentKey = > if set look for comparators and apply them to the parent key


function(collectionName, criterion, key, parentKey) {
        var queryPart = '';

        if (parentKey) {
            return sql.prepareCriterion(collectionName, criterion, key, parentKey);
        }

        // OR
        if (key.toLowerCase() === 'or') {
            queryPart = sql.build(collectionName, criterion, sql.where, ' OR ');
            return ' ( ' + queryPart + ' ) ';
        }

        // AND
        else if (key.toLowerCase() === 'and') {
            queryPart = sql.build(collectionName, criterion, sql.where, ' AND ');
            return ' ( ' + queryPart + ' ) ';
        }

        // IN
        else if (_.isArray(criterion)) {
            queryPart = sql.prepareAttribute(collectionName, null, key) + " IN (" + sql.values(collectionName, criterion, key) + ")";
            return queryPart;
        }

        // LIKE
        else if (key.toLowerCase() === 'like') {
            return sql.build(collectionName, criterion, function(collectionName, value, attrName) {
                var attrStr = sql.prepareAttribute(collectionName, value, attrName);

                attrStr = attrStr.replace(/'/g, '"');

                // TODO: Handle regexp criterias
                if (_.isRegExp(value)) {
                    throw new Error('RegExp LIKE criterias not supported by the MySQLAdapter yet.  Please contribute @ http://github.com/balderdashy/sails-mysql');
                }

                var valueStr = sql.prepareValue(collectionName, value, attrName);

                // Handle escaped percent (%) signs [encoded as %%%]
                valueStr = valueStr.replace(/%%%/g, '\\%');
                var condition = (attrStr + " LIKE " + valueStr);

                //condition = condition.replace(/'/g, '"');

                return condition;
            }, ' AND ');
        }

        // NOT
        else if (key.toLowerCase() === 'not') {
            throw new Error('NOT not supported yet!');
        }

        // Basic criteria item
        else {
            return sql.prepareCriterion(collectionName, criterion, key);
        }

    }

Recursively parse a predicate calculus and build a SQL query


function sqlTypeCast(type, attrName) {
    type = type && type.toLowerCase();

    switch (type) {
        case 'string':
            return 'VARCHAR2(255)';

        case 'text':
        case 'array':
        case 'json':
            return 'VARCHAR2(255)';

        case 'boolean':
            return 'NUMBER(1) CHECK("' + attrName + '" IN (0,1))';

        case 'int':
        case 'integer':
            return 'NUMBER';

        case 'float':
        case 'double':
            return 'FLOAT';

        case 'date':
            return 'DATE';

        case 'datetime':
            return 'TIMESTAMP';

        case 'binary':
            return 'BLOB';

        default:
            console.error("Unregistered type given: " + type);
            return "TEXT";
    }
}

function
sqlTypeCast
(
type
,
attrName
)
{
type
=
type
&&
type
.
toLowerCase
(
)
;
switch
(
type
)
{
case
'string'
:
return
'VARCHAR2(255)'
;
case
'text'
:
case
'array'
:
case
'json'
:
return
'VARCHAR2(255)'
;
case
'boolean'
:
return
'NUMBER(1) CHECK("'
+
attrName
+
'" IN (0,1))'
;
case
'int'
:
case
'integer'
:
return
'NUMBER'
;
case
'float'
:
case
'double'
:
return
'FLOAT'
;
case
'date'
:
return
'DATE'
;
case
'datetime'
:
return
'TIMESTAMP'
;
case
'binary'
:
return
'BLOB'
;
default
:
console
.
error
(
"Unregistered type given: "
+
type
)
;
return
"TEXT"
;
}
}

Cast waterline types into SQL data types


function validSubAttrCriteria(c) {
    return _.isObject(c) && (
            !_.isUndefined(c.not) || !_.isUndefined(c.greaterThan) || !_.isUndefined(c.lessThan) ||
            !_.isUndefined(c.greaterThanOrEqual) || !_.isUndefined(c.lessThanOrEqual) || !_.isUndefined(c['<']) ||
            !_.isUndefined(c['<=']) || !_.isUndefined(c['!']) || !_.isUndefined(c['>']) || !_.isUndefined(c['>=']) ||
            !_.isUndefined(c.startsWith) || !_.isUndefined(c.endsWith) || !_.isUndefined(c.contains) || !_.isUndefined(c.like));
}

function validSubAttrCriteria ( c ) { return _ . isObject ( c ) && ( ! _ . isUndefined ( c . not ) || ! _ . isUndefined ( c . greaterThan ) || ! _ . isUndefined ( c . lessThan ) || ! _ . isUndefined ( c . greaterThanOrEqual ) || ! _ . isUndefined ( c . lessThanOrEqual ) || ! _ . isUndefined ( c [ '<' ] ) || ! _ . isUndefined ( c [ '<=' ] ) || ! _ . isUndefined ( c [ '!' ] ) || ! _ . isUndefined ( c [ '>' ] ) || ! _ . isUndefined ( c [ '>=' ] ) || ! _ . isUndefined ( c . startsWith ) || ! _ . isUndefined ( c . endsWith ) || ! _ . isUndefined ( c . contains ) || ! _ . isUndefined ( c . like ) ) ; }

Return whether this criteria is valid as an object inside of an attribute


function processIconTemplate(srcFile, destFile, data, cb) {
  fs.readFile(srcFile, 'utf8', (err, srcFileContents) => {
    if (err) throw err;
    const result = template(srcFileContents, {
      // Use custom template delimiters of `{{` and `}}`.
      interpolate: /{{([\s\S]+?)}}/g,
      // Use custom evaluate delimiters of `{%` and `%}`.
      evaluate: /{%([\s\S]+?)%}/g,
    })(data);
    fs.writeFile(destFile, result, cb);
  });
}

Process Icon Templates
@param {string} srcFile - Path to lodash template file.
@param {string} destFile - Path to write processed file to.
@param {object} data - Data to pass to template.
@param {function} cb - Callback for when done.


function icons(done) {
    const stream = gulp.src(config.src)
      .pipe(iconfont({
        fontName: config.iconName,
        appendUniconde: true,
        formats: config.formats,
        timestamp: config.useTimestamp ? getTimestamp() : 0,
        autohint: config.autohint,
        normalize: config.normalize,
      }));
    // write icons to disk
    stream.pipe(gulp.dest(config.dest));

    // reload browser
    core.events.emit('reload');

    if (config.templates.enabled && config.templates.sets.length) {
      stream.on('glyphs', (glyphs) => {
        // console.log(glyphs);
        const iconData = {
          glyphs: glyphs.map(glyph => ({ // returns the object
            name: glyph.name,
            content: glyph.unicode[0].toString(16).toUpperCase(),
          })),
          fontName: config.iconName,
          fontPath: config.fontPathPrefix,
          classNamePrefix: config.classNamePrefix,
        };

        Promise.all(config.templates.sets.map(set => new Promise((resolve, reject) => {
          processIconTemplate(set.src, set.dest, iconData, (err) => {
            if (err) reject();
            resolve();
          });
        }))).then(() => done());
      });
    } else {
      done();
    }
  }

function
icons
(
done
)
{
const
stream
=
gulp
.
src
(
config
.
src
)
.
pipe
(
iconfont
(
{
fontName
:
config
.
iconName
,
appendUniconde
:
true
,
formats
:
config
.
formats
,
timestamp
:
config
.
useTimestamp
getTimestamp
(
)
:
0
,
autohint
:
config
.
autohint
,
normalize
:
config
.
normalize
,
}
)
)
;
// write icons to disk
stream
.
pipe
(
gulp
.
dest
(
config
.
dest
)
)
;
// reload browser
core
.
events
.
emit
(
'reload'
)
;
if
(
config
.
templates
.
enabled
&&
config
.
templates
.
sets
.
length
)
{
stream
.
on
(
'glyphs'
,
(
glyphs
)
=>
{
// console.log(glyphs);
const
iconData
=
{
glyphs
:
glyphs
.
map
(
glyph
=>
(
{
// returns the object
name
:
glyph
.
name
,
content
:
glyph
.
unicode
[
0
]
.
toString
(
16
)
.
toUpperCase
(
)
,
}
)
)
,
fontName
:
config
.
iconName
,
fontPath
:
config
.
fontPathPrefix
,
classNamePrefix
:
config
.
classNamePrefix
,
}
;
Promise
.
all
(
config
.
templates
.
sets
.
map
(
set
=>
new
Promise
(
(
resolve
,
reject
)
=>
{
processIconTemplate
(
set
.
src
,
set
.
dest
,
iconData
,
(
err
)
=>
{
if
(
err
)
reject
(
)
;
resolve
(
)
;
}
)
;
}
)
)
)
.
then
(
(
)
=>
done
(
)
)
;
}
)
;
}
else
{
done
(
)
;
}
}

Build font icons from SVG files and optionally make scss and demo templates.
@param done {function} - Callback when all done.

Build font icons from SVG files and optionally make scss and demo templates .


function injectData(tokenValue, options, key) {
    var data;
    if (~options.contentType.indexOf('application/json')) {
        data = options.data ? JSON.parse(options.data) : {};
        data[key] = tokenValue;
        options.data = JSON.stringify(data);
    } else {
        options.data += options.data ? '&' : '';
        options.data += key + '=' + tokenValue;
    }
}

function injectData ( tokenValue , options , key ) { var data ; if ( ~ options . contentType . indexOf ( 'application/json' ) ) { data = options . data ? JSON . parse ( options . data ) : { } ; data [ key ] = tokenValue ; options . data = JSON . stringify ( data ) ; } else { options . data += options . data ? '&' : '' ; options . data += key + '=' + tokenValue ; } }

Inject CSRF token via POST body

@param {string} tokenValue CSRF token value
@param {object} options jQuery prefilter options
@param {string} key POST data key


function injectQuery(tokenValue, options, param) {
    options.url += ~options.url.indexOf('?') ? '&' : '?';
    options.url += param + '=' + tokenValue;
}

function injectQuery ( tokenValue , options , param ) { options . url += ~ options . url . indexOf ( '?' ) ? '&' : '?' ; options . url += param + '=' + tokenValue ; }

Inject CSRF token via query param.

@param {string} tokenValue CSRF token value
@param {object} options jQuery prefilter options
@param {string} param Query param key


function homedir(username) {
  return username ? path.resolve(path.dirname(home), username) : home;
}

function homedir ( username ) { return username ? path . resolve ( path . dirname ( home ) , username ) : home ; }

Resolves the path to the user's home directory.

@param {String} [username]
Username of user whose path you seek.

@return {String}
The full path to the user's home directory.

Resolves the path to the user s home directory .


function (conn, cb) {
            if (LOG_DEBUG) {
                console.log("BEGIN tearDown");
            }

            if (typeof conn == 'function') {
                cb = conn;
                conn = null;
            }
            if (!conn) {
                connections = {};
                return cb();
            }
            if (!connections[conn])
                return cb();
            delete connections[conn];
            cb();
        }

function
(
conn
,
cb
)
{
if
(
LOG_DEBUG
)
{
console
.
log
(
"BEGIN tearDown"
)
;
}
if
(
typeof
conn
==
'function'
)
{
cb
=
conn
;
conn
=
;
}
if
(
!
conn
)
{
connections
=
{
}
;
return
cb
(
)
;
}
if
(
!
connections
[
conn
]
)
return
cb
(
)
;
delete
connections
[
conn
]
;
cb
(
)
;
}

OK
Fired when a model is unregistered, typically when the server
is killed. Useful for tearing-down remaining open connections,
etc.

@param  {Function} cb [description]
@return {[type]}      [description]
 Teardown a Connection OK

OK Fired when a model is unregistered typically when the server is killed . Useful for tearing - down remaining open connections etc .


function (connectionName, table, query, data, cb) {
            var connectionObject = connections[connectionName];
            if (LOG_DEBUG) {
                console.log("BEGIN query");
            }

            if (_.isFunction(data)) {
                cb = data;
                data = null;
            }

            // Run query
            if (!data)
                data = {};
            connectionObject.pool.getConnection(
                    function (err, connection)
                    {
                        if (err) {
                            return handleQueryError(err, 'query');;
                        }
                        if (LOG_QUERIES) {
                            console.log('Executing query: ' + query);
                        }
                        connection.execute(query, data, {outFormat: oracledb.OBJECT}, function (err, result) {
                            if (err) {
                                doRelease(connection);
                                return cb(err, result);
                            }

                            return castClobs(result, function (err, result) {
                                if (err) {
                                    doRelease(connection);
                                    return cb(err, result);
                                }
                                if (LOG_QUERIES) {
                                    console.log("Length: " + result.rows.length);
                                }
                                doRelease(connection);
                                return cb(err, result);
                            });
                        });
                    });
        }

function
(
connectionName
,
table
,
query
,
data
,
cb
)
{
var
connectionObject
=
connections
[
connectionName
]
;
if
(
LOG_DEBUG
)
{
console
.
log
(
"BEGIN query"
)
;
}
if
(
_
.
isFunction
(
data
)
)
{
cb
=
data
;
data
=
;
}
// Run query
if
(
!
data
)
data
=
{
}
;
connectionObject
.
pool
.
getConnection
(
function
(
err
,
connection
)
{
if
(
err
)
{
return
handleQueryError
(
err
,
'query'
)
;
;
}
if
(
LOG_QUERIES
)
{
console
.
log
(
'Executing query: '
+
query
)
;
}
connection
.
execute
(
query
,
data
,
{
outFormat
:
oracledb
.
OBJECT
}
,
function
(
err
,
result
)
{
if
(
err
)
{
doRelease
(
connection
)
;
return
cb
(
err
,
result
)
;
}
return
castClobs
(
result
,
function
(
err
,
result
)
{
if
(
err
)
{
doRelease
(
connection
)
;
return
cb
(
err
,
result
)
;
}
if
(
LOG_QUERIES
)
{
console
.
log
(
"Length: "
+
result
.
rows
.
length
)
;
}
doRelease
(
connection
)
;
return
cb
(
err
,
result
)
;
}
)
;
}
)
;
}
)
;
}


function dropTable(item, next) {

                // Build Query
                var query = 'DROP TABLE ' + utils.escapeName(item) + '';

                // Run Query

                connectionObject.pool.getConnection(function (err, connection) {
                    if (LOG_QUERIES) {
                        console.log('Executing query: ' + query);
                    }
                    connection.execute(query, {}, function (err, result) {
                        doRelease(connection);
                        next(null, result);
                    });
                });

            }

function
dropTable
(
item
,
next
)
{
// Build Query
var
query
=
'DROP TABLE '
+
utils
.
escapeName
(
item
)
+
''
;
// Run Query
connectionObject
.
pool
.
getConnection
(
function
(
err
,
connection
)
{
if
(
LOG_QUERIES
)
{
console
.
log
(
'Executing query: '
+
query
)
;
}
connection
.
execute
(
query
,
{
}
,
function
(
err
,
result
)
{
doRelease
(
connection
)
;
next
(
,
result
)
;
}
)
;
}
)
;
}


function (connectionName, table, attrName, attrDef, cb) {
            var connectionObject = connections[connectionName];
            if (LOG_DEBUG) {
                console.log("BEGIN addAttribute");
            }
            // Escape Table Name
            table = utils.escapeName(table);

            // Setup a Schema Definition
            var attrs = {};
            attrs[attrName] = attrDef;

            var _schema = utils.buildSchema(attrs);

            // Build Query
            var query = 'ALTER TABLE ' + table + ' ADD COLUMN ' + _schema;

            // Run Query
            connectionObject.pool.getConnection(
                    function (err, connection)
                    {
                        if (err) {
                            handleQueryError(err, 'addAttribute');
                            return;
                        }
                        if (LOG_QUERIES) {
                            console.log('Executing query: ' + query);
                        }
                        connection.execute(query, {}, {outFormat: oracledb.OBJECT}, function __ADD_ATTRIBUTE__(err, result) {
                            /* Release the connection back to the connection pool */
                            doRelease(connection);
                            if (err)
                                return cb(handleQueryError(err, 'addAttribute'));
                            cb(null, result.rows);
                        });
                    });

        }


function(connectionName, table, options, data, cb) {
            if (LOG_DEBUG) {
                console.log("BEGIN update");
            }
            //LIMIT in a oracle UPDATE command is not valid
            if (hop(options, 'limit')) {
                return cb(new Error('Your \'LIMIT ' + options.limit + '\' is not allowed in the Oracle DB UPDATE query.'));
            }

            var connectionObject = connections[connectionName];
            var collection = connectionObject.collections[table];

            var _schema = connectionObject.schema;
            var processor = new Processor(_schema);

            // Mixin WL Next connection overrides to sqlOptions
            var overrides = connectionOverrides[connectionName] || {};
            var _options = _.cloneDeep(sqlOptions);
            if (hop(overrides, 'wlNext')) {
                _options.wlNext = overrides.wlNext;
            }

            var sequel = new Sequel(_schema, _options);
            var query;
            // Build a query for the specific query strategy
            try {
                query = sequel.update(table, options, data);
            } catch (e) {
                return cb(e);
            }

            query.query = query.query.replace('RETURNING *', '');
            query.query = query.query.replace( /\$/g, ':');
            query.query = query.query.replace(' AS ', " ");

            var keys = Object.keys(data);
            var j = 1;
            for (j; j < keys.length + 1; j++) {
                query.query = query.query.replace(":" + j, ":" + keys[j - 1]);
            }

            var keysoptions = Object.keys(options.where);
            var oraOptions = {where: {}};
            for(var k=0; k <keysoptions.length; k++){
                oraOptions.where[ "where"+keysoptions[k] ] = options.where[ keysoptions[k] ];
                data["where"+keysoptions[k]] = options.where[ keysoptions[k] ];
            }
            var keysoptions = Object.keys(oraOptions.where);
            for (var z = keys.length; z < keys.length + keysoptions.length + 1; z++) {
                query.query = query.query.replace(":" + z, ":" + keysoptions[z - 1 - keys.length]);
            }

            // Run Query
            connectionObject.pool.getConnection(
                    function (err, connection)
                    {
                        if (err) {
                            handleQueryError(err, 'create');
                            return;
                        }
                        if (LOG_QUERIES) {
                            console.log('Executing query: ' + query.query);
                        }
                        connection.execute(query.query, data, {/*outFormat: oracledb.OBJECT, */autoCommit: false}, function __CREATE__(err, result) {

                            if (err) {
                                // Release the connection back to the connection pool
                                return connection.rollback(function(rollerr) {
                                	doRelease(connection);
                                	return cb(handleQueryError(err, 'update'));
                                });
                            }

                            // Build a query for the specific query strategy
                            try {
                                var _seqQuery = sequel.find(table, options);
                            } catch (e) {
                                return cb(handleQueryError(e, 'update'));
                            }

                            var findQuery = _seqQuery.query[0];
                            findQuery = findQuery.split( /\$/g).join(":");
                            findQuery = findQuery.split(" AS ").join(" ");

                            var keysOptionsSelect = Object.keys(oraOptions.where);
                            for (var z = 1; z < keysOptionsSelect.length + 1; z++) {
                                findQuery = findQuery.replace(":" + z, ":" + keysOptionsSelect[z-1]);
                            }

                            connection.execute(findQuery, oraOptions.where,  {outFormat: oracledb.OBJECT}, function __CREATE_SELECT__(err, result){

                                if (err){
                                    // Release the connection back to the connection pool
                                    return connection.rollback(function(rollerr) {
                                    	doRelease(connection);
                                    	return cb(handleQueryError(err, 'update_select'));
                                    });
                                }

                                // Cast special values
                                var values = [];
                                result.rows.forEach(function (row) {
                                    values.push(processor.cast(table, _.omit(row, 'LINE_NUMBER')));
                                });

                                connection.commit(function (err){

                                    // Release the connection back to the connection pool
                                    doRelease(connection);
                                    if (err){
                                        return cb(handleQueryError(err, 'update_commit'));
                                    }

                                    cb(null, values);
                                });
                            });
                        });
                    });

        }

Update one or more models in the collection - PENDIENTE


function(connectionName, table, options, cb) {
            if (LOG_DEBUG) {
                console.log("BEGIN destroy");
            }

            var connectionObject = connections[connectionName];
            var collection = connectionObject.collections[table];

            var _schema = connectionObject.schema;

            // Mixin WL Next connection overrides to sqlOptions
            var overrides = connectionOverrides[connectionName] || {};
            var _options = _.cloneDeep(sqlOptions);
            if (hop(overrides, 'wlNext')) {
                _options.wlNext = overrides.wlNext;
            }

            var sequel = new Sequel(_schema, _options);
            var query;

            // Build a query for the specific query strategy
            try {
                query = sequel.destroy(table, options);
            } catch (e) {
                return cb(e);
            }

            query.query = query.query.replace('RETURNING *', '');
            query.query = query.query.replace( /\$/g, ':');
            query.query = query.query.replace(" AS ", " ");

            // Run Query
            connectionObject.pool.getConnection(
                    function (err, connection)
                    {
                        if (err) {
                            handleQueryError(err, 'destroy');
                            return;
                        }
                        if (LOG_QUERIES) {
                            console.log('Executing query: ' + query.query);
                            console.log('Data for query: ' + JSON.stringify(query.values));
                        }
                        connection.execute(query.query, query.values, {autoCommit: true, outFormat: oracledb.OBJECT}, function __DELETE__(err, result) {
                            if (err) {
                                /* Release the connection back to the connection pool */
                                doRelease(connection);
                                return cb(handleQueryError(err, 'destroy'));
                            }

                            /* Release the connection back to the connection pool */
                            doRelease(connection);

                            cb(null, result.rows);

                        });
                    });

        }

Delete one or more models from the collection - PENDIENTE


function printError (message) {
  arrayify(message).forEach(function (msg) {
    console.error(ansi.format(msg, 'red'))
  })
}

function printError ( message ) { arrayify ( message ) . forEach ( function ( msg ) { console . error ( ansi . format ( msg , 'red' ) ) } ) }

Prints one or more strings in red to stderr.

@param {string | string[]} - input message(s)
@static

Prints one or more strings in red to stderr .