Creates a new NIO.

        :param node: Dynamips node instance
        :param nio_settings: information to create the NIO

        :returns: a NIO object
776331
def create_nio(self, node, nio_settings):
        

        nio = None
        if nio_settings["type"] == "nio_udp":
            lport = nio_settings["lport"]
            rhost = nio_settings["rhost"]
            rport = nio_settings["rport"]
            try:
                info = socket.getaddrinfo(rhost, rport, socket.AF_UNSPEC, socket.SOCK_DGRAM, 0, socket.AI_PASSIVE)
                if not info:
                    raise DynamipsError("getaddrinfo returns an empty list on {}:{}".format(rhost, rport))
                for res in info:
                    af, socktype, proto, _, sa = res
                    with socket.socket(af, socktype, proto) as sock:
                        sock.connect(sa)
            except OSError as e:
                raise DynamipsError("Could not create an UDP connection to {}:{}: {}".format(rhost, rport, e))
            nio = NIOUDP(node, lport, rhost, rport, nio_settings.get("filters", {}))
        elif nio_settings["type"] == "nio_generic_ethernet":
            ethernet_device = nio_settings["ethernet_device"]
            if sys.platform.startswith("win"):
                # replace the interface name by the GUID on Windows
                windows_interfaces = interfaces()
                npf_interface = None
                for interface in windows_interfaces:
                    if interface["name"] == ethernet_device:
                        npf_interface = interface["id"]
                if not npf_interface:
                    raise DynamipsError("Could not find interface {} on this host".format(ethernet_device))
                else:
                    ethernet_device = npf_interface
            if not is_interface_up(ethernet_device):
                raise aiohttp.web.HTTPConflict(text="Ethernet interface {} is down".format(ethernet_device))
            nio = NIOGenericEthernet(node.hypervisor, ethernet_device)
        elif nio_settings["type"] == "nio_linux_ethernet":
            if sys.platform.startswith("win"):
                raise DynamipsError("This NIO type is not supported on Windows")
            ethernet_device = nio_settings["ethernet_device"]
            nio = NIOLinuxEthernet(node.hypervisor, ethernet_device)
        elif nio_settings["type"] == "nio_tap":
            tap_device = nio_settings["tap_device"]
            nio = NIOTAP(node.hypervisor, tap_device)
            if not is_interface_up(tap_device):
                # test after the TAP interface has been created (if it doesn't exist yet)
                raise aiohttp.web.HTTPConflict(text="TAP interface {} is down".format(tap_device))
        elif nio_settings["type"] == "nio_unix":
            local_file = nio_settings["local_file"]
            remote_file = nio_settings["remote_file"]
            nio = NIOUNIX(node.hypervisor, local_file, remote_file)
        elif nio_settings["type"] == "nio_vde":
            control_file = nio_settings["control_file"]
            local_file = nio_settings["local_file"]
            nio = NIOVDE(node.hypervisor, control_file, local_file)
        elif nio_settings["type"] == "nio_null":
            nio = NIONull(node.hypervisor)
        else:
            raise aiohttp.web.HTTPConflict(text="NIO of type {} is not supported".format(nio_settings["type"]))

        yield from nio.create()
        return nio
226471
def create(cls, interface_id, address, network_value,
               nodeid=1, **kwargs):
        
        data = {'address': address,
                'network_value': network_value,
                'nicid': str(interface_id),
                'auth_request': False,
                'backup_heartbeat': False,
                'nodeid': nodeid,
                'outgoing': False,
                'primary_mgt': False,
                'primary_heartbeat': False}

        for k, v in kwargs.items():
            data.update({k: v})

        return cls(data)
833428
def initialise(self):
        
        self._checkWriteMode()
        self._createSystemTable()
        self._createNetworkTables()
        self._createOntologyTable()
        self._createReferenceSetTable()
        self._createReferenceTable()
        self._createDatasetTable()
        self._createReadGroupSetTable()
        self._createReadGroupTable()
        self._createCallSetTable()
        self._createVariantSetTable()
        self._createVariantAnnotationSetTable()
        self._createFeatureSetTable()
        self._createContinuousSetTable()
        self._createBiosampleTable()
        self._createIndividualTable()
        self._createPhenotypeAssociationSetTable()
        self._createRnaQuantificationSetTable()
1086154
def create_node(doc, node_name, content=nil) #:doc:
      node = Nokogiri::XML::Node.new(node_name, doc)
      node.content = content if content
      node
    end
