function(str, gga) {

      if (gga.length !== 16) {
        throw new Error('Invalid GGA length: ' + str);
      }

      /*
       11
       1         2       3 4        5 6 7  8   9  10 |  12 13  14  15
       |         |       | |        | | |  |   |   | |   | |   |   |
       $--GGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh

       1) Time (UTC)
       2) Latitude
       3) N or S (North or South)
       4) Longitude
       5) E or W (East or West)
       6) GPS Quality Indicator,
       0 = Invalid, 1 = Valid SPS, 2 = Valid DGPS, 3 = Valid PPS
       7) Number of satellites in view, 00 - 12
       8) Horizontal Dilution of precision, lower is better
       9) Antenna Altitude above/below mean-sea-level (geoid)
       10) Units of antenna altitude, meters
       11) Geoidal separation, the difference between the WGS-84 earth
       ellipsoid and mean-sea-level (geoid), '-' means mean-sea-level below ellipsoid
       12) Units of geoidal separation, meters
       13) Age of differential GPS data, time in seconds since last SC104
       type 1 or 9 update, null field when DGPS is not used
       14) Differential reference station ID, 0000-1023
       15) Checksum
       */

      return {
        'time': parseTime(gga[1]),
        'lat': parseCoord(gga[2], gga[3]),
        'lon': parseCoord(gga[4], gga[5]),
        'alt': parseDist(gga[9], gga[10]),
        'quality': parseGGAFix(gga[6]),
        'satellites': parseNumber(gga[7]),
        'hdop': parseNumber(gga[8]), // dilution
        'geoidal': parseDist(gga[11], gga[12]), // aboveGeoid
        'age': parseNumber(gga[13]), // dgps time since update
        'stationID': parseNumber(gga[14]) // dgpsReference??
      };
    }


function(str, gsa) {

      if (gsa.length !== 19 && gsa.length !== 20) {
        throw new Error('Invalid GSA length: ' + str);
      }

      /*
       eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C
       eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35

       1    = Mode:
       M=Manual, forced to operate in 2D or 3D
       A=Automatic, 3D/2D
       2    = Mode:
       1=Fix not available
       2=2D
       3=3D
       3-14 = PRNs of Satellite Vehicles (SVs) used in position fix (null for unused fields)
       15   = PDOP
       16   = HDOP
       17   = VDOP
       (18) = systemID NMEA 4.10
       18   = Checksum
       */

      var sats = [];
      for (var i = 3; i < 15; i++) {

        if (gsa[i] !== '') {
          sats.push(parseInt(gsa[i], 10));
        }
      }

      return {
        'mode': parseGSAMode(gsa[1]),
        'fix': parseGSAFix(gsa[2]),
        'satellites': sats,
        'pdop': parseNumber(gsa[15]),
        'hdop': parseNumber(gsa[16]),
        'vdop': parseNumber(gsa[17]),
        'systemId': gsa.length > 19 ? parseNumber(gsa[18]) : null
      };
    }


function(str, rmc) {

      if (rmc.length !== 13 && rmc.length !== 14 && rmc.length !== 15) {
        throw new Error('Invalid RMC length: ' + str);
      }

      /*
       $GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a*hh

       RMC  = Recommended Minimum Specific GPS/TRANSIT Data
       1    = UTC of position fix
       2    = Data status (A-ok, V-invalid)
       3    = Latitude of fix
       4    = N or S
       5    = Longitude of fix
       6    = E or W
       7    = Speed over ground in knots
       8    = Track made good in degrees True
       9    = UT date
       10   = Magnetic variation degrees (Easterly var. subtracts from true course)
       11   = E or W
       (12) = NMEA 2.3 introduced FAA mode indicator (A=Autonomous, D=Differential, E=Estimated, N=Data not valid)
       (13) = NMEA 4.10 introduced nav status
       12   = Checksum
       */

      return {
        'time': parseTime(rmc[1], rmc[9]),
        'status': parseRMC_GLLStatus(rmc[2]),
        'lat': parseCoord(rmc[3], rmc[4]),
        'lon': parseCoord(rmc[5], rmc[6]),
        'speed': parseKnots(rmc[7]),
        'track': parseNumber(rmc[8]), // heading
        'variation': parseRMCVariation(rmc[10], rmc[11]),
        'faa': rmc.length > 13 ? parseFAA(rmc[12]) : null,
        'navStatus': rmc.length > 14 ? rmc[13] : null
      };
    }


function(str, gsv) {

      if (gsv.length % 4 % 3 === 0) {
        throw new Error('Invalid GSV length: ' + str);
      }

      /*
       $GPGSV,1,1,13,02,02,213,,03,-3,000,,11,00,121,,14,13,172,05*67

       1    = Total number of messages of this type in this cycle
       2    = Message number
       3    = Total number of SVs in view
       repeat [
       4    = SV PRN number
       5    = Elevation in degrees, 90 maximum
       6    = Azimuth, degrees from true north, 000 to 359
       7    = SNR (signal to noise ratio), 00-99 dB (null when not tracking, higher is better)
       ]
       N+1   = signalID NMEA 4.10
       N+2   = Checksum
       */

      var sats = [];

      for (var i = 4; i < gsv.length - 3; i += 4) {

        var prn = parseNumber(gsv[i]);
        var snr = parseNumber(gsv[i + 3]);
        /*
         Plot satellites in Radar chart with north on top
         by linear map elevation from 0° to 90° into r to 0

         centerX + cos(azimuth - 90) * (1 - elevation / 90) * radius
         centerY + sin(azimuth - 90) * (1 - elevation / 90) * radius
         */
        sats.push({
          'prn': prn,
          'elevation': parseNumber(gsv[i + 1]),
          'azimuth': parseNumber(gsv[i + 2]),
          'snr': snr,
          'status': prn !== null ? (snr !== null ? 'tracking' : 'in view') : null
        });
      }

      return {
        'msgNumber': parseNumber(gsv[2]),
        'msgsTotal': parseNumber(gsv[1]),
        //'satsInView'  : parseNumber(gsv[3]), // Can be obtained by satellites.length
        'satellites': sats,
        'signalId': gsv.length % 4 === 2 ? parseNumber(gsv[gsv.length - 2]) : null // NMEA 4.10 addition
      };
    }


function computeIndexChunks(buffer) {
  var BLOCK_SIZE = 65536;
  var view = new jDataView(buffer, 0, buffer.byteLength, true /* little endian */);

  var minBlockIndex = Infinity;
  var contigStartOffsets = [];
  view.getInt32();  // magic
  var n_ref = view.getInt32();
  for (var j = 0; j < n_ref; j++) {
    contigStartOffsets.push(view.tell());
    var n_bin = view.getInt32();
    for (var i = 0; i < n_bin; i++) {
      view.getUint32();  // bin ID
      var n_chunk = view.getInt32();
      view.skip(n_chunk * 16);
    }
    var n_intv = view.getInt32();
    if (n_intv) {
      var offset = VirtualOffset.fromBlob(view.getBytes(8), 0),
          coffset = offset.coffset + (offset.uoffset ? BLOCK_SIZE : 0);
      minBlockIndex = coffset ? Math.min(coffset, minBlockIndex) : BLOCK_SIZE;
      view.skip((n_intv - 1) * 8);
    }
  }
  contigStartOffsets.push(view.tell());

  // At this point, `minBlockIndex` should be non-Infinity (see #405 & #406)
  return {
    chunks: _.zip(_.initial(contigStartOffsets), _.rest(contigStartOffsets)),
    minBlockIndex
  };
}

In the event that index chunks aren't available from an external source, it winds up saving time to do a fast pass over the data to compute them. This allows us to parse a single contig at a time using jBinary.

In the event that index chunks aren t available from an external source it winds up saving time to do a fast pass over the data to compute them . This allows us to parse a single contig at a time using jBinary .


function (el) {
            var genericCloseButton;

            if ($(el).data('popupoptions').closebuttonmarkup) {
                genericCloseButton = $(options.closebuttonmarkup).addClass(el.id + '_close');
            } else {
                genericCloseButton = '<button class="popup_close ' + el.id + '_close" title="Close" aria-label="Close">×</button>';
            }

            if ($(el).data('popup-initialized')){
                $(el).append(genericCloseButton);
            }

        }

Add-close-button method

@param {object} el - popup instance DOM node


function (el, ordinal, func) {
        var options = $(el).data('popupoptions');
        var openelement;
        var elementclicked;
        if (typeof options === 'undefined') return;
        openelement =  options.openelement ? options.openelement : ('.' + el.id + opensuffix);
        elementclicked = $(openelement + '[data-popup-ordinal="' + ordinal + '"]');
        if (typeof func == 'function') {
            func.call($(el), el, elementclicked);
        }
    }

function ( el , ordinal , func ) { var options = $ ( el ) . data ( 'popupoptions' ) ; var openelement ; var elementclicked ; if ( typeof options === 'undefined' ) return ; openelement = options . openelement ? options . openelement : ( '.' + el . id + opensuffix ) ; elementclicked = $ ( openelement + '[data-popup-ordinal="' + ordinal + '"]' ) ; if ( typeof func == 'function' ) { func . call ( $ ( el ) , el , elementclicked ) ; } }

Callback event calls

@param {object} el - popup instance DOM node
@param {number} ordinal - order number of an `open` element
@param {function} func - callback function


