Creates frontend and backend for a XPUB/XSUB forwarding device
343866
def xpubsubSockets(self, hostSub, portSub, hostPub, portPub):
        '''
        
        '''
        frontend_addr = self.tcpAddress(hostSub, portSub)
        backend_addr = self.tcpAddress(hostPub, portPub)

        frontendSocket = self._context.socket(zmq.SUB)
        frontendSocket.bind(frontend_addr)
        frontendSocket.setsockopt(zmq.SUBSCRIBE, b'')

        backendSocket = self._context.socket(zmq.PUB)
        backendSocket.bind(backend_addr)

        return frontendSocket, backendSocket
863783
def create_app(cls, port):
        
        app = FrontEndApp()
        app_server = GeventServer(app, port=port, hostname='0.0.0.0')
        return app_server
401562
def update_frontend(self, info):
        
        headers = {'Content-Type': 'text/event-stream'}
        if info.get('when'):
            info['when'] = info['when'].isoformat()
        requests.post(self.base_url + '/publish', data=json.dumps(info), headers=headers)
57459
function setupBundler(cwd, entryPoints, flags, noWatchify, ready) {
  noWatchify ?
    onlocalwatchify() :
    resolve('watchify', {basedir: cwd}, onlocalwatchify)

  function onlocalwatchify(err, localDir) {
    if(err || !localDir) {
      return resolve('browserify', {basedir: cwd}, onlocalbrowserify)
    }

    setupWatchify(path.dirname(localDir), entryPoints, flags, ready)
  }

  function onlocalbrowserify(err, localDir) {
    if(err || !localDir) {
      return findGlobals(onglobals)
    }

    setupBrowserify(path.dirname(localDir), entryPoints, flags, ready)
  }

  function onglobals(err, dirs) {
    if(err) {
      return ready(err)
    }

    dirs = dirs.sort()

    for(var i = 0, len = dirs.length; i < len; ++i) {
      if(!noWatchify && path.basename(dirs[i]) === 'watchify') {
        return setupWatchify(dirs[i], entryPoints, flags, ready)
      }

      if(path.basename(dirs[i]) === 'browserify') {
        return setupBrowserify(dirs[i], entryPoints, flags, ready)
      }
    }

    return ready(new Error('Could not find a suitable bundler!'))
  }
}
795120
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
        """"""
        device = '0.0.%s' % fcp
        target = '%s:%s:%s' % (device, target_wwpn, target_lun)
        disk_offline = '/sbin/chzdev zfcp-lun %s -d' % target
        host_offline = '/sbin/chzdev zfcp-host %s -d' % fcp
        offline_dev = 'chccwdev -d %s' % fcp
        return '\n'.join((disk_offline,
                          host_offline,
                          offline_dev))
101159
def setup_backend(
    serve=True,
    host=DEFAULT_HOST,
    port=DEFAULT_PORT,
    debug=False,
    open_browser=True,
    browsername=None,
    testing=False,
    private_key=None,
    certificate=None,
    LLDB=False,
):
    """"""
    app.config["LLDB"] = LLDB

    kwargs = {}
    ssl_context = get_ssl_context(private_key, certificate)
    if ssl_context:
        # got valid ssl context
        # force everything through https
        SSLify(app)
        # pass ssl_context to flask
        kwargs["ssl_context"] = ssl_context

    url = "%s:%s" % (host, port)
    if kwargs.get("ssl_context"):
        protocol = "https://"
        url_with_prefix = "https://" + url
    else:
        protocol = "http://"
        url_with_prefix = "http://" + url

    if debug:
        async_mode = "eventlet"
    else:
        async_mode = "gevent"

    socketio.server_options["async_mode"] = async_mode
    try:
        socketio.init_app(app)
    except Exception:
        print(
            'failed to initialize socketio app with async mode "%s". Continuing with async mode "threading".'
            % async_mode
        )
        socketio.server_options["async_mode"] = "threading"
        socketio.init_app(app)

    if testing is False:
        if host == DEFAULT_HOST:
            url = (DEFAULT_HOST, port)
        else:
            try:
                url = (socket.gethostbyname(socket.gethostname()), port)
            except Exception:
                url = (host, port)

        if open_browser is True and debug is False:
            browsertext = repr(browsername) if browsername else "default browser"
            args = (browsertext,) + url
            text = ("Opening gdbgui with %s at " + protocol + "%s:%d") % args
            print(colorize(text))
            b = webbrowser.get(browsername) if browsername else webbrowser
            b.open(url_with_prefix)
        else:
            print(colorize("View gdbgui at %s%s:%d" % (protocol, url[0], url[1])))

        print("exit gdbgui by pressing CTRL+C")

        try:
            socketio.run(
                app,
                debug=debug,
                port=int(port),
                host=host,
                extra_files=get_extra_files(),
                **kwargs
            )
        except KeyboardInterrupt:
            # Process was interrupted by ctrl+c on keyboard, show message
            pass