1167021
def create_basic_op_node(op_name, node, kwargs):
    """"""
    name, input_nodes, _ = get_inputs(node, kwargs)

    node = onnx.helper.make_node(
        op_name,
        input_nodes,
        [name],
        name=name
    )
    return [node]
95007
function nodeGo(config) {
        // Create the node
        RED.nodes.createNode(this, config)

        /** @since 2019-02-02 - the current instance name (url) */
        var uibInstance = config.url // for logging

        log.verbose(`[${uibInstance}] ================ instance registered ================`)

        /** A copy of 'this' object in case we need it in context of callbacks of other functions. @constant {Object} node */
        const node = this

        log.verbose(`[${uibInstance}] = Keys: this, config =`, {'this': Object.keys(node), 'config': Object.keys(config)})

        //#region --- Create local copies of the node configuration (as defined in the .html file)
        // NB: node.id and node.type are also available
        node.name          = config.name || ''
        node.topic         = config.topic || ''
        // TODO: Needs validation as a suitable URL path
        node.url           = config.url  || 'uibuilder'
        node.fwdInMessages = config.fwdInMessages        // @since 2017-09-20 changed to remove default, || with boolean doesn't work properly
        node.allowScripts  = config.allowScripts
        node.allowStyles   = config.allowStyles
        node.debugFE       = config.debugFE
        node.copyIndex     = config.copyIndex
        node.filename      = config.filename
        node.format        = config.format
        node.template      = config.template
        //#endregion ----

        log.verbose(`[${uibInstance}] Node instance settings`, {'name': node.name, 'topic': node.topic, 'url': node.url, 'fwdIn': node.fwdInMessages, 'allowScripts': node.allowScripts, 'allowStyles': node.allowStyles, 'debugFE': node.debugFE })

        // Keep a log of the active instances @since 2019-02-02
        instances[node.id] = node.url
        log.verbose(`[${uibInstance}] Node Instances Registered`, instances)

        /** Name of the fs path used to hold custom files & folders for THIS INSTANCE of uibuilder
         *   Files in this folder are also served to URL but take preference
         *   over those in the nodes folders (which act as defaults) @type {string}
         */
        node.customFolder = path.join(uib_rootPath, node.url)

        /** User supplied vendor packages
         * & only if using dev folders (delete ~/.node-red/uibuilder/<url>/dist/index.html)
         * JK @since 2017-08-17 fix for non-existent properties and use getProps()
         * JK @since 2018-01-06 use uib_globalSettings instead of RED.settings.uibuilder. At least an empty array is returned.
         * @type {Array}
         */
        node.userVendorPackages = uiblib.getProps(RED,config,'userVendorPackages',null) || uiblib.getProps(RED,uib_globalSettings,'userVendorPackages',[])

        log.verbose(`[${uibInstance}] Node package details`, { 'usrVendorPkgs': node.userVendorPackages, 'customAppFldr': uib_rootPath, 'customFldr': node.customFolder } )

        //#region ---- Socket.IO instance configuration ----
        /** How many Socket clients connected to this instance? @type {integer} */
        node.ioClientsCount = 0
        /** How many msg's received since last reset or redeploy? @type {integer} */
        node.rcvMsgCount = 0
        /** The channel names for Socket.IO @type {Object} */
        node.ioChannels = {control: 'uiBuilderControl', client: 'uiBuilderClient', server: 'uiBuilder'}
        /** Make sure each node instance uses a separate Socket.IO namespace - WARNING: This HAS to match the one derived in uibuilderfe.js
         * @since v1.0.10, changed namespace creation to correct a missing / if httpNodeRoot had been changed from the default. @type {string} */
        node.ioNamespace = tilib.urlJoin(httpNodeRoot, node.url)
        //#endregion ---- ----

        log.verbose(`[${uibInstance}] Socket.io details`, { 'ClientCount': node.ioClientsCount, 'rcvdMsgCount': node.rcvMsgCount, 'Channels': node.ioChannels, 'Namespace': node.ioNamespace } )

        // Keep track of the number of times each instance is deployed.
        // The initial deployment = 1
        if ( deployments.hasOwnProperty(node.id) ) deployments[node.id]++
        else deployments[node.id] = 1
        log.verbose(`[${uibInstance}] Number of Deployments`, deployments[node.id] )

        // We need an http server to serve the page. @since 2019-02-04 removed httpAdmin - we only want to use httpNode for web pages
        const app = RED.httpNode // || RED.httpAdmin

        /** Provide the ability to have a ExpressJS middleware hook.
         * This can be used for custom authentication/authorisation or anything else.
         * The function must be defined in settings.js
         * @since v1.0.3 2017-12-15
         */
        var httpMiddleware = function(req,res,next) { next() }
        if ( uib_globalSettings.hasOwnProperty('middleware') ) {
            /** Is a uibuilder specific function available? */
            if ( typeof uib_globalSettings.middleware === 'function' ) {
                log.verbose(`[${uibInstance}] Using uibuilder specific middleware from settings.js`)
                httpMiddleware = uib_globalSettings.middleware
            }
        } else {
            /** If not, see if the Node-RED one is available and use that instead.
             * Use httNodeMiddleware function which is defined in settings.js
             * as for the http in/out nodes - normally used for authentication
             */
            if ( typeof RED.settings.httpNodeMiddleware === 'function' ) {
                log.verbose(`[${uibInstance}] Using Node-RED middleware from settings.js`)
                httpMiddleware = RED.settings.httpNodeMiddleware
            }
        }

        /** This ExpressJS middleware runs when the uibuilder page loads
         * @see https://expressjs.com/en/guide/using-middleware.html */
        function localMiddleware (req, res, next) {
            // Tell the client what Socket.IO namespace to use,
            // trim the leading slash because the cookie will turn it into a %2F
            res.setHeader('uibuilder-namespace', node.ioNamespace)
            res.cookie('uibuilder-namespace', tilib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true})
            next()
        }

        //#region ----- Create local folder structure ----- //
        var customStatic = function(req,res,next) { next() } // Dummy ExpressJS middleware, replaced by local static folder if needed
        var customFoldersOK = true
        // TODO: May be better as async calls - probably not, but a promisified version would be OK?
        // Make sure the global custom folder exists first
        try {
            fs.mkdirSync(uib_rootPath) // try to create
            fs.accessSync( uib_rootPath, fs.constants.W_OK ) // try to access
        } catch (e) {
            if ( e.code !== 'EEXIST' ) { // ignore folder exists error
                log.error(`[${uibInstance}] Custom folder ERROR, path: ${uib_rootPath}`, e.message)
                customFoldersOK = false
            }
        }
        // make sure the folder for this node instance exists
        try {
            fs.mkdirSync(node.customFolder)
            fs.accessSync(node.customFolder, fs.constants.W_OK)
        } catch (e) {
            if ( e.code !== 'EEXIST' ) {
                log.error(`[${uibInstance}] Local custom folder ERROR`, e.message)
                customFoldersOK = false
            }
        }
        // Then make sure the DIST & SRC folders for this node instance exist
        try {
            fs.mkdirSync( path.join(node.customFolder, 'dist') )
            fs.mkdirSync( path.join(node.customFolder, 'src') )
        } catch (e) {
            if ( e.code !== 'EEXIST' ) {
                log.error(`[${uibInstance}] Local custom dist or src folder ERROR`, e.message)
                customFoldersOK = false
            }
        }

        // We've checked that the custom folder is there and has the correct structure
        if ( customFoldersOK === true ) {
            // local custom folders are there ...
            log.debug(`[${uibInstance}] Using local front-end folders in`, node.customFolder)

            /** Now copy files from the master template folder (instead of master src) @since 2017-10-01
             *  Note: We don't copy the master dist folder
             *  Don't copy if copy turned off in admin ui 
             * TODO: always copy index.html */
            if ( node.copyIndex ) {
                const cpyOpts = {'overwrite':false, 'preserveTimestamps':true}
                fs.copy( path.join( masterTemplateFolder, templateToUse ), path.join(node.customFolder, 'src'), cpyOpts, function(err){
                    if(err){
                        log.error(`[${uibInstance}] Error copying template files from ${path.join( __dirname, 'templates')} to ${path.join(node.customFolder, 'src')}`, err)
                    } else {
                        log.debug(`[${uibInstance}] Copied template files to local src (not overwriting)`, node.customFolder )
                    }
                })
            }
        } else {
            // Local custom folders are not right!
            log.error(`[${uibInstance}] Wanted to use local front-end folders in ${node.customFolder} but could not`)
        }

        //#region Add static path for local custom files
        // TODO: need a build capability for dist - nb probably keep vendor and private code separate
        try {
            // Check if local dist folder contains an index.html & if NR can read it - fall through to catch if not
            fs.accessSync( path.join(node.customFolder, 'dist', 'index.html'), fs.constants.R_OK )
            // If the ./dist/index.html exists use the dist folder...
            log.debug(`[${uibInstance}] Using local dist folder`)
            customStatic = serveStatic( path.join(node.customFolder, 'dist') )
            // NOTE: You are expected to have included vendor packages in
            //       a build process so we are not loading them here
        } catch (e) {
            // dist not being used or not accessible, use src
            log.debug(`[${uibInstance}] Dist folder not in use or not accessible. Using local src folder`, e.message )
            customStatic = serveStatic( path.join(node.customFolder, 'src') )
            // Include vendor resource source paths if needed
            node.userVendorPackages.forEach(function (packageName) {
                // @since 2017-09-19 Using get-installed-path to find where a module is actually installed
                // @since 2017-09-19 AND try require.resolve() as backup (NB this may return unusable path for linked modules)
                var installPath = ''
                try { //@since 2017-09-21 force cwd to be NR's UserDir - Colin Law
                    installPath = getInstalledPathSync(packageName, {local:true, cwd: userDir})
                } catch (e1) {
                    // if getInstalledPath fails, try nodejs internal resolve
                    try {
                        // @since 2017-11-11 v1.0.2 resolve returns the root script not the path
                        installPath = path.dirname( require.resolve(packageName) )
                    } catch (e2) {
                        log.error(`[${uibInstance}] Failed to add user vendor path - no install found for ${packageName}.  Try doing "npm install ${packageName} --save" from ${userDir}`, e2.message );
                        RED.log.warn(`uibuilder:${uibInstance}: Failed to add user vendor path - no install found for ${packageName}.  Try doing "npm install ${packageName} --save" from ${userDir}`)
                    }
                }
                if (installPath !== '') {
                    let vendorPath = tilib.urlJoin(node.url, 'vendor', packageName)
                    log.info(`[${uibInstance}] Adding user vendor path`, {
                        'url': vendorPath, 'path': installPath
                    })
                    app.use( vendorPath, serveStatic(installPath) )
                    vendorPaths[packageName] = {'url': vendorPath, 'path': installPath}
                }
            }) // -- end of forEach vendor package -- //
        }
        //#endregion -- Added static path for local custom files -- //
        //#endregion ------ End of Create custom folder structure ------- //

        /** Create a new, additional static http path to enable
         * loading of central static resources for uibuilder */
        var masterStatic = function(req,res,next) { next() }
        //Object.defineProperty(f, 'name', {value: myName, writable: false})
        try {
            // Will we use "compiled" version of module front-end code?
            fs.accessSync( path.join(__dirname, 'dist', 'index.html'), fs.constants.R_OK )
            log.debug(`[${uibInstance}] Using master production build folder`)
            // If the ./dist/index.html exists use the dist folder...
            masterStatic = serveStatic( path.join( __dirname, 'dist' ) )
        } catch (e) {
            // ... otherwise, use dev resources at ./src/
            log.debug(`[${uibInstance}] Using master src folder and master vendor packages` )
            log.debug('        Reason for not using master dist folder: ', e.message )
            masterStatic = serveStatic( path.join( __dirname, 'src' ) )
            // Include vendor resource source paths if needed
            vendorPackages.forEach(function (packageName) {
                // @since 2017-09-19 Using get-installed-path to find where a module is actually installed
                // @since 2017-09-19 AND try require.resolve() as backup (NB this may return unusable path for linked modules)
                var installPath = ''
                try { //@since 2017-09-21 force cwd to be NR's UserDir - Colin Law
                    installPath = getInstalledPathSync(packageName, {local:true, cwd: userDir})
                } catch (e1) {
                    // if getInstalledPath fails, try nodejs internal resolve
                    try {
                        // @since 2017-11-11 v1.0.2 resolve returns the root script not the path
                        installPath = path.dirname( require.resolve(packageName) )
                    } catch (e2) {
                        log.error(`[${uibInstance}] Failed to add master vendor path - no install found for ${packageName}. Should have been installed by this module`)
                        RED.log.warn(`uibuilder:${uibInstance}: Failed to add master vendor path - no install found for ${packageName}. Should have been installed by this module`)
                    }
                }
                if (installPath !== '') {
                    log.info(`[${uibInstance}] Adding master vendor path`, {
                        'url':  tilib.urlJoin(node.url, 'vendor', packageName), 'path': installPath
                    } )
                    app.use( tilib.urlJoin(node.url, 'vendor', packageName), serveStatic(installPath) )
                }
            })
        }

        app.use( tilib.urlJoin(node.url), httpMiddleware, localMiddleware, customStatic, masterStatic )

        const fullPath = tilib.urlJoin( httpNodeRoot, node.url ) // same as node.ioNamespace

        log.info(`[${uibInstance}] Version ${nodeVersion} started at URL ${fullPath}`)
        log.info(`[${uibInstance}] UI Source files at ${node.customFolder}`)
        RED.log.info(`uibuilder:${uibInstance}: UI Builder Version ${nodeVersion} started at URL ${fullPath}`)
        RED.log.info(`uibuilder:${uibInstance}: UI Source files at ${node.customFolder}`)

        //console.dir(app._router.stack)
        //if (debug && process.env.NODE_ENV === 'development') { // Only in dev environment
            // Absolute path to output file
            //var filepath = path.join(__dirname, './routes.generated.txt')
            // Invoke express-print-routes
            //require('express-print-routes')(app, filepath)
        //}

        // We only do the following if io is not already assigned (e.g. after a redeploy)
        uiblib.setNodeStatus( { fill: 'blue', shape: 'dot', text: 'Node Initialised' }, node )

        /** Each deployed instance has it's own namespace @type {Object.ioNameSpace} */
        var ioNs = io.of(node.ioNamespace)

        /** When someone loads the page, it will try to connect over Socket.IO
         *  note that the connection returns the socket instance to monitor for responses from
         *  the ui client instance */
        ioNs.on('connection', function(socket) {
            node.ioClientsCount++

            log.verbose(`[${uibInstance}] Socket connected, clientCount: ${node.ioClientsCount}, ID: ${socket.id}`)

            uiblib.setNodeStatus( { fill: 'green', shape: 'dot', text: 'connected ' + node.ioClientsCount }, node )

            // Let the clients (and output #2) know we are connecting & send the desired debug state
            uiblib.sendControl({
                'uibuilderCtrl': 'client connect',
                'cacheControl': 'REPLAY',          // @since 2017-11-05 v0.4.9 @see WIKI for details
                'debug': node.debugFE,
                '_socketId': socket.id,
                'from': 'server',
                // @since 2018-10-07 v1.0.9 - send server timestamp so that client can work out
                // time difference (UTC->Local) without needing clever libraries.
                'serverTimestamp': (new Date()),
            }, ioNs, node)
            //ioNs.emit( node.ioChannels.control, { 'uibuilderCtrl': 'server connected', 'debug': node.debugFE } )

            // if the client sends a specific msg channel...
            socket.on(node.ioChannels.client, function(msg) {
                log.debug(`[${uibInstance}] Data received from client, ID: ${socket.id}, Msg:`, msg)

                // Make sure the incoming msg is a correctly formed Node-RED msg
                switch ( typeof msg ) {
                    case 'string':
                    case 'number':
                    case 'boolean':
                        msg = { 'topic': node.topic, 'payload': msg}
                }

                // If the sender hasn't added msg._clientId, add the Socket.id now
                if ( ! msg.hasOwnProperty('_socketId') ) {
                    msg._socketId = socket.id
                }

                // Send out the message for downstream flows
                // TODO: This should probably have safety validations!
                node.send(msg)
            })
            socket.on(node.ioChannels.control, function(msg) {
                log.debug(`[${uibInstance}] Control Msg from client, ID: ${socket.id}, Msg:`, msg)

                // Make sure the incoming msg is a correctly formed Node-RED msg
                switch ( typeof msg ) {
                    case 'string':
                    case 'number':
                    case 'boolean':
                        msg = { 'uibuilderCtrl': msg }
                }

                // If the sender hasn't added msg._clientId, add the Socket.id now
                if ( ! msg.hasOwnProperty('_socketId') ) {
                    msg._socketId = socket.id
                }

                // @since 2017-11-05 v0.4.9 If the sender hasn't added msg.from, add it now
                if ( ! msg.hasOwnProperty('from') ) {
                    msg.from = 'client'
                }

                // Send out the message on port #2 for downstream flows
                uiblib.sendControl(msg, ioNs, node)  // fn adds topic if needed
                //node.send([null,msg])
            })

            socket.on('disconnect', function(reason) {
                node.ioClientsCount--
                log.debug(
                    `[${uibInstance}] Socket disconnected, clientCount: ${node.ioClientsCount}, Reason: ${reason}, ID: ${socket.id}`
                )
                if ( node.ioClientsCount <= 0) uiblib.setNodeStatus( { fill: 'blue', shape: 'dot', text: 'connected ' + node.ioClientsCount }, node )
                else uiblib.setNodeStatus( { fill: 'green', shape: 'ring', text: 'connected ' + node.ioClientsCount }, node )
                // Let the control output port know a client has disconnected
                uiblib.sendControl({
                    'uibuilderCtrl': 'client disconnect',
                    'reason': reason,
                    '_socketId': socket.id,
                    'from': 'server'
                }, ioNs, node)
                //node.send([null, {'uibuilderCtrl': 'client disconnect', '_socketId': socket.id, 'topic': node.topic}])
            })

            socket.on('error', function(err) {
                log.error(`[${uibInstance}] ERROR received, ID: ${socket.id}, Reason: ${err.message}`)
                // Let the control output port know there has been an error
                uiblib.sendControl({
                    'uibuilderCtrl': 'socket error',
                    'error': err.message,
                    '_socketId': socket.id,
                    'from': 'server'
                }, ioNs, node)
            })

            /* More Socket.IO events but we really don't need to monitor them
                socket.on('disconnecting', function(reason) {
                    RED.log.audit({
                        'UIbuilder': node.url+' DISCONNECTING received', 'ID': socket.id,
                        'data': reason
                    })
                })
                socket.on('newListener', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' NEWLISTENER received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('removeListener', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' REMOVELISTENER received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('ping', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' PING received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('pong', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' PONG received', 'ID': socket.id,
                        'data': data
                    })
                })
            */

        }) // ---- End of ioNs.on connection ---- //

        /** Handler function for node input events (when a node instance receives a msg)
         * @param {Object} msg The msg object received.
         **/
        function nodeInputHandler(msg) {
            log.verbose(`[${uibInstance}] nodeGo:nodeInputHandler - emit received msg - Namespace: ${node.url}`) //debug

            // If msg is null, nothing will be sent
            if ( msg !== null ) {
                // if msg isn't null and isn't an object
                // NOTE: This is paranoid and shouldn't be possible!
                if ( typeof msg !== 'object' ) {
                    // Force msg to be an object with payload of original msg
                    msg = { 'payload': msg }
                }
                // Add topic from node config if present and not present in msg
                if ( !(msg.hasOwnProperty('topic')) || msg.topic === '' ) {
                    if ( node.topic !== '' ) msg.topic = node.topic
                    else msg.topic = 'uibuilder'
                }
            }

            // Keep this fn small for readability so offload
            // any further, more customised code to another fn
            msg = uiblib.inputHandler(msg, node, RED, io, ioNs, log)

        } // -- end of msg received processing -- //

        // Process inbound messages
        node.on('input', nodeInputHandler)

        // Do something when Node-RED is closing down
        // which includes when this node instance is redeployed
        node.on('close', function(removed,done) {
            log.debug(`[${uibInstance}] nodeGo:on-close: ${removed?'Node Removed':'Node (re)deployed'}`)

            node.removeListener('input', nodeInputHandler)

            // Do any complex close processing here if needed - MUST BE LAST
            //processClose(null, node, RED, ioNs, io, app) // swap with below if needing async
            uiblib.processClose(done, node, RED, ioNs, io, app, log, instances)

            done()
        })

    }