function (el) {
        var bounding = el.getBoundingClientRect();
        return (
            bounding.top >= 0 &&
            bounding.left >= 0 &&
            bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }

function ( el ) { var bounding = el . getBoundingClientRect ( ) ; return ( bounding . top >= 0 && bounding . left >= 0 && bounding . bottom <= ( window . innerHeight || document . documentElement . clientHeight ) && bounding . right <= ( window . innerWidth || document . documentElement . clientWidth ) ) ; }

Check if element is fully in viewport

@param {object} el - popup instance DOM node


function main() {
    var app = new App();
    function intentHandler(url) {
        Auth0Cordova.onRedirectUri(url);
    }
    window.handleOpenURL = intentHandler;
    app.run('#app');
}

function main ( ) { var app = new App ( ) ; function intentHandler ( url ) { Auth0Cordova . onRedirectUri ( url ) ; } window . handleOpenURL = intentHandler ; app . run ( '#app' ) ; }

In a real world app, you should replace this with React or Angular or jQuery.

In a real world app you should replace this with React or Angular or jQuery .


function WebView() {
  this.tab = null;
  this.handler = null;
  this.open = this.open.bind(this);
  this.handleFirstLoadEnd = this.handleFirstLoadEnd.bind(this);
  this.handleLoadError = this.handleLoadError.bind(this);
  this.handleExit = this.handleExit.bind(this);
  this.clearEvents = this.clearEvents.bind(this);
  this.close = this.close.bind(this);
}

function WebView ( ) { this . tab = null ; this . handler = null ; this . open = this . open . bind ( this ) ; this . handleFirstLoadEnd = this . handleFirstLoadEnd . bind ( this ) ; this . handleLoadError = this . handleLoadError . bind ( this ) ; this . handleExit = this . handleExit . bind ( this ) ; this . clearEvents = this . clearEvents . bind ( this ) ; this . close = this . close . bind ( this ) ; }

Fallback to old WebView where SFSafariViewController is not supported


function processProps(props) {
  const { title, label, key, value } = props;
  const cloneProps = { ...props };

  // Warning user not to use deprecated label prop.
  if (label && !title) {
    if (!warnDeprecatedLabel) {
      warning(false, "'label' in treeData is deprecated. Please use 'title' instead.");
      warnDeprecatedLabel = true;
    }

    cloneProps.title = label;
  }

  if (!key) {
    cloneProps.key = value;
  }

  return cloneProps;
}

Use `rc-tree` convertDataToTree to convert treeData to TreeNodes.
This will change the label to title value

Use rc - tree convertDataToTree to convert treeData to TreeNodes . This will change the label to title value


function writeHeaders(file, headers, only = null) {
  for (let name in headers) {
    let value = headers[name];
    if (only && !match(name, only))
      continue;
    if (Array.isArray(value))
      for (let item of value)
        file.write(`${name}: ${item}\n`);
    else
      file.write(`${name}: ${value}\n`);
  }
}

function writeHeaders ( file , headers , only = null ) { for ( let name in headers ) { let value = headers [ name ] ; if ( only && ! match ( name , only ) ) continue ; if ( Array . isArray ( value ) ) for ( let item of value ) file . write ( ` ${ name } ${ item } \n ` ) ; else file . write ( ` ${ name } ${ value } \n ` ) ; } }

Write headers to the File object.  Optional argument `only` is an array of regular expressions; only headers matching one of these expressions are written.

Write headers to the File object . Optional argument only is an array of regular expressions ; only headers matching one of these expressions are written .


function match(name, regexps){
  for (let regexp of regexps)
    if (regexp.test(name))
      return true;
  return false;
}

function match ( name , regexps ) { for ( let regexp of regexps ) if ( regexp . test ( name ) ) return true ; return false ; }

Returns true if header name matches one of the regular expressions.

Returns true if header name matches one of the regular expressions .


function showHelpAndDie(message) {
        if (message) {
            console.error(message);
        }
        console.error(commander.helpInformation());
        process.exit(1);
    }

function showHelpAndDie ( message ) { if ( message ) { console . error ( message ) ; } console . error ( commander . helpInformation ( ) ) ; process . exit ( 1 ) ; }

This is a bit crappy as it uses the global commander variable. But whaeva.

This is a bit crappy as it uses the global commander variable . But whaeva .


function robohydraHeadType(settings) {
    var parentClass = settings.parentClass || RoboHydraHead;

    var newConstructorFunction = function(props) {
        if (!props && settings.defaultProps) {
            deprecationWarning("deprecated 'defaultProps', please use 'defaultPropertyObject' instead");
            props = settings.defaultProps;
        }
        props = props || settings.defaultPropertyObject || {};

        // Checks mandatory and optional properties
        this._importProperties(newConstructorFunction, props);

        var parentPropBuilder =
                settings.parentPropertyBuilder || function() { return {}; };
        if (settings.parentPropBuilder) {
            deprecationWarning("deprecated 'parentPropBuilder', please use 'parentPropertyBuilder' instead");
            parentPropBuilder = settings.parentPropBuilder;
        }
        var parentProps = parentPropBuilder.call(this);
        IMPLICIT_OPTIONAL_PROPS.forEach(function(p) {
            var propName = typeof p === 'object' ? p.name : p;
            if (! (propName in parentProps)) {
                parentProps[propName] = this[propName];
            }
        }, this);
        parentClass.call(this, parentProps);

        this.type = settings.name || '<undefined>';
        if (typeof settings.init === 'function') {
            settings.init.call(this);
        }
    };

    newConstructorFunction.mandatoryProperties =
        settings.mandatoryProperties || [];
    newConstructorFunction.optionalProperties =
        (settings.optionalProperties || []).concat(IMPLICIT_OPTIONAL_PROPS);
    newConstructorFunction.prototype = new parentClass();

    return newConstructorFunction;
}

Convenience function to create new types of heads. It takes care of a bit of inheritance hassle.

Convenience function to create new types of heads . It takes care of a bit of inheritance hassle .


function proxyRequest(req, res, proxyTo, opts) {
        opts = opts || {};
        var httpRequestFunction  = opts.httpRequestFunction  || http.request;
        var httpsRequestFunction = opts.httpsRequestFunction || https.request;
        var setHostHeader = opts.setHostHeader;

        var proxyUrl = proxyTo;
        if (typeof(proxyTo) === 'string') {
            proxyUrl = url.parse(proxyTo, true);
        }
        var proxyToHost = proxyUrl.hostname;
        var proxyToPort = proxyUrl.port ||
                (proxyUrl.protocol === 'https:' ? 443 : 80);
        var proxyToPath = proxyUrl.pathname +
            (proxyUrl.search === null ? "" : proxyUrl.search);
        var requestFunction = (proxyUrl.protocol === 'https:') ?
                httpsRequestFunction : httpRequestFunction;
        var headers = {};
        for (var h in req.headers) { headers[h] = req.headers[h]; }
        if (setHostHeader) {
            headers.host = proxyToHost +
                (proxyUrl.port ? ":" + proxyUrl.port : "");
        }

        var proxyReq = requestFunction(
            {host: proxyToHost,
             port: proxyToPort,
             method: req.method,
             path: proxyToPath,
             headers: headers},
            function (proxyRes) {
                // Copy over headers and status code from proxied request
                res.statusCode = proxyRes.statusCode;
                res.headers    = proxyRes.headers;

                proxyRes.on("data", function (chunk) {
                    res.write(chunk);
                });

                proxyRes.on("end", function () {
                    res.end();
                });
            });

        proxyReq.on('error', function (err) {
            res.statusCode = 502;
            res.send('Bad Gateway! Could not proxy request. Invalid host or proxy destination down? Reported error was: ' + err);
        });

        if (req.rawBody) {
            proxyReq.write(req.rawBody);
        }
        proxyReq.end();
    }

Proxies the given request to the given URL, writing the result
in the given response object.

@method proxyRequest
@for robohydra
@param {Request} req The request object to proxy.
@param {Response} res The response object to write the result to.
@param {URL} proxyTo The URL to proxy to, either in the form of
a URL object (result of the url.parse method) or a string.
@param {Object} opts
@param {Function} opts.httpRequestFunction The http.request
function or a mock of it.
@param {Function} opts.httpsRequestFunction The https.request
function or a mock of it.
@param {Boolean} opts.setHostHeader Specifies if the "Host"
header should be set in the proxied request, so pretend as if
the original request was indeed intended for the final
URL. Defaults to false.

Proxies the given request to the given URL writing the result in the given response object .


function BigIq50LicenseProvider(bigIp, options) {
    const injectedLogger = options ? options.logger : undefined;
    let loggerOptions = options ? options.loggerOptions : undefined;

    if (injectedLogger) {
        this.logger = injectedLogger;
        util.setLogger(injectedLogger);
    } else {
        loggerOptions = loggerOptions || { logLevel: 'none' };
        loggerOptions.module = module;
        this.logger = Logger.getLogger(loggerOptions);
        util.setLoggerOptions(loggerOptions);
    }

    logger = this.logger;
    this.bigIp = bigIp;
}

function BigIq50LicenseProvider ( bigIp , options ) { const injectedLogger = options ? options . logger : undefined ; let loggerOptions = options ? options . loggerOptions : undefined ; if ( injectedLogger ) { this . logger = injectedLogger ; util . setLogger ( injectedLogger ) ; } else { loggerOptions = loggerOptions || { logLevel : 'none' } ; loggerOptions . module = module ; this . logger = Logger . getLogger ( loggerOptions ) ; util . setLoggerOptions ( loggerOptions ) ; } logger = this . logger ; this . bigIp = bigIp ; }

BigIq 5.0 license provider constructor

@class
@classdesc
Provides ability to get licenses from BIG-IQ 5.0 (and compatible versions).

@param {Object} bigIp                   - Base {@link BigIp} object.
@param {Object} [options]               - Optional parameters.
@param {Object} [options.logger]        - Logger to use. Or, pass loggerOptions to get your own logger.
@param {Object} [options.loggerOptions] - Options for the logger.
See {@link module:logger.getLogger} for details.

BigIq 5 . 0 license provider constructor


function listPrivateKey(keyType, folder, name, noRetry) {
    let privateKeyName;

    // Try with .key suffix first. If unsuccessful, retry without the .key suffix
    if (noRetry) {
        // If present, remove '.key' suffix
        privateKeyName = name.replace(REG_EXPS.KEY_SUFFIX, '');
    } else {
        // Append '.key' suffix, if not present
        privateKeyName = (name.match(REG_EXPS.KEY_SUFFIX)) ? name : `${name}.key`;
    }

    return util.runTmshCommand(`list sys ${keyType} /${folder}/${privateKeyName}`)
        .then((keyData) => {
            // If no result, retry if a retry hasn't occurred yet.
            if (!keyData) {
                if (!noRetry) {
                    return listPrivateKey(keyType, folder, name, true);
                }
                return q();
            }
            return q({ privateKeyName, keyData });
        })
        .catch((err) => {
            // If the object is not found (code: 01020036:3), retry if a retry hasn't occurred yet.
            const notFoundRegex = /01020036:3/;
            if (err.message.match(notFoundRegex) && !noRetry) {
                return listPrivateKey(keyType, folder, name, true);
            }
            return q.reject(err);
        });
}

List a private key by folder and name.

Will first search for a private key with a '.key' suffix, and then without a '.key' suffix

@param {String}  keyType      - Key Type to list. Examples: 'file ssl-key', crypto key
@param {String}  folder       - Folder in which to search for the private key.
@param {String}  name         - Name of the private key to search for
@param {Boolean} [noRetry]    - Whether or not to retry command with a different private key name.

@returns {Promise}   A promise which will be resolved with a dictionary containing the name of the
found private key, and the tmsh command response:

{
privateKeyName: <String>,
response: <String>
}


function createTrafficGroup(bigIp, trafficGroup) {
        let createGroup = true;
        bigIp.list('/tm/cm/traffic-group')
            .then((response) => {
                response.forEach((group) => {
                    if (group.name === trafficGroup) {
                        createGroup = false;
                    }
                });
                if (createGroup) {
                    return bigIp.create(
                        '/tm/cm/traffic-group',
                        {
                            name: trafficGroup,
                            partition: '/Common'
                        }
                    );
                }
                return q();
            })
            .catch((err) => {
                return q.reject(err);
            });
    }

function createTrafficGroup ( bigIp , trafficGroup ) { let createGroup = true ; bigIp . list ( '/tm/cm/traffic-group' ) . then ( ( response ) => { response . forEach ( ( group ) => { if ( group . name === trafficGroup ) { createGroup = false ; } } ) ; if ( createGroup ) { return bigIp . create ( '/tm/cm/traffic-group' , { name : trafficGroup , partition : '/Common' } ) ; } return q ( ) ; } ) . catch ( ( err ) => { return q . reject ( err ) ; } ) ; }

Creates a Traffic Group on BigIP, if the Traffic Group does not exist

@param {Object}  bigIp - bigIp client object
@param {String}  trafficGroup - Traffic Group name

@returns {Promise} Promise that will be resolved when Traffic Group is created,
already exists, or if an error occurs.

Creates a Traffic Group on BigIP if the Traffic Group does not exist


function becomeMaster(provider, bigIp, options) {
        let hasUcs = false;

        logger.info('Becoming master.');
        logger.info('Checking for backup UCS.');

        return provider.getStoredUcs()
            .then((response) => {
                if (response) {
                    hasUcs = true;
                    return loadUcs(provider, bigIp, response, options.cloud);
                }
                return q();
            })
            .then(() => {
                // If we loaded UCS, re-initialize encryption so our keys
                // match each other
                if (hasUcs) {
                    return initEncryption.call(this, provider, bigIp);
                }
                return q();
            })
            .then(() => {
                return bigIp.list('/tm/sys/global-settings');
            })
            .then((globalSettings) => {
                const hostname = globalSettings ? globalSettings.hostname : undefined;

                if (hostname) {
                    this.instance.hostname = hostname;
                } else {
                    logger.debug('hostname not found in this.instance or globalSettings');
                }

                return bigIp.list('/tm/sys/provision');
            })
            .then((response) => {
                const modulesProvisioned = {};

                if (response && response.length > 0) {
                    response.forEach((module) => {
                        modulesProvisioned[module.name] = !(module.level === 'none');
                    });
                }

                // Make sure device group exists
                logger.info('Creating device group.');

                const deviceGroupOptions = {
                    autoSync: options.autoSync,
                    saveOnAutoSync: options.saveOnAutoSync,
                    fullLoadOnSync: options.fullLoadOnSync,
                    asmSync: modulesProvisioned.asm || options.asmSync,
                    networkFailover: options.networkFailover
                };

                return bigIp.cluster.createDeviceGroup(
                    options.deviceGroup,
                    'sync-failover',
                    [this.instance.hostname],
                    deviceGroupOptions
                );
            })
            .then(() => {
                logger.info('Writing master file.');
                return writeMasterFile(hasUcs);
            });
    }

Handles becoming master.

@returns {Promise} promise which is resolved tieh true if successful


function getAutoscaleProcessCount() {
        const actions = 'cluster-action update|-c update|cluster-action join|-c join';
        const grepCommand = `grep autoscale.js | grep -E '${actions}' | grep -v 'grep autoscale.js'`;

        return util.getProcessCount(grepCommand)
            .then((response) => {
                return q(response);
            })
            .catch((err) => {
                logger.error('Could not determine if another autoscale script is running');
                return q.reject(err);
            });
    }

Get the count of running Autoscale process with actions of join or update.

Get the count of running Autoscale process with actions of join or update .


function initEncryption(provider, bigIp) {
        const PRIVATE_KEY_OUT_FILE = '/tmp/tempPrivateKey.pem';

        let passphrase;

        if (provider.hasFeature(CloudProvider.FEATURE_ENCRYPTION)) {
            logger.debug('Generating public/private keys for autoscaling.');
            return cryptoUtil.generateRandomBytes(PASSPHRASE_LENGTH, 'base64')
                .then((response) => {
                    passphrase = response;
                    return cryptoUtil.generateKeyPair(
                        PRIVATE_KEY_OUT_FILE,
                        { passphrase, keyLength: '3072' }
                    );
                })
                .then((publicKey) => {
                    return provider.putPublicKey(this.instanceId, publicKey);
                })
                .then(() => {
                    return bigIp.installPrivateKey(
                        PRIVATE_KEY_OUT_FILE,
                        AUTOSCALE_PRIVATE_KEY_FOLDER,
                        AUTOSCALE_PRIVATE_KEY,
                        { passphrase }
                    );
                })
                .then(() => {
                    return bigIp.save();
                })
                .catch((err) => {
                    logger.info('initEncryption error', err && err.message ? err.message : err);
                    return q.reject(err);
                });
        }
        return q();
    }

If the provider supports encryption, initializes and stores keys.

Called with this bound to the caller.

If the provider supports encryption initializes and stores keys .


function getMasterInstance(instances) {
        let instanceId;

        const instanceIds = Object.keys(instances);
        for (let i = 0; i < instanceIds.length; i++) {
            instanceId = instanceIds[i];
            if (instances[instanceId].isMaster) {
                return {
                    id: instanceId,
                    instance: instances[instanceId]
                };
            }
        }
        return null;
    }

function getMasterInstance ( instances ) { let instanceId ; const instanceIds = Object . keys ( instances ) ; for ( let i = 0 ; i < instanceIds . length ; i ++ ) { instanceId = instanceIds [ i ] ; if ( instances [ instanceId ] . isMaster ) { return { id : instanceId , instance : instances [ instanceId ] } ; } } return null ; }

Gets the instance marked as master

@param {Object} instances - Instances map

@returns {Object} master instance if one is found

{
id: instance_id,
instance: instance_data
}


function markVersions(instances) {
        let highestVersion = '0.0.0';
        let instance;

        Object.keys(instances).forEach((instanceId) => {
            instance = instances[instanceId];
            if (instance.version && util.versionCompare(instance.version, highestVersion) > 0) {
                highestVersion = instance.version;
            }
        });

        Object.keys(instances).forEach((instanceId) => {
            instance = instances[instanceId];
            if (!instance.version || util.versionCompare(instance.version, highestVersion) === 0) {
                instance.versionOk = true;
            } else {
                instance.versionOk = false;
            }
        });
    }

function markVersions ( instances ) { let highestVersion = '0.0.0' ; let instance ; Object . keys ( instances ) . forEach ( ( instanceId ) => { instance = instances [ instanceId ] ; if ( instance . version && util . versionCompare ( instance . version , highestVersion ) > 0 ) { highestVersion = instance . version ; } } ) ; Object . keys ( instances ) . forEach ( ( instanceId ) => { instance = instances [ instanceId ] ; if ( ! instance . version || util . versionCompare ( instance . version , highestVersion ) === 0 ) { instance . versionOk = true ; } else { instance . versionOk = false ; } } ) ; }

Checks that master instance has the most recent
version of all the BIG-IP instances

@param {Object} instances - Instances map

Checks that master instance has the most recent version of all the BIG - IP instances


function isMasterExternalValueOk(masterId, instances) {
        const instanceIds = Object.keys(instances);
        let instance;
        let hasExternal;

        for (let i = 0; i < instanceIds.length; i++) {
            instance = instances[instanceIds[i]];
            if (instance.external) {
                hasExternal = true;
                break;
            }
        }

        if (hasExternal) {
            return !!instances[masterId].external;
        }

        return true;
    }

function isMasterExternalValueOk ( masterId , instances ) { const instanceIds = Object . keys ( instances ) ; let instance ; let hasExternal ; for ( let i = 0 ; i < instanceIds . length ; i ++ ) { instance = instances [ instanceIds [ i ] ] ; if ( instance . external ) { hasExternal = true ; break ; } } if ( hasExternal ) { return ! ! instances [ masterId ] . external ; } return true ; }

Checks that if there are external instances, the master is
one of them

@param {String} masterId  - Instance ID of master
@param {Object} instances - Instances map

@returns {Boolean} True if there are no external instances or
if there are external instances and the master is
one of them

Checks that if there are external instances the master is one of them


function getDataFromPropPath(pathArray, obj) {
    if (pathArray.length === 0) {
        return undefined;
    }
    return pathArray.reduce((result, prop) => {
        if (typeof result !== 'object' || result === null) {
            return {};
        }
        if (prop === '') {
            return result;
        }
        return result[prop];
    }, obj);
}

function getDataFromPropPath ( pathArray , obj ) { if ( pathArray . length === 0 ) { return undefined ; } return pathArray . reduce ( ( result , prop ) => { if ( typeof result !== 'object' || result === null ) { return { } ; } if ( prop === '' ) { return result ; } return result [ prop ] ; } , obj ) ; }

Gets the value from an Object's property using a provided Object property path. An empty
property name in the path fetches all keys in the current Object.

@param {String[]} pathArray - Array of properties to traverse through.
@param {Object} obj - Object to traverse.

@returns {*} Data that was fetched from the property.

Gets the value from an Object s property using a provided Object property path . An empty property name in the path fetches all keys in the current Object .


function checkTask(taskPath, taskIdToCheck, options) {
    const func = function () {
        const deferred = q.defer();
        this.list(`${taskPath}/${taskIdToCheck}`, undefined, util.NO_RETRY)
            .then((response) => {
                const statusAttribute = (options && options.statusAttribute)
                    ? options.statusAttribute
                    : '_taskState';
                const taskState = response[statusAttribute];
                if (taskState === 'VALIDATING' || taskState === 'STARTED') {
                    // this is a normal state, just not done yet - keep waiting
                    deferred.reject();
                } else if (taskState === 'COMPLETED' || taskState === 'FINISHED') {
                    deferred.resolve({ success: true, response });
                } else if (taskState === 'FAILED') {
                    deferred.resolve({ success: false, response });
                } else {
                    deferred.reject(new Error(`checkTask: unexpected command status: ${taskState}`));
                }
            })
            .catch(() => {
                // if this throws, assume it is because restjavad has been restarted
                // and we are done for now
                deferred.resolve({ success: true });
            });

        return deferred.promise;
    };

    return util.tryUntil(this, util.DEFAULT_RETRY, func);
}

Checks status of iControl REST task

@param {String} taskPath                     - URL that created the task
@param {String} taskIdToCheck                - ID of task as returned by create
@param {Object} [options]                    - Options for parsing task response
@param {String} [options.statusAttribute]    - Name of the Task Status attribute in the result response.
Default: '_taskState'

@returns {Promise} A promise which is resolved with true if the task completes
successfully, resolved with false if task goes to error state
or rejected if some other error occurs.


function BigIq54LicenseProvider(bigIp, options) {
    const injectedLogger = options ? options.logger : undefined;
    let loggerOptions = options ? options.loggerOptions : undefined;

    this.constructorOptions = {};
    if (options) {
        Object.keys(options).forEach((option) => {
            this.constructorOptions[option] = options[option];
        });
    }

    if (injectedLogger) {
        this.logger = injectedLogger;
        util.setLogger(injectedLogger);
    } else {
        loggerOptions = loggerOptions || { logLevel: 'none' };
        loggerOptions.module = module;
        this.logger = Logger.getLogger(loggerOptions);
        util.setLoggerOptions(loggerOptions);
    }

    this.bigIp = bigIp;
}

function BigIq54LicenseProvider ( bigIp , options ) { const injectedLogger = options ? options . logger : undefined ; let loggerOptions = options ? options . loggerOptions : undefined ; this . constructorOptions = { } ; if ( options ) { Object . keys ( options ) . forEach ( ( option ) => { this . constructorOptions [ option ] = options [ option ] ; } ) ; } if ( injectedLogger ) { this . logger = injectedLogger ; util . setLogger ( injectedLogger ) ; } else { loggerOptions = loggerOptions || { logLevel : 'none' } ; loggerOptions . module = module ; this . logger = Logger . getLogger ( loggerOptions ) ; util . setLoggerOptions ( loggerOptions ) ; } this . bigIp = bigIp ; }

BigIq 5.3 license provider constructor

@class
@classdesc
Provides ability to get licenses from BIG-IQ 5.3 (and compatible versions).

@param {Object} bigIp                   - Base {@link BigIp} object.
@param {Object} [options]               - Optional parameters.
@param {Object} [options.logger]        - Logger to use. Or, pass loggerOptions to get your own logger.
@param {Object} [options.loggerOptions] - Options for the logger.
See {@link module:logger.getLogger} for details.

BigIq 5 . 3 license provider constructor


Encrypts data with a public key

@param {String} publicKeyDataOrFile - Either the public key, or the full path to
a file containing the public key
@param {String} data                - String version of the data to encrypt

@returns {Promise} A promise which is resolved with a base64 encoded version
of the encrypted data, or rejected if an error occurs.


function getLabel(logLevel, moduleLogging, verboseLabel) {
    let parts;
    let label = '';

    if (moduleLogging) {
        if (logLevel === 'debug' || logLevel === 'silly' || verboseLabel) {
            parts = moduleLogging.filename.split('/');
            label = `${parts[parts.length - 2]}/${parts.pop()}`;
        }
    }

    return label;
}

function getLabel ( logLevel , moduleLogging , verboseLabel ) { let parts ; let label = '' ; if ( moduleLogging ) { if ( logLevel === 'debug' || logLevel === 'silly' || verboseLabel ) { parts = moduleLogging . filename . split ( '/' ) ; label = ` ${ parts [ parts . length - 2 ] } ${ parts . pop ( ) } ` ; } } return label ; }

Return the last folder name in the path and the calling module's filename.

Return the last folder name in the path and the calling module s filename .


function getLicenseProvider(poolName, options) {
    const methodOptions = {};
    Object.assign(methodOptions, options);
    const factoryOptions = {};
    Object.assign(factoryOptions, this.constructorOptions);

    let licenseProvider;

    if (methodOptions.autoApiType) {
        return getApiType.call(this, poolName, methodOptions)
            .then((apiType) => {
                // Even though the main API by type is the same across BIG-IQ versions,
                // there are some subtle differences the implementations need to know
                // about
                factoryOptions.version = this.version;
                try {
                    licenseProvider = bigIqLicenseProviderFactory.getLicenseProviderByType(
                        apiType,
                        this.bigIp,
                        factoryOptions
                    );
                    return q(licenseProvider);
                } catch (err) {
                    this.logger.info(
                        'Error getting license provider by type', err && err.message ? err.message : err
                    );
                    return q.reject(err);
                }
            })
            .catch((err) => {
                this.logger.info('Error getting api type', err && err.message ? err.message : err);
                return q.reject(err);
            });
    }

    try {
        licenseProvider = bigIqLicenseProviderFactory.getLicenseProviderByVersion(
            this.version,
            this.bigIp,
            factoryOptions
        );

        return q(licenseProvider);
    } catch (err) {
        this.logger.info(
            'Error getting license provider by type', err && err.message ? err.message : err
        );
        return q.reject(err);
    }
}

Gets a license provider based on api type or version
@param {String} poolName                 - The name of the license pool
@param {Object} options                  - Options
@param {Boolean} options.autoApiType     - Automatically determine API type rather
than basing on BIG-IQ version.
@param {Boolean} [options.noUnreachable] - Do not use the unreachable API even on BIG-IQs that support it.


function forceResetUserPassword(user) {
    const deferred = q.defer();

    cryptoUtil.generateRandomBytes(24, 'hex')
        .then((randomBytes) => {
            util.runShellCommand(`echo -e "${randomBytes}\n${randomBytes}" | passwd ${user}`);
            deferred.resolve(randomBytes);
        })
        .catch((err) => {
            deferred.reject(err);
        });
    return deferred.promise;
}

function forceResetUserPassword ( user ) { const deferred = q . defer ( ) ; cryptoUtil . generateRandomBytes ( 24 , 'hex' ) . then ( ( randomBytes ) => { util . runShellCommand ( ` ${ randomBytes } \n ${ randomBytes } ${ user } ` ) ; deferred . resolve ( randomBytes ) ; } ) . catch ( ( err ) => { deferred . reject ( err ) ; } ) ; return deferred . promise ; }

Force resets a user's password, even if the oldPassword is not known.

@param {String} user - user to reset

@returns {Promise} A promise which is resolved when the operation is complete
or rejected if an error occurs.

Force resets a user s password even if the oldPassword is not known .


function jscoverage_endLengthyOperation() {
  var progressBar = document.getElementById('progressBar');
  ProgressBar.setPercentage(progressBar, 100);
  setTimeout(function() {
    jscoverage_inLengthyOperation = false;
    progressBar.style.visibility = 'hidden';
    var progressLabel = document.getElementById('progressLabel');
    progressLabel.style.visibility = 'hidden';
    progressLabel.innerHTML = '';

    var tabs = document.getElementById('tabs').getElementsByTagName('div');
    var i;
    for (i = 0; i < tabs.length; i++) {
      tabs.item(i).style.cursor = '';
    }
  }, 50);
}

function jscoverage_endLengthyOperation ( ) { var progressBar = document . getElementById ( 'progressBar' ) ; ProgressBar . setPercentage ( progressBar , 100 ) ; setTimeout ( function ( ) { jscoverage_inLengthyOperation = false ; progressBar . style . visibility = 'hidden' ; var progressLabel = document . getElementById ( 'progressLabel' ) ; progressLabel . style . visibility = 'hidden' ; progressLabel . innerHTML = '' ; var tabs = document . getElementById ( 'tabs' ) . getElementsByTagName ( 'div' ) ; var i ; for ( i = 0 ; i < tabs . length ; i ++ ) { tabs . item ( i ) . style . cursor = '' ; } } , 50 ) ; }

Removes the progress bar and busy cursor.

Removes the progress bar and busy cursor .


function jscoverage_initTabContents(queryString) {
  var showMissingColumn = false;
  var url = null;
  var windowURL = null;
  var parameters, parameter, i, index, name, value;
  if (queryString.length > 0) {
    // chop off the question mark
    queryString = queryString.substring(1);
    parameters = queryString.split(/&|;/);
    for (i = 0; i < parameters.length; i++) {
      parameter = parameters[i];
      index = parameter.indexOf('=');
      if (index === -1) {
        // still works with old syntax
        url = decodeURIComponent(parameter);
      }
      else {
        name = parameter.substr(0, index);
        value = decodeURIComponent(parameter.substr(index + 1));
        if (name === 'missing' || name === 'm') {
          showMissingColumn = jscoverage_getBooleanValue(value);
        }
        else if (name === 'url' || name === 'u' || name === 'frame' || name === 'f') {
          url = value;
        }
        else if (name === 'window' || name === 'w') {
          windowURL = value;
        }
      }
    }
  }

  var checkbox = document.getElementById('checkbox');
  checkbox.checked = showMissingColumn;
  if (showMissingColumn) {
    jscoverage_appendMissingColumn();
  }

  var isValidURL = function (url) {
    var result = jscoverage_isValidURL(url);
    if (! result) {
      alert('Invalid URL: ' + url);
    }
    return result;
  };

  if (url !== null && isValidURL(url)) {
    // this will automatically propagate to the input field
    frames[0].location = url;
  }
  else if (windowURL !== null && isValidURL(windowURL)) {
    window.open(windowURL);
  }

  // if the browser tab is absent, we have to initialize the summary tab
  if (! document.getElementById('browserTab')) {
    jscoverage_recalculateSummaryTab();
  }
}

Initializes the contents of the tabs.  This sets the initial values of the
input field and iframe in the "Browser" tab and the checkbox in the "Summary"
tab.
@param  queryString  this should always be location.search

Initializes the contents of the tabs . This sets the initial values of the input field and iframe in the Browser tab and the checkbox in the Summary tab .


function jscoverage_recalculateSourceTab() {
  if (! jscoverage_currentFile) {
    jscoverage_endLengthyOperation();
    return;
  }
  var progressLabel = document.getElementById('progressLabel');
  progressLabel.innerHTML = 'Calculating coverage ...';
  var progressBar = document.getElementById('progressBar');
  ProgressBar.setPercentage(progressBar, 20);
  setTimeout(jscoverage_makeTable, 0);
}

function
jscoverage_recalculateSourceTab
(
)
{
if
(
!
jscoverage_currentFile
)
{
jscoverage_endLengthyOperation
(
)
;
return
;
}
var
progressLabel
=
document
.
getElementById
(
'progressLabel'
)
;
progressLabel
.
innerHTML
=
'Calculating coverage ...'
;
var
progressBar
=
document
.
getElementById
(
'progressBar'
)
;
ProgressBar
.
setPercentage
(
progressBar
,
20
)
;
setTimeout
(
jscoverage_makeTable
,
0
)
;
}

Calculates coverage statistics for the current source file.

Calculates coverage statistics for the current source file .


function jscoverage_selectTab(tab) {
  if (typeof tab !== 'number') {
    tab = jscoverage_tabIndexOf(tab);
  }
  var tabs = document.getElementById('tabs');
  var tabPages = document.getElementById('tabPages');
  var nodeList;
  var tabNum;
  var i;
  var node;

  nodeList = tabs.childNodes;
  tabNum = 0;
  for (i = 0; i < nodeList.length; i++) {
    node = nodeList.item(i);
    if (node.nodeType !== 1) {
      continue;
    }

    if (node.className !== 'disabled') {
      if (tabNum === tab) {
        node.className = 'selected';
      }
      else {
        node.className = '';
      }
    }
    tabNum++;
  }

  nodeList = tabPages.childNodes;
  tabNum = 0;
  for (i = 0; i < nodeList.length; i++) {
    node = nodeList.item(i);
    if (node.nodeType !== 1) {
      continue;
    }

    if (tabNum === tab) {
      node.className = 'selected TabPage';
    }
    else {
      node.className = 'TabPage';
    }
    tabNum++;
  }
}

function
jscoverage_selectTab
(
tab
)
{
if
(
typeof
tab
!==
'number'
)
{
tab
=
jscoverage_tabIndexOf
(
tab
)
;
}
var
tabs
=
document
.
getElementById
(
'tabs'
)
;
var
tabPages
=
document
.
getElementById
(
'tabPages'
)
;
var
nodeList
;
var
tabNum
;
var
i
;
var
node
;
nodeList
=
tabs
.
childNodes
;
tabNum
=
0
;
for
(
i
=
0
;
i
<
nodeList
.
length
;
i
++
)
{
node
=
nodeList
.
item
(
i
)
;
if
(
node
.
nodeType
!==
1
)
{
continue
;
}
if
(
node
.
className
!==
'disabled'
)
{
if
(
tabNum
===
tab
)
{
node
.
className
=
'selected'
;
}
else
{
node
.
className
=
''
;
}
}
tabNum
++
;
}
nodeList
=
tabPages
.
childNodes
;
tabNum
=
0
;
for
(
i
=
0
;
i
<
nodeList
.
length
;
i
++
)
{
node
=
nodeList
.
item
(
i
)
;
if
(
node
.
nodeType
!==
1
)
{
continue
;
}
if
(
tabNum
===
tab
)
{
node
.
className
=
'selected TabPage'
;
}
else
{
node
.
className
=
'TabPage'
;
}
tabNum
++
;
}
}

Selects a tab.
@param  tab  the integer index of the tab (0, 1, 2, or 3)
OR
the ID of the tab element
OR
the tab element itself


function compareAscending(a, b) {
    var ac = a.criteria,
        bc = b.criteria;

    // ensure a stable sort in V8 and other engines
    // http://code.google.com/p/v8/issues/detail?id=90
    if (ac !== bc) {
      if (ac > bc || typeof ac == 'undefined') {
        return 1;
      }
      if (ac < bc || typeof bc == 'undefined') {
        return -1;
      }
    }
    // The JS engine embedded in Adobe applications like InDesign has a buggy
    // `Array#sort` implementation that causes it, under certain circumstances,
    // to return the same value for `a` and `b`.
    // See https://github.com/jashkenas/underscore/pull/1247
    return a.index - b.index;
  }

Used by `sortBy` to compare transformed `collection` elements, stable sorting
them in ascending order.

@private
@param {Object} a The object to compare to `b`.
@param {Object} b The object to compare to `a`.
@returns {number} Returns the sort order indicator of `1` or `-1`.

Used by sortBy to compare transformed collection elements stable sorting them in ascending order .


function baseFlatten(array, isShallow, isArgArrays, fromIndex) {
      var index = (fromIndex || 0) - 1,
          length = array ? array.length : 0,
          result = [];

      while (++index < length) {
        var value = array[index];

        if (value && typeof value == 'object' && typeof value.length == 'number'
            && (isArray(value) || isArguments(value))) {
          // recursively flatten arrays (susceptible to call stack limits)
          if (!isShallow) {
            value = baseFlatten(value, isShallow, isArgArrays);
          }
          var valIndex = -1,
              valLength = value.length,
              resIndex = result.length;

          result.length += valLength;
          while (++valIndex < valLength) {
            result[resIndex++] = value[valIndex];
          }
        } else if (!isArgArrays) {
          result.push(value);
        }
      }
      return result;
    }

The base implementation of `_.flatten` without support for callback
shorthands or `thisArg` binding.

@private
@param {Array} array The array to flatten.
@param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
@param {boolean} [isArgArrays=false] A flag to restrict flattening to arrays and `arguments` objects.
@param {number} [fromIndex=0] The index to start from.
@returns {Array} Returns a new flattened array.

The base implementation of _ . flatten without support for callback shorthands or thisArg binding .


function pluck(collection, property) {
      var index = -1,
          length = collection ? collection.length : 0;

      if (typeof length == 'number') {
        var result = Array(length);
        while (++index < length) {
          result[index] = collection[index][property];
        }
      }
      return result || map(collection, property);
    }

function pluck ( collection , property ) { var index = - 1 , length = collection ? collection . length : 0 ; if ( typeof length == 'number' ) { var result = Array ( length ) ; while ( ++ index < length ) { result [ index ] = collection [ index ] [ property ] ; } } return result || map ( collection , property ) ; }

Retrieves the value of a specified property from all elements in the `collection`.

@static
@memberOf _
@type Function
@category Collections
@param {Array|Object|string} collection The collection to iterate over.
@param {string} property The property to pluck.
@returns {Array} Returns a new array of property values.
@example

var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];

