DHT object (local)
774903
function DHT (seeds, onConnect, onUpdate) {
	var l_map = {};

	// build DHT connection
	var l_dht = undefined;
		
	// init DHT
	if (seeds instanceof Array) {
		l_dht = kademlia({
  			address: '127.0.0.1',
  			port: 65535,
  			seeds: seeds,
  			storage: levelup('./store/dht_db')
		});
		
		l_dht.on('connect', function () {
			LOG.warn('DHT connected...', 'SR.DHT');
			UTIL.safeCall(onConnect);
		});		
	}
	else
		UTIL.safeCall(onConnect);
	
	this.set = function (key, value, onDone) {
		if (!l_dht) {
			l_map[key] = value;
			return UTIL.safeCall(onDone, true);		
		}
		
		l_dht.put(key, value, function (err) {
			if (err) {
				LOG.error(err, 'SR.DHT');
				UTIL.safeCall(onDone, false);
			}
			else
				UTIL.safeCall(onDone, true);
		});
	};

	this.get = function (key, onDone) {
		if (!l_dht) {
			if (l_map.hasOwnProperty(key))
				UTIL.safeCall(onDone, l_map[key]);
			else
				UTIL.safeCall(onDone);
			return;
		}

 		l_dht.get(key, function (err, value) {
			if (err) {
				LOG.error(err, 'SR.DHT');
				UTIL.safeCall(onDone);				
			}
			else {
				// remove from local & return undefined
				if (value === 'DELETED') {
					delete l_map[key];
					return UTIL.safeCall(onDone);
				}
				
				// update to local
				l_map[key] = value;
				UTIL.safeCall(onDone, value);
			}
		});
	};
	
	this.delete = function (key, onDone) {
		if (!l_dht) {
			
			if (l_map.hasOwnProperty(key)) {
				delete l_map[key];
				UTIL.safeCall(onDone, true);
			}
			else {
				UTIL.safeCall(onDone, false);
			}
			return;
		}
		
		// TODO: need a way to delete?
		l_dht.put(key, 'DELETED', function (err) {
			if (err) {
				LOG.error(err, 'SR.DHT');
				UTIL.safeCall(onDone, false);
			}
			else
				UTIL.safeCall(onDone, true);
		});
	}
}
335787
def __load_uri(self, sock_dir, node):
        '''
        
        '''
        if node == 'master':
            if self.opts['ipc_mode'] == 'tcp':
                puburi = int(self.opts['tcp_master_pub_port'])
                pulluri = int(self.opts['tcp_master_pull_port'])
            else:
                puburi = os.path.join(
                    sock_dir,
                    'master_event_pub.ipc'
                )
                pulluri = os.path.join(
                    sock_dir,
                    'master_event_pull.ipc'
                )
        else:
            if self.opts['ipc_mode'] == 'tcp':
                puburi = int(self.opts['tcp_pub_port'])
                pulluri = int(self.opts['tcp_pull_port'])
            else:
                hash_type = getattr(hashlib, self.opts['hash_type'])
                # Only use the first 10 chars to keep longer hashes from exceeding the
                # max socket path length.
                id_hash = hash_type(salt.utils.stringutils.to_bytes(self.opts['id'])).hexdigest()[:10]
                puburi = os.path.join(
                    sock_dir,
                    'minion_event_{0}_pub.ipc'.format(id_hash)
                )
                pulluri = os.path.join(
                    sock_dir,
                    'minion_event_{0}_pull.ipc'.format(id_hash)
                )
        log.debug('%s PUB socket URI: %s', self.__class__.__name__, puburi)
        log.debug('%s PULL socket URI: %s', self.__class__.__name__, pulluri)
        return puburi, pulluri
529904
function Http(ip) {
    Http['super_'].call(this);

    /**
     * @property options
     * @private
     * @type {{hostname: String, port: Number, path: String, method: String}}
     */
    this.options = {
        hostname: ip,
        port: 80,
        path: '/rpc',
        method: 'POST',
        headers: {
            'Content-Length': 0
        }
    };
}
1148959
function createClientDHInnerData(context) {
    var retryCount = 0;
    if (logger.isDebugEnabled()) {
        logger.debug('Start calculating g_b');
    }
    // Calculate g_b
    var g = context.serverDHInnerData.g;
    var b = utility.createNonce(256);
    var dhPrime = context.serverDHInnerData.dh_prime;
    var gb = utility.modPow(g, b, dhPrime);
    if (logger.isDebugEnabled()) {
        logger.debug('g_b(%s) = %s', gb.length, gb.toString('hex'));
    }
    // Create client DH inner data
    context.clientDHInnerData = new mtproto.type.Client_DH_inner_data({
        props: {
            nonce: context.resPQ.nonce,
            server_nonce: context.resPQ.server_nonce,
            retry_id: retryCount,
            g_b: gb
        }
    }).serialize();
    context.b = b;
    return context;
}
1116448
def _broadcast_and_set_attrs(self, local_dict):
        
        del local_dict['self']
        self.remove_axis = False
        max_length = 0
        for key in local_dict:
            try:
                length = len(local_dict[key])
                if length > max_length:
                    max_length = length

            except TypeError:
                pass

        if max_length == 0:
            self.remove_axis = True
            for key in local_dict:
                setattr(self, key, np.array([local_dict[key]]))

        # check for bad length arrays
        else:
            for key in local_dict:
                try:
                    if len(local_dict[key]) < max_length and len(local_dict[key]) > 1:
                        raise ValueError("Casting parameters not correct."
                                         + " Need all at a maximum shape and the rest being"
                                         + "len-1 arrays or scalars")
                except TypeError:
                    pass

            # broadcast arrays
            for key in local_dict:
                try:
                    if len(local_dict[key]) == max_length:
                        setattr(self, key, local_dict[key])
                    elif len(local_dict[key]) == 1:
                        setattr(self, key, np.full((max_length,), local_dict[key][0]))
                except TypeError:
                    setattr(self, key, np.full((max_length,), local_dict[key]))
        return