325594
function newNetwork(instance, nodesID, nodesName, response) {
  const viewID = misc.uuidv4().slice(0, 8);
  const edgesID = response.workflowID.slice(0, 8);
  return updateItem(instance, item => {
    item.views.push({
      $schema: "https://mojaie.github.io/kiwiii/specs/network_v1.0.json",
      viewID: viewID,
      name: `${nodesName}_${response.name}`,
      viewType: 'network',
      nodes: nodesID,
      edges: edgesID,
      minConnThld: response.query.params.threshold
    });
    item.dataset.push({
      $schema: "https://mojaie.github.io/kiwiii/specs/collection_v1.0.json",
      collectionID: edgesID,
      name: response.name,
      contents: [response]
    });
  }).then(() => viewID);
}
668358
def add_nio(self, nio, port_number):
        

        if port_number not in [port["port_number"] for port in self._ports]:
            raise DynamipsError("Port {} doesn't exist".format(port_number))

        if port_number in self._mappings:
            raise DynamipsError("Port {} isn't free".format(port_number))

        yield from Bridge.add_nio(self, nio)

        log.info('Ethernet hub "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
                                                                                       id=self._id,
                                                                                       nio=nio,
                                                                                       port=port_number))
        self._mappings[port_number] = nio
620069
def new(self, node: Node):
        """"""
        return Property(self.name, self._setter, node)