_.pluck(stooges, 'name');
// => ['moe', 'larry']

Retrieves the value of a specified property from all elements in the collection .


function reduceRight(collection, callback, accumulator, thisArg) {
      var noaccum = arguments.length < 3;
      callback = baseCreateCallback(callback, thisArg, 4);
      forEachRight(collection, function(value, index, collection) {
        accumulator = noaccum
          ? (noaccum = false, value)
          : callback(accumulator, value, index, collection);
      });
      return accumulator;
    }

function reduceRight ( collection , callback , accumulator , thisArg ) { var noaccum = arguments . length < 3 ; callback = baseCreateCallback ( callback , thisArg , 4 ) ; forEachRight ( collection , function ( value , index , collection ) { accumulator = noaccum ? ( noaccum = false , value ) : callback ( accumulator , value , index , collection ) ; } ) ; return accumulator ; }

This method is like `_.reduce` except that it iterates over elements
of a `collection` from right to left.

@static
@memberOf _
@alias foldr
@category Collections
@param {Array|Object|string} collection The collection to iterate over.
@param {Function} [callback=identity] The function called per iteration.
@param {*} [accumulator] Initial value of the accumulator.
@param {*} [thisArg] The `this` binding of `callback`.
@returns {*} Returns the accumulated value.
@example