261069
def add_port_fwd(zone, src, dest, proto='tcp', dstaddr='', permanent=True):
    '''
    
    '''
    cmd = '--zone={0} --add-forward-port=port={1}:proto={2}:toport={3}:toaddr={4}'.format(
        zone,
        src,
        proto,
        dest,
        dstaddr
    )

    if permanent:
        cmd += ' --permanent'

    return __firewall_cmd(cmd)
830717
function createPreBootstrapServices() {
   const browser = createBrowser();
   const configuration = createConfiguration( window.laxar || {
      name: 'laxar-compatibility',
      logging: { threshold: 'DEBUG' }
   } );
   const i18n = createI18n( configuration );
   const log = createLog( configuration, browser );
   const storage = createStorage( configuration, browser );

   return {
      configuration,
      i18n,
      log,
      storage
   };
}
379547
def main(req_port=None, res_port=None, use_security=False):
    '''
    '''
    if req_port is None:
        req_port = env.get_req_port()
    if res_port is None:
        res_port = env.get_res_port()
    auth = None
    try:
        context = zmq.Context()
        frontend_service = context.socket(zmq.XREP)
        backend_service = context.socket(zmq.XREQ)
        if use_security:
            if not os.path.exists(env.get_server_public_key_dir()):
                create_certificates(env.get_server_public_key_dir())
            auth = Authenticator.instance(env.get_server_public_key_dir())
            auth.set_server_key(
                frontend_service, env.get_server_secret_key_path())
            auth.set_client_key(backend_service, env.get_client_secret_key_path(),
                                env.get_server_public_key_path())
        frontend_service.bind('tcp://*:{req_port}'.format(req_port=req_port))
        backend_service.bind('tcp://*:{res_port}'.format(res_port=res_port))
        zmq.device(zmq.QUEUE, frontend_service, backend_service)
    except KeyboardInterrupt:
        pass
    finally:
        frontend_service.close()
        backend_service.close()
        context.term()
        if use_security and auth is not None:
            auth.stop()
276206
private void createInputHandlersForPubSub()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "createInputHandlersForPubSub");

        // Create the pub-sub input handler.
        _baseDestinationHandler.setInputHandler(
                        new PubSubInputHandler(
                                        _baseDestinationHandler,
                                        _pubSubRemoteSupport.getTargetProtocolItemStream(),
                                        _pubsubMessageItemStream,
                                        _proxyReferenceStream,
                                        _pubSubRemoteSupport.getSourceProtocolItemStream()));

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "createInputHandlersForPubSub");
    }
1218815
def main(pub_port=None, sub_port=None):
    '''
    '''
    try:
        if sub_port is None:
            sub_port = get_sub_port()
        if pub_port is None:
            pub_port = get_pub_port()
        context = zmq.Context(1)
        frontend = context.socket(zmq.SUB)
        backend = context.socket(zmq.PUB)

        frontend.bind('tcp://*:{pub_port}'.format(pub_port=pub_port))
        frontend.setsockopt(zmq.SUBSCRIBE, b'')
        backend.bind('tcp://*:{sub_port}'.format(sub_port=sub_port))
        zmq.device(zmq.FORWARDER, frontend, backend)
    except KeyboardInterrupt:
        pass
    finally:
        frontend.close()
        backend.close()
        context.term()