1230050
function Node (host, customSettings) {
  let node = new EventEmitter()

  let _settings = {...defaultSettings, ...customSettings, host}
  _validateSettings(_settings)

  let _id = getNodeId(_settings)
  let _name = nodeIdToName(_id)
  let _active = false
  let _deactivating = false
  let _canPublish = false
  let _receiving = false
  let _master = null

  let { external } = _settings

  //  Debug
  const _debugStr = `dnsmq-messagebus:${external ? 'externalnode' : 'dnsnode'}`
  const _debug = D(_debugStr)
  const debug = (...args) => _debug(_name, ...args)

  /**
   * starts a master node resolution;
   * if a master node is found starts a connection to it
   */
  const _seekForMaster = () => {
    if (!_active || _masterResolver.isResolving) return
    _masterResolver
    .resolve()
    .then(_connectToMaster)
    .catch(() => {
      _seekForMaster()
    })
  }
  /**
   * starts a connection of the PUB and SUB interfaces
   * to a given master
   * @param  {string} id
   * @param  {string} name
   * @param  {object} endpoints
   */
  const _connectToMaster = ({id, name, endpoints}) => {
    if (!_active) return
    _master = {id, name, endpoints}
    _subConnection.connect({name, endpoint: endpoints.pub})
    _pubConnection.connect({name, endpoint: endpoints.sub})
    if (!external) {
      name === _name ? _masterBroker.startHeartbeats() : _masterBroker.stoptHeartbeats()
    }
  }

  /**
   * publish interface
   * @type {object}
   */
  let _pubConnection = PubConnection(node)
  _pubConnection.on('connect', () => {
    _canPublish = true
    node.emit('can:publish')
    if (_receiving) node.emit('ready')
  })
  _pubConnection.on('disconnect', () => {
    _canPublish = false
    node.emit('cannot:publish')
    if (_receiving) node.emit('not:ready')
  })

  /**
   * subscribe interface
   * @type {object}
   */
  let _subConnection = SubConnection(node)
  _subConnection.on('missingmaster', () => {
    _pubConnection.disconnect()
    _seekForMaster()
  })
  _subConnection.on('newmaster', _connectToMaster)
  _subConnection.on('connect', () => {
    _receiving = true
    node.emit('receiving')
    if (_canPublish) node.emit('ready')
  })
  _subConnection.on('disconnect', () => {
    _receiving = false
    _master = null
    node.emit('not:receiving')
    if (_canPublish) node.emit('not:ready')
  })

  /**
   * master resolution component
   * @type {object}
   */
  let _masterResolver

  /**
   * master broker component
   * The external nodes dont have this component
   * @type {object}
   */
  let _masterBroker

  if (!external) {
    _masterBroker = MasterBroker(node)
    _masterResolver = MasterElector(node, _masterBroker)
    _masterResolver.on('newmaster', _connectToMaster)
  } else {
    _masterResolver = MasterFinder(node)
  }

  /**
   * Activates the node
   * @return {object} node instance
   */
  function activate () {
    if (_active) return node
    _active = true
    debug('activated')

    if (!external) {
      _masterBroker.bind()
      _masterResolver.bind()
    }
    if (!node.isReady) _seekForMaster()
    return node
  }
  /**
   * Starts the node's deactivation routine
   * @return {object} node instance
   */
  function deactivate () {
    if (!_active || _deactivating) return node
    debug('deactivating')

    if (external) {
      _active = false
      _subConnection.disconnect()
      _pubConnection.disconnect()
      node.emit('deactivated')
    } else {
      _deactivating = true
      let ensuredMaster = Promise.resolve()

      const isMaster = _subConnection.master && _subConnection.master.name === _name

      if (isMaster) {
        debug(`I'm the master node. I will try to elect another master before disconnecting.`)

        let advertiseId = `zz-zzzzzzzz-${_id}`
        ensuredMaster = _masterResolver
                        .resolve(advertiseId)
                        .then(master => {
                          debug(`successfully elected a new master: ${master.name}`)
                          try {
                            _masterBroker.signalNewMaster(master)
                          } catch (e) {
                            console.log(e)
                          }
                        })
                        .catch(() => {
                          debug(`failed to elect a new master. Disconnecting anyway.`)
                        })
      }

      ensuredMaster
      .then(() => {
        _subConnection.disconnect()
        _pubConnection.disconnect()
        _masterResolver.unbind()
        let timeout = isMaster ? 1000 : 1
        setTimeout(() => {
          debug('deactivated')
          node.emit('deactivated')
          _masterBroker.unbind()
        }, timeout)
      })
    }

    return node
  }
  /**
   * Sends a message through the bus, published on a particular channel
   * @param  {string} channel
   * @param  {array} args
   * @return {object} node instance
   */
  function publish (channel, ...args) {
    if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`)
    if (~internalChannels.indexOf(channel)) {
      console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`)
      return node
    }
    if (!_pubConnection.connected) {
      console.warn(`${_debugStr} cannot publish on bus.`)
      return node
    }
    _pubConnection.publish(channel, ...args)
    return node
  }
  /**
   * Subscribes the node to the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function subscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .subscribe([...channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot subscribe to it.`)
        return
      }
      _subConnection.subscribe([channel])
    })
    return node
  }
  /**
   * Unsubscribes the node from the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function unsubscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`)
        return
      }
      _subConnection.unsubscribe([channel])
    })
    return node
  }

  return Object.defineProperties(node, {
    id: {get: () => _id},
    name: {get: () => _name},
    settings: {get: () => ({..._settings})},
    type: {get: () => external ? EXTERNAL_NODE : DNS_NODE},
    canPublish: {get: () => _pubConnection.connected},
    isReceiving: {get: () => _subConnection.connected},
    isReady: {get: () => _pubConnection.connected && _subConnection.connected},
    subscribedChannels: {get: () => _subConnection.subscribedChannels},
    isMaster: {get: () => _master && _master.name === _name || false},
    master: {get: () => _master && {..._master, endpoints: {..._master.endpoints}}},
    activate: {value: activate},
    deactivate: {value: deactivate},
    publish: {value: publish},
    subscribe: {value: subscribe},
    unsubscribe: {value: unsubscribe}
  })
}
949628
def register_new_node(suffix_node_id=None):
    
    node_id = uuid4()
    event = Node.Created(originator_id=node_id, suffix_node_id=suffix_node_id)
    entity = Node.mutate(event=event)
    publish(event)
    return entity
176735
def create(self):
        
        self.service.create()

        # Set env vars for immediate use
        zone_id = predix.config.get_env_key(self.use_class, 'zone_id')
        zone = self.service.settings.data['zone']['http-header-value']
        os.environ[zone_id] = zone

        uri = predix.config.get_env_key(self.use_class, 'uri')
        os.environ[uri] = self.service.settings.data['uri']
574248
def create_bare(self):
        
        self.instances = []
        for ip in self.settings['NODES']:
            new_instance = Instance.new(settings=self.settings, cluster=self)
            new_instance.ip = ip
            self.instances.append(new_instance)
1298869
def slot_add_nio_binding(self, slot_number, port_number, nio):
        

        try:
            adapter = self._slots[slot_number]
        except IndexError:
            raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name,
                                                                                              slot_number=slot_number))

        if adapter is None:
            raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number))

        if not adapter.port_exists(port_number):
            raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
                                                                                                port_number=port_number))

        try:
            yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name,
                                                                                                                         slot_number=slot_number,
                                                                                                                         port_number=port_number,
                                                                                                                         nio=nio))
        except DynamipsError:
            # in case of error try to remove and add the nio binding
            yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name,
                                                                                                                      slot_number=slot_number,
                                                                                                                      port_number=port_number))
            yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name,
                                                                                                                         slot_number=slot_number,
                                                                                                                         port_number=port_number,
                                                                                                                         nio=nio))

        log.info('Router "{name}" [{id}]: NIO {nio_name} bound to port {slot_number}/{port_number}'.format(name=self._name,
                                                                                                           id=self._id,
                                                                                                           nio_name=nio.name,
                                                                                                           slot_number=slot_number,
                                                                                                           port_number=port_number))

        yield from self.slot_enable_nio(slot_number, port_number)
        adapter.add_nio(port_number, nio)
1170216
def create_modelo(self):
        """"""
        return Modelo(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
957086
def create_node(self, network, participant):
        """"""
        return self.models.MCMCPAgent(network=network, participant=participant)
504420
def _create_node(self, name, factory, directory=None, create=1):
        
        import SCons.Util
        node = factory(name, directory, create)
        node.set_noclean(self.noclean)
        node.set_precious(self.precious)
        if self.nodefault:
            self.env.Ignore('.', node)
        if self.alias:
            self.env.AlwaysBuild(self.env.Alias(self.alias, node))
        return node