var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
// => [4, 5, 2, 3, 0, 1]

This method is like _ . reduce except that it iterates over elements of a collection from right to left .


function sample(collection, n, guard) {
      var length = collection ? collection.length : 0;
      if (typeof length != 'number') {
        collection = values(collection);
      }
      if (n == null || guard) {
        return collection ? collection[random(length - 1)] : undefined;
      }
      var result = shuffle(collection);
      result.length = nativeMin(nativeMax(0, n), result.length);
      return result;
    }

function sample ( collection , n , guard ) { var length = collection ? collection . length : 0 ; if ( typeof length != 'number' ) { collection = values ( collection ) ; } if ( n == null || guard ) { return collection ? collection [ random ( length - 1 ) ] : undefined ; } var result = shuffle ( collection ) ; result . length = nativeMin ( nativeMax ( 0 , n ) , result . length ) ; return result ; }

Retrieves a random element or `n` random elements from a collection.

@static
@memberOf _
@category Collections
@param {Array|Object|string} collection The collection to sample.
@param {number} [n] The number of elements to sample.
@param- {Object} [guard] Allows working with functions, like `_.map`,
without using their `key` and `object` arguments as sources.
@returns {Array} Returns the random sample(s) of `collection`.
@example

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

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

Retrieves a random element or n random elements from a collection .