17740
def send_dir(self, local_path, remote_path, user='root'):
        
        self.enable_user(user)
        return self.ssh_pool.send_dir(user, local_path, remote_path)
76724
public ArrayList<Pair<String, Integer>> dhtNodes() {
        string_int_pair_vector v = p.get_dht_nodes();
        int size = (int) v.size();
        ArrayList<Pair<String, Integer>> l = new ArrayList<>();

        for (int i = 0; i < size; i++) {
            string_int_pair n = v.get(i);
            l.add(new Pair<>(n.getFirst(), n.getSecond()));
        }

        return l;
    }
909545
def _get_local_ip():
        
        return set([x[4][0] for x in socket.getaddrinfo(
            socket.gethostname(),
            80,
            socket.AF_INET
        )]).pop()
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
659693
function local(rootFolder) {
    // Construct name to remote id map
    const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE);
    const remoteSource = fs.readJsonSync(remote, 'utf8');
    const destination = constants.META_LOCAL;
    return pack(rootFolder, destination);
}
498070
static H2ONode self(InetAddress local) {
    assert H2O.H2O_PORT != 0;
    try {
      // Figure out which interface matches our IP address
      List<NetworkInterface> matchingIfs = new ArrayList();
      Enumeration<NetworkInterface> netIfs = NetworkInterface.getNetworkInterfaces();
      while( netIfs.hasMoreElements() ) {
        NetworkInterface netIf = netIfs.nextElement();
        Enumeration<InetAddress> addrs = netIf.getInetAddresses();
        while( addrs.hasMoreElements() ) {
          InetAddress addr = addrs.nextElement();
          if( addr.equals(local) ) {
            matchingIfs.add(netIf);
            break;
          }
        }
      }
      switch( matchingIfs.size() ) {
      case 0: H2O.CLOUD_MULTICAST_IF = null; break;
      case 1: H2O.CLOUD_MULTICAST_IF = matchingIfs.get(0); break;
      default:
        String msg = "Found multiple network interfaces for ip address " + local;
        for( NetworkInterface ni : matchingIfs ) {
          msg +="\n\t" + ni;
        }
        msg +="\nUsing " + matchingIfs.get(0) + " for UDP broadcast";
        Log.warn(msg);
        H2O.CLOUD_MULTICAST_IF = matchingIfs.get(0);
      }
    } catch( SocketException e ) {
      throw  Log.errRTExcept(e);
    }
    try {
      assert H2O.CLOUD_DGRAM == null;
      H2O.CLOUD_DGRAM = DatagramChannel.open();
    } catch( Exception e ) {
      throw  Log.errRTExcept(e);
    }
    return intern(new H2Okey(local,H2O.H2O_PORT));
  }
378213
function init(shard, socket) {  // {{{2
/**
 * Sends request to the master shard to establish a link.
 *
 * @param shard {Object} Slave shard
 * @param ws {Object} WebSocket
 *
 * @method constructor
 */

  if (shard.slaves) {
    if (socket._lid in shard.slaves) {
      return L.error(socket, O.log.todo('Duplicit lid', shard, socket._lid));
    }
  } else {
    shard.slaves = {};
  }

  this.shard = shard;
  shard.slaves[socket._lid] = this;

  return L.open(this, socket, {
    home: shard.isAtHome() || shard.masterState === shard.MASTER_STATE.HOME,
    homeTime: Date.now() + shard.homeTimeOffset,
  });
}
395452
def hub(self, port):
        '''  
        '''
        self._ip = "localhost"
        self._port = port 
        self.command = [self._conf["java_path"], "-jar", self._conf["jar_path"], "-port", str(port), "-role", "hub"]        
        return self
482616
def get():
        """"""
        return {
            attr: getattr(Conf, attr)
            for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith("__")
        }
1040153
def hvals(key, host=None, port=None, db=None, password=None):
    '''
    
    '''
    server = _connect(host, port, db, password)
    return server.hvals(key)
1308528
def deserialize(cls, value):
        
        parsed = json.loads(value)

        if "name" not in parsed:
            raise ValueError("No peer name.")
        if "ip" not in parsed:
            raise ValueError("No peer IP.")
        if "port" not in parsed:
            parsed["port"] = DEFAULT_PEER_PORT

        return cls(parsed["name"], parsed["ip"], parsed["port"])
1269831
def canonical_peer( self, peer ):
        
        their_host, their_port = url_to_host_port( peer )

        if their_host in ['127.0.0.1', '::1']:
            their_host = 'localhost'

        return "%s:%s" % (their_host, their_port)