78176
function FrontRouter() {
    var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

    _classCallCheck(this, FrontRouter);

    this.options = {
      pageRoot: opts.pageRoot || process.cwd(),
      overwrite: opts.overwrite || false
    };
    this.routes = [];

    // Figure out what library to load
    switch (_typeof(opts.library)) {
      // String: pull a library out of the built-in ones
      case 'string':
        {
          var lib = Libraries[opts.library];
          if (typeof lib === 'undefined') {
            throw new Error('Front Router: there\'s no built-in plugin for "' + opts.library + '"');
          } else {
            this.options.library = lib;
          }
          break;
        }
      // Function: add as-is
      case 'function':
        {
          this.options.library = opts.library;
          break;
        }
      // Nothing: use the default library adapter
      case 'undefined':
        {
          this.options.library = Libraries.default;
          break;
        }
      // Other weird values? Nope
      default:
        {
          throw new Error('Front Router: library must be a string or function.');
        }
    }
  }
64760
function HookBackendEvent (adapter, backend, socket) {
          
    function EventDevAuth (device){
        device.websock=0;   // special counter to repost full device every 20 positions
        adapter.Debug (5, "EventDevAuth devid=%s name=%s", device.devid, device.name);
        var msg = 
            {type : 1
               ,devid: device.devid
               ,src  : adapter.src + ' ' + device.adapter.id
               ,model: device.type
               ,name : device.name
               ,call : device.call
               ,cargo: device.cargo
        };
        adapter.BroadcastJson (msg);
    };    
    
    function EventDevTmp (device){
        device.websock=0;   // special counter to repost full device every 20 positions
        adapter.Debug (5, "EventDevTmp devid=%s name=%s", device.devid, device.name);
        var msg = 
        {type : 0
            ,devid: device.devid
            ,src  : adapter.src + ' ' + device.adapter.id
            ,lat  : device.stamp.lat
            ,lon  : device.stamp.lon
            ,sog  : device.stamp.sog
            ,cog  : device.stamp.cog
        };
        adapter.BroadcastJson (msg);
    };    

    // Events successful process by tracker adapter
    function EventDevPos (device){
        adapter.Debug (6, "EventDevPos devid=%s name=%s", device.devid, device.name);
         
         // force push of full device info every 20 positions update
         if (device.websock++ >= 10) EventDevAuth (device); 
         
         var msg = 
            {type : 2
            ,devid: device.devid
            ,src  : adapter.src + ' ' +device.adapter.id
            ,lat  : device.stamp.lat
            ,lon  : device.stamp.lon
            ,sog  : device.stamp.sog
            ,cog  : device.stamp.cog
        };
        adapter.BroadcastJson (msg);
    };
    
    // Events successful process by tracker adapter
    function EventDevPing (device){
        adapter.Debug (7, "EventDevPing devid=%s name=%s", device.devid, device.name);
         
        var msg = 
            {type : 3
            ,devid: device.devid
        };
        adapter.BroadcastJson (msg);
    };
    
     // Events on action refused by tracker adapter
    function EventDevQuit (device){
       var msg=
           {type: 4
           ,devid: device.devid
           };
       adapter.BroadcastJson (msg);
    };

    backend.event.on("dev-tmp" ,EventDevTmp);	
    backend.event.on("dev-auth",EventDevAuth);	
    backend.event.on("dev-pos" ,EventDevPos);	
    backend.event.on("dev-ign" ,EventDevPing);	
    backend.event.on("dev-quit",EventDevQuit);	
}
1096559
def start(bt_device=''):
        '''
        
        '''
        # import ptyprocess here so as long as all implementations are in the same file, all will work
        import ptyprocess

        if not bt_device:
            bt_device = 'hci0'

        log.info('Start receiving broadcasts (device %s)', bt_device)
        DEVNULL = subprocess.DEVNULL if sys.version_info >= (3, 3) else open(os.devnull, 'wb')

        subprocess.call('sudo hciconfig %s reset' % bt_device, shell=True, stdout=DEVNULL)
        hcitool = subprocess.Popen(['sudo', '-n', 'hcitool', 'lescan', '--duplicates'], stdout=DEVNULL)
        hcidump = ptyprocess.PtyProcess.spawn(['sudo', '-n', 'hcidump', '--raw'])
        return (hcitool, hcidump)