function bind(func, thisArg) {
      return arguments.length > 2
        ? createBound(func, 17, nativeSlice.call(arguments, 2), null, thisArg)
        : createBound(func, 1, null, null, thisArg);
    }

function bind ( func , thisArg ) { return arguments . length > 2 ? createBound ( func , 17 , nativeSlice . call ( arguments , 2 ) , null , thisArg ) : createBound ( func , 1 , null , null , thisArg ) ; }

Creates a function that, when called, invokes `func` with the `this`
binding of `thisArg` and prepends any additional `bind` arguments to those
provided to the bound function.

@static
@memberOf _
@category Functions
@param {Function} func The function to bind.
@param {*} [thisArg] The `this` binding of `func`.
@param {...*} [arg] Arguments to be partially applied.
@returns {Function} Returns the new bound function.
@example

var func = function(greeting) {
return greeting + ' ' + this.name;
};

func = _.bind(func, { 'name': 'moe' }, 'hi');
func();
// => 'hi moe'

Creates a function that when called invokes func with the this binding of thisArg and prepends any additional bind arguments to those provided to the bound function .


function bindAll(object) {
      var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
          index = -1,
          length = funcs.length;

      while (++index < length) {
        var key = funcs[index];
        object[key] = createBound(object[key], 1, null, null, object);
      }
      return object;
    }

function bindAll ( object ) { var funcs = arguments . length > 1 ? baseFlatten ( arguments , true , false , 1 ) : functions ( object ) , index = - 1 , length = funcs . length ; while ( ++ index < length ) { var key = funcs [ index ] ; object [ key ] = createBound ( object [ key ] , 1 , null , null , object ) ; } return object ; }

Binds methods of an object to the object itself, overwriting the existing
method. Method names may be specified as individual arguments or as arrays
of method names. If no method names are provided all the function properties
of `object` will be bound.

@static
@memberOf _
@category Functions
@param {Object} object The object to bind and assign the bound methods to.
@param {...string} [methodName] The object method names to
bind, specified as individual method names or arrays of method names.
@returns {Object} Returns `object`.
@example

var view = {
'label': 'docs',
'onClick': function() { console.log('clicked ' + this.label); }
};

_.bindAll(view);
jQuery('#docs').on('click', view.onClick);
// => logs 'clicked docs', when the button is clicked

Binds methods of an object to the object itself overwriting the existing method . Method names may be specified as individual arguments or as arrays of method names . If no method names are provided all the function properties of object will be bound .


function curry(func, arity) {
      arity = typeof arity == 'number' ? arity : (+arity || func.length);
      return createBound(func, 4, null, null, null, arity);
    }

function curry ( func , arity ) { arity = typeof arity == 'number' ? arity : ( + arity || func . length ) ; return createBound ( func , 4 , null , null , null , arity ) ; }

Creates a function which accepts one or more arguments of `func` that when
invoked either executes `func` returning its result, if all `func` arguments
have been provided, or returns a function that accepts one or more of the
remaining `func` arguments, and so on. The arity of `func` can be specified
if `func.length` is not sufficient.

@static
@memberOf _
@category Functions
@param {Function} func The function to curry.
@param {number} [arity=func.length] The arity of `func`.
@returns {Function} Returns the new curried function.
@example

var curried = _.curry(function(a, b, c) {
console.log(a + b + c);
});

curried(1)(2)(3);
// => 6

curried(1, 2)(3);
// => 6

curried(1, 2, 3);
// => 6

Creates a function which accepts one or more arguments of func that when invoked either executes func returning its result if all func arguments have been provided or returns a function that accepts one or more of the remaining func arguments and so on . The arity of func can be specified if func . length is not sufficient .


function wrap(value, wrapper) {
      if (!isFunction(wrapper)) {
        throw new TypeError;
      }
      return function() {
        var args = [value];
        push.apply(args, arguments);
        return wrapper.apply(this, args);
      };
    }

function wrap ( value , wrapper ) { if ( ! isFunction ( wrapper ) ) { throw new TypeError ; } return function ( ) { var args = [ value ] ; push . apply ( args , arguments ) ; return wrapper . apply ( this , args ) ; } ; }

Creates a function that provides `value` to the wrapper function as its
first argument. Additional arguments provided to the function are appended
to those provided to the wrapper function. The wrapper is executed with
the `this` binding of the created function.

@static
@memberOf _
@category Functions
@param {*} value The value to wrap.
@param {Function} wrapper The wrapper function.
@returns {Function} Returns the new function.
@example

var hello = function(name) { return 'hello ' + name; };
hello = _.wrap(hello, function(func) {
return 'before, ' + func('moe') + ', after';
});
hello();
// => 'before, hello moe, after'

Creates a function that provides value to the wrapper function as its first argument . Additional arguments provided to the function are appended to those provided to the wrapper function . The wrapper is executed with the this binding of the created function .


function mixin(object, source) {
      var ctor = object,
          isFunc = !source || isFunction(ctor);

      if (!source) {
        ctor = lodashWrapper;
        source = object;
        object = lodash;
      }
      forEach(functions(source), function(methodName) {
        var func = object[methodName] = source[methodName];
        if (isFunc) {
          ctor.prototype[methodName] = function() {
            var value = this.__wrapped__,
                args = [value];

            push.apply(args, arguments);
            var result = func.apply(object, args);
            if (value && typeof value == 'object' && value === result) {
              return this;
            }
            result = new ctor(result);
            result.__chain__ = this.__chain__;
            return result;
          };
        }
      });
    }

function mixin ( object , source ) { var ctor = object , isFunc = ! source || isFunction ( ctor ) ; if ( ! source ) { ctor = lodashWrapper ; source = object ; object = lodash ; } forEach ( functions ( source ) , function ( methodName ) { var func = object [ methodName ] = source [ methodName ] ; if ( isFunc ) { ctor . prototype [ methodName ] = function ( ) { var value = this . __wrapped__ , args = [ value ] ; push . apply ( args , arguments ) ; var result = func . apply ( object , args ) ; if ( value && typeof value == 'object' && value === result ) { return this ; } result = new ctor ( result ) ; result . __chain__ = this . __chain__ ; return result ; } ; } } ) ; }

Adds function properties of a source object to the `lodash` function and
chainable wrapper.

@static
@memberOf _
@category Utilities
@param {Object} object The object of function properties to add to `lodash`.
@param {Object} object The object of function properties to add to `lodash`.
@example

_.mixin({
'capitalize': function(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
});

_.capitalize('moe');
// => 'Moe'

_('moe').capitalize();
// => 'Moe'

Adds function properties of a source object to the lodash function and chainable wrapper .


function() {

            var target = arguments[0];

            for (var i = 1, l = arguments.length; i < l; i++) {

                var extension = arguments[i];

                // Only functions and objects can be mixined.

                if ((Object(extension) !== extension) &&
                    !_.isFunction(extension) &&
                    (extension === null || extension === undefined)) {

                    continue;
                }

                _.each(extension, function(copy, key) {

                    if (this.mixin.deep && (Object(copy) === copy)) {

                        if (!target[key]) {

                            target[key] = _.isArray(copy) ? [] : {};
                        }

                        this.mixin(target[key], copy);
                        return;
                    }

                    if (target[key] !== copy) {

                        if (!this.mixin.supplement || !target.hasOwnProperty(key)) {

	                    target[key] = copy;
                        }

                    }

                }, this);
            }

            return target;
        }

Copy all the properties to the first argument from the following arguments. All the properties will be overwritten by the properties from the following arguments. Inherited properties are ignored.

Copy all the properties to the first argument from the following arguments . All the properties will be overwritten by the properties from the following arguments . Inherited properties are ignored .


function(args) {

                return _.template('<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>', {
                    dx: args.dx || 0,
                    dy: args.dy || 0,
                    color: args.color || 'black',
                    blur: _.isFinite(args.blur) ? args.blur : 4
                });
            }

`dx` ... horizontal shift `dy` ... vertical shift `blur` ... blur `color` ... color

dx ... horizontal shift dy ... vertical shift blur ... blur color ... color


`amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged.

amount ... the proportion of the conversion . A value of 1 is completely grayscale . A value of 0 leaves the input unchanged .


function(args) {

                var amount = _.isFinite(args.amount) ? args.amount : 1;

                return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', {
                    amount: 1 - amount
                });
            }

`amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged.

amount ... the proportion of the conversion . A value of 0 is completely un - saturated . A value of 1 leaves the input unchanged .


function(sx, sy) {
            sy = (typeof sy === 'undefined') ? sx : sy;

            var transformAttr = this.attr('transform') || '',
                transform = parseTransformString(transformAttr);

            // Is it a getter?
            if (typeof sx === 'undefined') {
                return transform.scale;
            }

            transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim();

            this.attr('transform', transformAttr + ' scale(' + sx + ',' + sy + ')');
            return this;
        }

function
(
sx
,
sy
)
{
sy
=
(
typeof
sy
===
'undefined'
)
sx
:
sy
;
var
transformAttr
=
this
.
attr
(
'transform'
)
||
''
,
transform
=
parseTransformString
(
transformAttr
)
;
// Is it a getter?
if
(
typeof
sx
===
'undefined'
)
{
return
transform
.
scale
;
}
transformAttr
=
transformAttr
.
replace
(
/
scale\([^\)]*\)
/
g
,
''
)
.
trim
(
)
;
this
.
attr
(
'transform'
,
transformAttr
+
' scale('
+
sx
+
','
+
sy
+
')'
)
;
return
this
;
}

Note that `scale` as the only transformation does not combine with previous values.

Note that scale as the only transformation does not combine with previous values .


function(withoutTransformations, target) {

            // If the element is not in the live DOM, it does not have a bounding box defined and
            // so fall back to 'zero' dimension element.
            if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 };

            var box;
            try {

                box = this.node.getBBox();

		// Opera returns infinite values in some cases.
		// Note that Infinity | 0 produces 0 as opposed to Infinity || 0.
		// We also have to create new object as the standard says that you can't
		// modify the attributes of a bbox.
		box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0};

            } catch (e) {

                // Fallback for IE.
                box = {
                    x: this.node.clientLeft,
                    y: this.node.clientTop,
                    width: this.node.clientWidth,
                    height: this.node.clientHeight
                };
            }

            if (withoutTransformations) {

                return box;
            }

            var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement);
            var corners = [];
            var point = this.node.ownerSVGElement.createSVGPoint();

            point.x = box.x;
            point.y = box.y;
            corners.push(point.matrixTransform(matrix));

            point.x = box.x + box.width;
            point.y = box.y;
            corners.push(point.matrixTransform(matrix));

            point.x = box.x + box.width;
            point.y = box.y + box.height;
            corners.push(point.matrixTransform(matrix));

            point.x = box.x;
            point.y = box.y + box.height;
            corners.push(point.matrixTransform(matrix));

            var minX = corners[0].x;
            var maxX = minX;
            var minY = corners[0].y;
            var maxY = minY;

            for (var i = 1, len = corners.length; i < len; i++) {

                var x = corners[i].x;
                var y = corners[i].y;

                if (x < minX) {
                    minX = x;
                } else if (x > maxX) {
                    maxX = x;
                }

                if (y < minY) {
                    minY = y;
                } else if (y > maxY) {
                    maxY = y;
                }
            }

            return {
                x: minX,
                y: minY,
                width: maxX - minX,
                height: maxY - minY
            };
        }

Get SVGRect that contains coordinates and dimension of the real bounding box, i.e. after transformations are applied. If `target` is specified, bounding box will be computed relatively to `target` element.

Get SVGRect that contains coordinates and dimension of the real bounding box i . e . after transformations are applied . If target is specified bounding box will be computed relatively to target element .


function(x, y) {

            var svg = this.svg().node;

            var p = svg.createSVGPoint();
            p.x = x;
            p.y = y;

	    try {

		var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse());
		var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse();

	    } catch(e) {
		// IE9 throws an exception in odd cases. (`Unexpected call to method or property access`)
		// We have to make do with the original coordianates.
		return p;
	    }

            return globalPoint.matrixTransform(globalToLocalMatrix);
        }

Convert global point into the coordinate space of this element.

Convert global point into the coordinate space of this element .


function(o) {
            o = (o && point(o)) || point(0,0);
            var x = this.x;
            var y = this.y;
            this.x = sqrt((x-o.x)*(x-o.x) + (y-o.y)*(y-o.y));   // r
            this.y = toRad(o.theta(point(x,y)));
            return this;
        }

function
(
o
)
{
o
=
(
o
&&
point
(
o
)
)
||
point
(
0
,
0
)
;
var
x
=
this
.
x
;
var
y
=
this
.
y
;
this
.
x
=
sqrt
(
(
x
o
.
x
)
*
(
x
o
.
x
)
+
(
y
o
.
y
)
*
(
y
o
.
y
)
)
;
// r
this
.
y
=
toRad
(
o
.
theta
(
point
(
x
,
y
)
)
)
;
return
this
;
}

Converts rectangular to polar coordinates. An origin can be specified, otherwise it's 0@0.

Converts rectangular to polar coordinates . An origin can be specified otherwise it s 0


function(o, angle) {
            angle = (angle + 360) % 360;
            this.toPolar(o);
            this.y += toRad(angle);
            var p = point.fromPolar(this.x, this.y, o);
            this.x = p.x;
            this.y = p.y;
            return this;
        }

function ( o , angle ) { angle = ( angle + 360 ) % 360 ; this . toPolar ( o ) ; this . y += toRad ( angle ) ; var p = point . fromPolar ( this . x , this . y , o ) ; this . x = p . x ; this . y = p . y ; return this ; }


function(ref, distance) {
            var theta = toRad(point(ref).theta(this));
            return this.offset(cos(theta) * distance, -sin(theta) * distance);
        }

function ( ref , distance ) { var theta = toRad ( point ( ref ) . theta ( this ) ) ; return this . offset ( cos ( theta ) * distance , - sin ( theta ) * distance ) ; }

Move point on line starting from ref ending at me by distance distance.

Move point on line starting from ref ending at me by distance distance .


function(p, angle) {
            p = point(p);
	    var center = point(this.x + this.width/2, this.y + this.height/2);
            var result;
            if (angle) p.rotate(center, angle);

	    // (clockwise, starting from the top side)
	    var sides = [
	        line(this.origin(), this.topRight()),
	        line(this.topRight(), this.corner()),
	        line(this.corner(), this.bottomLeft()),
	        line(this.bottomLeft(), this.origin())
	    ];
	    var connector = line(center, p);

	    for (var i = sides.length - 1; i >= 0; --i){
	        var intersection = sides[i].intersection(connector);
	        if (intersection !== null){
		    result = intersection;
                    break;
	        }
	    }
            if (result && angle) result.rotate(center, -angle);
            return result;
        }

Find point on my boundary where line starting from my center ending in point p intersects me. @param {number} angle If angle is specified, intersection with rotated rectangle is computed.

Find point on my boundary where line starting from my center ending in point p intersects me .


function(r) {
	    this.x += r.x;
	    this.y += r.y;
	    this.width += r.width;
	    this.height += r.height;
	    return this;
        }

function ( r ) { this . x += r . x ; this . y += r . y ; this . width += r . width ; this . height += r . height ; return this ; }

Move and expand me. @param r {rectangle} representing deltas


function(p, angle) {
	    p = point(p);
            if (angle) p.rotate(point(this.x, this.y), angle);
            var dx = p.x - this.x;
	    var dy = p.y - this.y;
            var result;
	    if (dx === 0) {
	        result = this.bbox().pointNearestToPoint(p);
                if (angle) return result.rotate(point(this.x, this.y), -angle);
                return result;
	    }
	    var m = dy / dx;
	    var mSquared = m * m;
	    var aSquared = this.a * this.a;
	    var bSquared = this.b * this.b;
	    var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared)));

            x = dx < 0 ? -x : x;
	    var y = m * x;
	    result = point(this.x + x, this.y + y);
            if (angle) return result.rotate(point(this.x, this.y), -angle);
            return result;
        }