1126754
function(conn) {

        this._connection = conn;

        /*
        Function used to setup plugin.
        */

        /* extend name space
        *  NS.PUBSUB - XMPP Publish Subscribe namespace
        *              from XEP 60.
        *
        *  NS.PUBSUB_SUBSCRIBE_OPTIONS - XMPP pubsub
        *                                options namespace from XEP 60.
        */
        Strophe.addNamespace('PUBSUB',"http://jabber.org/protocol/pubsub");
        Strophe.addNamespace('PUBSUB_SUBSCRIBE_OPTIONS',
                             Strophe.NS.PUBSUB+"#subscribe_options");
        Strophe.addNamespace('PUBSUB_ERRORS',Strophe.NS.PUBSUB+"#errors");
        Strophe.addNamespace('PUBSUB_EVENT',Strophe.NS.PUBSUB+"#event");
        Strophe.addNamespace('PUBSUB_OWNER',Strophe.NS.PUBSUB+"#owner");
        Strophe.addNamespace('PUBSUB_AUTO_CREATE',
                             Strophe.NS.PUBSUB+"#auto-create");
        Strophe.addNamespace('PUBSUB_PUBLISH_OPTIONS',
                             Strophe.NS.PUBSUB+"#publish-options");
        Strophe.addNamespace('PUBSUB_NODE_CONFIG',
                             Strophe.NS.PUBSUB+"#node_config");
        Strophe.addNamespace('PUBSUB_CREATE_AND_CONFIGURE',
                             Strophe.NS.PUBSUB+"#create-and-configure");
        Strophe.addNamespace('PUBSUB_SUBSCRIBE_AUTHORIZATION',
                             Strophe.NS.PUBSUB+"#subscribe_authorization");
        Strophe.addNamespace('PUBSUB_GET_PENDING',
                             Strophe.NS.PUBSUB+"#get-pending");
        Strophe.addNamespace('PUBSUB_MANAGE_SUBSCRIPTIONS',
                             Strophe.NS.PUBSUB+"#manage-subscriptions");
        Strophe.addNamespace('PUBSUB_META_DATA',
                             Strophe.NS.PUBSUB+"#meta-data");
        Strophe.addNamespace('ATOM', "http://www.w3.org/2005/Atom");

        if (conn.disco)
            conn.disco.addFeature(Strophe.NS.PUBSUB);

    }
963534
function startWebIDEServer(writeCallback) {
  var httpPort = args.ideServer;
  var server = require("http").createServer(function(req, res) {
    res.end(`<html>
<body style="margin:0px">
<iframe id="ideframe" src="https://www.espruino.com/ide/" style="width:100%;height:100%;border:0px;"></iframe>
<script src="https://www.espruino.com/ide/embed.js"></script>
<script>
  var ws = new WebSocket("ws://" + location.host + "/ws", "serial");
  var Espruino = EspruinoIDE(document.getElementById('ideframe'));
  Espruino.onports = function() {
    return [{path:'local', description:'Connected Device', type : "net"}];
  };
  Espruino.onready = function(data) { Espruino.connect("local");};
  Espruino.onwrite = function(data) { ws.send(data); }
  ws.onmessage = function (event) { Espruino.received(event.data); };
  ws.onclose = function (event) { Espruino.disconnect(); };
</script>
</body>
</html>
`);
  });
  server.listen(httpPort);
  log("Web IDE is now available on http://localhost:"+httpPort);
  /* Start the WebSocket relay - allows standard Websocket MQTT communications */
  var WebSocketServer = require('websocket').server;
  var wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
  });
  var ideConnections = [];
  wsServer.on('request', function(request) {
    // request.reject() based on request.origin?
    var connection = request.accept('serial', request.origin);
    ideConnections.push(connection);
    log('Web IDE Connection accepted.');
    connection.on('message', function(message) {
      if (message.type === 'utf8') writeCallback(message.utf8Data);
    });
    connection.on('close', function(reasonCode, description) {
      log('Web IDE Connection closed.');
      var conIdx = ideConnections.indexOf(connection);
      if (conIdx>=0) ideConnections.splice(conIdx,1);
    });
  });

  return {
    write : function(data) {
      ideConnections.forEach(function(connection) { connection.sendUTF(data) });
    }
  };
}
87863
function xframeFactory(options) {
  options = options || {};

  var str = 'DENY';
  if (isString(options)) {
    str = options;
  } else {
    if (options.sameOrigin) {
      str = 'SAMEORIGIN';
    }
    if (options.allow) {
      if (options.sameOrigin) {
        throw new Error('Cannot specify both ALLOW-FROM and SAMEORIGIN');
      }

      str = 'ALLOW-FROM ' + options.allow;
    }
  }

  return function xframe(req, res, next) {
    res.setHeader(HEADER, str);
    next();
  };
}