function ( p , angle ) { p = point ( p ) ; if ( angle ) p . rotate ( point ( this . x , this . y ) , angle ) ; var dx = p . x - this . x ; var dy = p . y - this . y ; var result ; if ( dx === 0 ) { result = this . bbox ( ) . pointNearestToPoint ( p ) ; if ( angle ) return result . rotate ( point ( this . x , this . y ) , - angle ) ; return result ; } var m = dy / dx ; var mSquared = m * m ; var aSquared = this . a * this . a ; var bSquared = this . b * this . b ; var x = sqrt ( 1 / ( ( 1 / aSquared ) + ( mSquared / bSquared ) ) ) ; x = dx < 0 ? - x : x ; var y = m * x ; result = point ( this . x + x , this . y + y ) ; if ( angle ) return result . rotate ( point ( this . x , this . y ) , - angle ) ; return result ; }

Find point on me where line from my center to point p intersects my boundary. @param {number} angle If angle is specified, intersection with rotated ellipse is computed.

Find point on me where line from my center to point p intersects my boundary .


function(knots) {
            var firstControlPoints = [];
            var secondControlPoints = [];
            var n = knots.length - 1;
            var i;

            // Special case: Bezier curve should be a straight line.
            if (n == 1) {
	        // 3P1 = 2P0 + P3
	        firstControlPoints[0] = point((2 * knots[0].x + knots[1].x) / 3,
	                                      (2 * knots[0].y + knots[1].y) / 3);
	        // P2 = 2P1 – P0
	        secondControlPoints[0] = point(2 * firstControlPoints[0].x - knots[0].x,
	                                       2 * firstControlPoints[0].y - knots[0].y);
	        return [firstControlPoints, secondControlPoints];
            }

                // Calculate first Bezier control points.
            // Right hand side vector.
            var rhs = [];

            // Set right hand side X values.
            for (i = 1; i < n - 1; i++) {
                rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
            }
            rhs[0] = knots[0].x + 2 * knots[1].x;
            rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;
            // Get first control points X-values.
            var x = this.getFirstControlPoints(rhs);

            // Set right hand side Y values.
            for (i = 1; i < n - 1; ++i) {
	        rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
            }
            rhs[0] = knots[0].y + 2 * knots[1].y;
            rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;
            // Get first control points Y-values.
            var y = this.getFirstControlPoints(rhs);

            // Fill output arrays.
            for (i = 0; i < n; i++) {
	        // First control point.
	        firstControlPoints.push(point(x[i], y[i]));
	        // Second control point.
	        if (i < n - 1) {
	            secondControlPoints.push(point(2 * knots [i + 1].x - x[i + 1],
                                                   2 * knots[i + 1].y - y[i + 1]));
	        } else {
	            secondControlPoints.push(point((knots[n].x + x[n - 1]) / 2,
					           (knots[n].y + y[n - 1]) / 2));
	        }
            }
            return [firstControlPoints, secondControlPoints];
        }

Get open-ended Bezier Spline Control Points. @param knots Input Knot Bezier spline points (At least two points!). @param firstControlPoints Output First Control points. Array of knots.length - 1 length. @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.

Get open - ended Bezier Spline Control Points .


function(model, opt) {

        opt = opt || {};

        if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) {
            opt.inbound = opt.outbound = true;
        }

        var links = [];

        this.each(function(cell) {

            var source = cell.get('source');
            var target = cell.get('target');

            if (source && source.id === model.id && opt.outbound) {

                links.push(cell);
            }

            if (target && target.id === model.id && opt.inbound) {

                links.push(cell);
            }
        });

        return links;
    }

function ( model , opt ) { opt = opt || { } ; if ( _ . isUndefined ( opt . inbound ) && _ . isUndefined ( opt . outbound ) ) { opt . inbound = opt . outbound = true ; } var links = [ ] ; this . each ( function ( cell ) { var source = cell . get ( 'source' ) ; var target = cell . get ( 'target' ) ; if ( source && source . id === model . id && opt . outbound ) { links . push ( cell ) ; } if ( target && target . id === model . id && opt . inbound ) { links . push ( cell ) ; } } ) ; return links ; }

Get all inbound and outbound links connected to the cell `model`.

Get all inbound and outbound links connected to the cell model .


function(model) {

        _.each(this.getConnectedLinks(model), function(link) {

            link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0));
        });
    }

function ( model ) { _ . each ( this . getConnectedLinks ( model ) , function ( link ) { link . set ( link . get ( 'source' ) . id === model . id ? 'source' : 'target' , g . point ( 0 , 0 ) ) ; } ) ; }

Disconnect links connected to the cell `model`.

Disconnect links connected to the cell model .


function(attrs, value, opt) {

        var currentAttrs = this.get('attrs');
        var delim = '/';

        if (_.isString(attrs)) {
            // Get/set an attribute by a special path syntax that delimits
            // nested objects by the colon character.

            if (value) {

                var attr = {};
                joint.util.setByPath(attr, attrs, value, delim);
                return this.set('attrs', _.merge({}, currentAttrs, attr), opt);

            } else {

                return joint.util.getByPath(currentAttrs, attrs, delim);
            }
        }

        return this.set('attrs', _.merge({}, currentAttrs, attrs), value);
    }

A convenient way to set nested attributes.

A convenient way to set nested attributes .


function(el) {

        var $el = this.$(el);

        if ($el.length === 0 || $el[0] === this.el) {

            // If the overall cell has set `magnet === false`, then return `undefined` to
            // announce there is no magnet found for this cell.
            // This is especially useful to set on cells that have 'ports'. In this case,
            // only the ports have set `magnet === true` and the overall element has `magnet === false`.
            var attrs = this.model.get('attrs') || {};
            if (attrs['.'] && attrs['.']['magnet'] === false) {
                return undefined;
            }

            return this.el;
        }

        if ($el.attr('magnet')) {

            return $el[0];
        }

        return this.findMagnet($el.parent());
    }

Find the closest element that has the `magnet` attribute set to `true`. If there was not such an element found, return the root element of the cell view.

Find the closest element that has the magnet attribute set to true . If there was not such an element found return the root element of the cell view .


function(el, selector) {

        if (el === this.el) {

            return selector;
        }

        var index = $(el).index();

        selector = el.tagName + ':nth-child(' + (index + 1) + ')' + ' ' + (selector || '');

        return this.getSelector($(el).parent()[0], selector + ' ');
    }

function
(
el
,
selector
)
{
if
(
el
===
this
.
el
)
{
return
selector
;
}
var
index
=
$
(
el
)
.
index
(
)
;
selector
=
el
.
tagName
+
':nth-child('
+
(
index
+
1
)
+
')'
+
' '
+
(
selector
||
''
)
;
return
this
.
getSelector
(
$
(
el
)
.
parent
(
)
[
0
]
,
selector
+
' '
)
;
}

Construct a unique selector for the `el` element within this view. `selector` is being collected through the recursive call. No value for `selector` is expected when using this method.

Construct a unique selector for the el element within this view . selector is being collected through the recursive call . No value for selector is expected when using this method .


function() {

        var markup = this.model.markup || this.model.get('markup');

        if (markup) {

            var nodes = V(markup);
            V(this.el).append(nodes);

        } else {

            throw new Error('properties.markup is missing while the default render() implementation is used.');
        }

        this.update();

        this.resize();
        this.rotate();
        this.translate();

        return this;
    }

`prototype.markup` is rendered by default. Set the `markup` attribute on the model if the default markup is not desirable.

prototype . markup is rendered by default . Set the markup attribute on the model if the default markup is not desirable .


function(idx, value) {

        idx = idx || 0;

        var labels = this.get('labels') || [];

        // Is it a getter?
        if (arguments.length === 0 || arguments.length === 1) {

            return labels[idx];
        }

        var newValue = _.merge({}, labels[idx], value);

        var newLabels = labels.slice();
        newLabels[idx] = newValue;

        return this.set({ labels: newLabels });
    }

function
(
idx
,
value
)
{
idx
=
idx
||
0
;
var
labels
=
this
.
get
(
'labels'
)
||
[
]
;
// Is it a getter?
if
(
arguments
.
length
===
0
||
arguments
.
length
===
1
)
{
return
labels
[
idx
]
;
}
var
newValue
=
_
.
merge
(
{
}
,
labels
[
idx
]
,
value
)
;
var
newLabels
=
labels
.
slice
(
)
;
newLabels
[
idx
]
=
newValue
;
return
this
.
set
(
{
labels
:
newLabels
}
)
;
}

A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter.

A convenient way to set labels . Currently set values will be mixined with value if used as a setter .


function(endType) {

        function watchEnd(link, end) {

            end = end || {};

            var previousEnd = link.previous(endType) || {};

            // Pick updateMethod this._sourceBboxUpdate or this._targetBboxUpdate.
            var updateEndFunction = this['_' + endType + 'BBoxUpdate'];

            if (this._isModel(previousEnd)) {
                this.stopListening(this.paper.getModelById(previousEnd.id), 'change', updateEndFunction);
            }

            if (this._isModel(end)) {
                // If the observed model changes, it caches a new bbox and do the link update.
                this.listenTo(this.paper.getModelById(end.id), 'change', updateEndFunction);
            }

            _.bind(updateEndFunction, this)({ cacheOnly: true });

            return this;
        }

        return watchEnd;
    }

Returns a function observing changes on an end of the link. If a change happens and new end is a new model, it stops listening on the previous one and starts listening to the new one.

Returns a function observing changes on an end of the link . If a change happens and new end is a new model it stops listening on the previous one and starts listening to the new one .


function(vertex) {

        this.model.set('attrs', this.model.get('attrs') || {});
        var attrs = this.model.get('attrs');

        // As it is very hard to find a correct index of the newly created vertex,
        // a little heuristics is taking place here.
        // The heuristics checks if length of the newly created
        // path is lot more than length of the old path. If this is the case,
        // new vertex was probably put into a wrong index.
        // Try to put it into another index and repeat the heuristics again.

        var vertices = (this.model.get('vertices') || []).slice();
        // Store the original vertices for a later revert if needed.
        var originalVertices = vertices.slice();

        // A `<path>` element used to compute the length of the path during heuristics.
        var path = this._V.connection.node.cloneNode(false);

        // Length of the original path.
        var originalPathLength = path.getTotalLength();
        // Current path length.
        var pathLength;
        // Tolerance determines the highest possible difference between the length
        // of the old and new path. The number has been chosen heuristically.
        var pathLengthTolerance = 20;
        // Total number of vertices including source and target points.
        var idx = vertices.length + 1;

        // Loop through all possible indexes and check if the difference between
        // path lengths changes significantly. If not, the found index is
        // most probably the right one.
        while (idx--) {

            vertices.splice(idx, 0, vertex);
            V(path).attr('d', this.getPathData(vertices));

            pathLength = path.getTotalLength();

            // Check if the path lengths changed significantly.
            if (pathLength - originalPathLength > pathLengthTolerance) {

                // Revert vertices to the original array. The path length has changed too much
                // so that the index was not found yet.
                vertices = originalVertices.slice();

            } else {

                break;
            }
        }

        this.model.set('vertices', vertices);

        // In manhattan routing, if there are no vertices, the path length changes significantly
        // with the first vertex added. Shall we check vertices.length === 0? at beginning of addVertex()
        // in order to avoid the temporary path construction and other operations?
        return Math.max(idx, 0);
    }

This method ads a new vertex to the `vertices` array of `.connection`. This method uses a heuristic to find the index at which the new `vertex` should be placed at assuming the new vertex is somewhere on the path.

This method ads a new vertex to the vertices array of . connection . This method uses a heuristic to find the index at which the new vertex should be placed at assuming the new vertex is somewhere on the path .


function findMiddleVertex(p1, p2, preferredDirection) {

            var direction = bestDirection(p1, p2, preferredDirection);
            if (direction === 'down' || direction === 'up') {
                return { x: p1.x, y: p2.y, d: direction };
            }
            return { x: p2.x, y: p1.y, d: direction };
        }

function findMiddleVertex ( p1 , p2 , preferredDirection ) { var direction = bestDirection ( p1 , p2 , preferredDirection ) ; if ( direction === 'down' || direction === 'up' ) { return { x : p1 . x , y : p2 . y , d : direction } ; } return { x : p2 . x , y : p1 . y , d : direction } ; }

Find a vertex in between the vertices `p1` and `p2` so that the route between those vertices is orthogonal. Prefer going the direction determined by `preferredDirection`.

Find a vertex in between the vertices p1 and p2 so that the route between those vertices is orthogonal . Prefer going the direction determined by preferredDirection .


function(cell) {

        var id = _.isString(cell) ? cell : cell.id;

        var $view = this.$('[model-id="' + id + '"]');
        if ($view.length) {

            return $view.data('view');
        }
        return undefined;
    }

function ( cell ) { var id = _ . isString ( cell ) ? cell : cell . id ; var $view = this . $ ( '[model-id="' + id + '"]' ) ; if ( $view . length ) { return $view . data ( 'view' ) ; } return undefined ; }

Find a view for a model `cell`. `cell` can also be a string representing a model `id`.

Find a view for a model cell . cell can also be a string representing a model id .


function(p) {

	p = g.point(p);

        var views = _.map(this.model.getElements(), this.findViewByModel);

	return _.filter(views, function(view) {
	    return g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p);
	}, this);
    }

function ( p ) { p = g . point ( p ) ; var views = _ . map ( this . model . getElements ( ) , this . findViewByModel ) ; return _ . filter ( views , function ( view ) { return g . rect ( V ( view . el ) . bbox ( false , this . viewport ) ) . containsPoint ( p ) ; } , this ) ; }


function(r) {

	r = g.rect(r);

        var views = _.map(this.model.getElements(), this.findViewByModel);

	return _.filter(views, function(view) {
	    return r.intersect(g.rect(V(view.el).bbox(false, this.viewport)));
	}, this);
    }

function ( r ) { r = g . rect ( r ) ; var views = _ . map ( this . model . getElements ( ) , this . findViewByModel ) ; return _ . filter ( views , function ( view ) { return r . intersect ( g . rect ( V ( view . el ) . bbox ( false , this . viewport ) ) ) ; } , this ) ; }


function(command) {

	return _.isArray(command)

	    ? _.find(command, function(singleCmd) { return !this._validateCommand(singleCmd); }, this)

	    : this._validateCommand(command);
    }

function ( command ) { return _ . isArray ( command ) ? _ . find ( command , function ( singleCmd ) { return ! this . _validateCommand ( singleCmd ) ; } , this ) : this . _validateCommand ( command ) ; }

iterates throught each command, stops on first invalid command.

iterates throught each command stops on first invalid command .


function(command) {

	// Backbone.model set() and Backbone.collection add() allow to pass an option parameter.
	// That is also kept within the command. It skips validation if requested.
	if (command.options && command.options.validation === false) return true;

	var handoverErr;

	_.each(this._map[command.action], function(route) {

	    var i = 0;

	    function callbacks(err) {

		var fn = route[i++];

		try {
		    if (fn) {
			fn(err, command, callbacks);
		    } else {
			handoverErr = err;
			return;
		    }
		} catch (err) {
		    callbacks(err);
		}
	    };

	    callbacks(handoverErr);
	});

	if (handoverErr) {

	    if (this.get('cancelInvalid')) this._commandManager.cancel();
	    this.trigger('invalid', handoverErr);
	    return false;
	}

	//command is valid
	return true;
    }

check whether the command is not against any rule


function(path, options) {

        var cell = this.options.cellView.model;

        var value = joint.util.getByPath(cell.attributes, path, '/');
        if (_.isUndefined(value) && !_.isUndefined(options.defaultValue)) {
            value = options.defaultValue;
        }

        if (options.valueRegExp) {

            if (_.isUndefined(value)) {

                throw new Error('Inspector: defaultValue must be present when valueRegExp is used.');
            }

            var valueMatch = value.match(new RegExp(options.valueRegExp));
            value = valueMatch && valueMatch[2];
        }

        return value;
    }

Get the value of the attribute at `path` based on the `options.defaultValue`, and `options.valueRegExp` if present.

Get the value of the attribute at path based on the options . defaultValue and options . valueRegExp if present .


function(type, value, targetElement) {

        switch (type) {
          case 'number':
            value = parseFloat(value);
            break;
          case 'toggle':
            value = targetElement.checked;
            break;
          default:
            value = value;
            break;
        }
        return value;
    }

function ( type , value , targetElement ) { switch ( type ) { case 'number' : value = parseFloat ( value ) ; break ; case 'toggle' : value = targetElement . checked ; break ; default : value = value ; break ; } return value ; }

Parse the input `value` based on the input `type`. Override this method if you need your own specific parsing.

Parse the input value based on the input type . Override this method if you need your own specific parsing .


function findMinSlack() {
    var result,
        eSlack = Number.POSITIVE_INFINITY;
    minLen.forEach(function(mle /* minLen entry */) {
      if (remaining.has(mle.u) !== remaining.has(mle.v)) {
        var mleSlack = rankUtil.slack(g, mle.u, mle.v, mle.len);
        if (mleSlack < eSlack) {
          if (!remaining.has(mle.u)) {
            result = {
              treeNode: mle.u,
              graphNode: mle.v,
              len: mle.len,
              reversed: false,
              weight: mle.weight
            };
          } else {
            result = {
              treeNode: mle.v,
              graphNode: mle.u,
              len: -mle.len,
              reversed: true,
              weight: mle.weight
            };
          }
          eSlack = mleSlack;
        }
      }
    });

    return result;
  }

function
findMinSlack
(
)
{
var
result
,
eSlack
=
Number
.
POSITIVE_INFINITY
;
minLen
.
forEach
(
function
(
mle
/* minLen entry */
)
{
if
(
remaining
.
has
(
mle
.
u
)
!==
remaining
.
has
(
mle
.
v
)
)
{
var
mleSlack
=
rankUtil
.
slack
(
g
,
mle
.
u
,
mle
.
v
,
mle
.
len
)
;
if
(
mleSlack
<
eSlack
)
{
if
(
!
remaining
.
has
(
mle
.
u
)
)
{
result
=
{
treeNode
:
mle
.
u
,
graphNode
:
mle
.
v
,
len
:
mle
.
len
,
reversed
:
false
,
weight
:
mle
.
weight
}
;
}
else
{
result
=
{
treeNode
:
mle
.
v
,
graphNode
:
mle
.
u
,
len
:
mle
.
len
,
reversed
:
true
,
weight
:
mle
.
weight
}
;
}
eSlack
=
mleSlack
;
}
}
}
)
;
return
result
;
}

Finds the next edge with the minimum slack.

Finds the next edge with the minimum slack .


function dfs(n) {
    var children = spanningTree.successors(n);
    for (var c in children) {
      var child = children[c];
      dfs(child);
    }
    if (n !== spanningTree.graph().root) {
      setCutValue(graph, spanningTree, n);
    }
  }

function dfs ( n ) { var children = spanningTree . successors ( n ) ; for ( var c in children ) { var child = children [ c ] ; dfs ( child ) ; } if ( n !== spanningTree . graph ( ) . root ) { setCutValue ( graph , spanningTree , n ) ; } }


function redirect(v) {
    var edges = tree.inEdges(v);
    for (var i in edges) {
      var e = edges[i];
      var u = tree.source(e);
      var value = tree.edge(e);
      redirect(u);
      tree.delEdge(e);
      value.reversed = !value.reversed;
      tree.addEdge(e, v, u, value);
    }
  }

function redirect ( v ) { var edges = tree . inEdges ( v ) ; for ( var i in edges ) { var e = edges [ i ] ; var u = tree . source ( e ) ; var value = tree . edge ( e ) ; redirect ( u ) ; tree . delEdge ( e ) ; value . reversed = ! value . reversed ; tree . addEdge ( e , v , u , value ) ; } }

Redirect edges so that target is the root of its subtree.

Redirect edges so that target is the root of its subtree .


function Set(initialKeys) {
  this._size = 0;
  this._keys = {};

  if (initialKeys) {
    for (var i = 0, il = initialKeys.length; i < il; ++i) {
      this.add(initialKeys[i]);
    }
  }
}

function Set ( initialKeys ) { this . _size = 0 ; this . _keys = { } ; if ( initialKeys ) { for ( var i = 0 , il = initialKeys . length ; i < il ; ++ i ) { this . add ( initialKeys [ i ] ) ; } } }

Constructs a new Set with an optional set of `initialKeys`.

It is important to note that keys are coerced to String for most purposes
with this object, similar to the behavior of JavaScript's Object. For
example, the following will add only one key:

var s = new Set();
s.add(1);
s.add("1");

However, the type of the key is preserved internally so that `keys` returns
the original key set uncoerced. For the above example, `keys` would return
`[1]`.

Constructs a new Set with an optional set of initialKeys .


function createCanvas() {

	    canvas = document.createElement('canvas');
	    canvas.width = imageWidth;
	    canvas.height = imageHeight;

	    // Draw rectangle of a certain color covering the whole canvas area.
	    // A JPEG image has black background by default and it might not be desirable.
	    context = canvas.getContext('2d');
	    context.fillStyle = options.backgroundColor || 'white';
	    context.fillRect(0, 0, imageWidth, imageHeight);
	}


function on (el, types, fn, context) {
  types.split(' ').forEach(function (type) {
    L.DomEvent.on(el, type, fn, context)
  })
}

function
on
(
el
,
types
,
fn
,
context
)
{
types
.
split
(
' '
)
.
forEach
(
function
(
type
)
{
L
.
DomEvent
.
on
(
el
,
type
,
fn
,
context
)
}
)
}