Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?
327304
def _cts_or_stc(data):
        """"""

        # UDP/TCP
        if data['transport']:

            # TCP flags
            if data['transport']['type'] == 'TCP':
                flags = data['transport']['flags']

                # Syn/Ack or fin/ack is a server response
                if 'syn_ack' in flags or 'fin_ack' in flags:
                    return 'STC'

                # Syn or fin is a client response
                if 'syn' in flags or 'fin' in flags:
                    return 'CTS'

            # Source Port/Destination Port
            if 'sport' in data['transport']:
                sport = data['transport']['sport']
                dport = data['transport']['dport']

                # High port talking to low port
                if dport < 1024 and sport > dport:
                    return 'CTS'

                # Low port talking to high port
                if sport < 1024 and sport < dport:
                    return 'STC'

                # Wow... guessing
                return 'STC' if sport < dport else 'CTS'

        # Internal/External
        if 'src' in data['packet'] and 'dst' in data['packet']:
            src = net_utils.inet_to_str(data['packet']['src'])
            dst = net_utils.inet_to_str(data['packet']['dst'])

            # Internal talking to external?
            if net_utils.is_internal(src) and not net_utils.is_internal(dst):
                return 'CTS'

            # External talking to internal?
            if net_utils.is_internal(dst) and not net_utils.is_internal(src):
                return 'STC'

        # Okay we have no idea
        return 'CTS'
1334353
def tcp_traceflow(frame, *, data_link):
    """"""
    if 'TCP' in frame:
        ip = (frame['IPv4'] if 'IPv4' in frame else frame['IPv6']).info
        tcp = frame['TCP'].info
        data = dict(
            protocol=data_link,                     # data link type from global header
            index=frame.info.number,                # frame number
            frame=frame.info,                       # extracted frame info
            syn=tcp.flags.syn,                      # TCP synchronise (SYN) flag
            fin=tcp.flags.fin,                      # TCP finish (FIN) flag
            src=ip.src,                             # source IP
            dst=ip.dst,                             # destination IP
            srcport=tcp.srcport,                    # TCP source port
            dstport=tcp.dstport,                    # TCP destination port
            timestamp=frame.info.time_epoch,        # frame timestamp
        )
        return True, data
    return False, None
283384
def tcp_traceflow(packet, *, count=NotImplemented):
    """"""
    if 'TCP' in packet:
        ip = packet['IP'] if 'IP' in packet else packet['IPv6']
        tcp = packet['TCP']
        data = dict(
            protocol=LINKTYPE.get(packet.name.upper()),     # data link type from global header
            index=count,                                    # frame number
            frame=packet2dict(packet),                      # extracted packet
            syn=bool(tcp.flags.S),                          # TCP synchronise (SYN) flag
            fin=bool(tcp.flags.F),                          # TCP finish (FIN) flag
            src=ipaddress.ip_address(ip.src),               # source IP
            dst=ipaddress.ip_address(ip.dst),               # destination IP
            srcport=tcp.sport,                              # TCP source port
            dstport=tcp.dport,                              # TCP destination port
            timestamp=time.time(),                          # timestamp
        )
        return True, data
    return False, None
1042363
private boolean isClientBufferFull(final long now) {
        // check client buffer length when we've already sent some messages
        if (lastMessageTs > 0) {
            // duration the stream is playing / playback duration
            final long delta = now - playbackStart;
            // buffer size as requested by the client
            final long buffer = subscriberStream.getClientBufferDuration();
            // expected amount of data present in client buffer
            final long buffered = lastMessageTs - delta;
            log.trace("isClientBufferFull: timestamp {} delta {} buffered {} buffer duration {}", new Object[] { lastMessageTs, delta, buffered, buffer });
            // fix for SN-122, this sends double the size of the client buffer
            if (buffer > 0 && buffered > (buffer * 2)) {
                // client is likely to have enough data in the buffer
                return true;
            }
        }
        return false;
    }
776022
@Override
    public TTransport connect(TTransport transport, String serverHost, String asUser) throws TTransportException {
        int maxBufferSize = type.getMaxBufferSize(storm_conf);
        // create a framed transport
        TTransport conn = new TFramedTransport(transport, maxBufferSize);

        // connect
        conn.open();
        LOG.debug("Simple client transport has been established");

        return conn;
    }
1178869
void data(boolean outFinished, int streamId, Buffer source, boolean flush) {
    Preconditions.checkNotNull(source, "source");

    OkHttpClientStream stream = transport.getStream(streamId);
    if (stream == null) {
      // This is possible for a stream that has received end-of-stream from server (but hasn't sent
      // end-of-stream), and was removed from the transport stream map.
      // In such case, we just throw away the data.
      return;
    }

    OutboundFlowState state = state(stream);
    int window = state.writableWindow();
    boolean framesAlreadyQueued = state.hasPendingData();
    int size = (int) source.size();

    if (!framesAlreadyQueued && window >= size) {
      // Window size is large enough to send entire data frame
      state.write(source, size, outFinished);
    } else {
      // send partial data
      if (!framesAlreadyQueued && window > 0) {
        state.write(source, window, false);
      }
      // Queue remaining data in the buffer
      state.enqueue(source, (int) source.size(), outFinished);
    }

    if (flush) {
      flush();
    }
  }
906181
def network_traffic_ports(instance):
    
    for key, obj in instance['objects'].items():
        if ('type' in obj and obj['type'] == 'network-traffic' and
                ('src_port' not in obj or 'dst_port' not in obj)):
            yield JSONError("The Network Traffic object '%s' should contain "
                            "both the 'src_port' and 'dst_port' properties."
                            % key, instance['id'], 'network-traffic-ports')
1251983
function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) {
  let result = {
    iface,
    operstate,
    rx_bytes,
    rx_dropped,
    rx_errors,
    tx_bytes,
    tx_dropped,
    tx_errors,
    rx_sec: -1,
    tx_sec: -1,
    ms: 0
  };

  if (_network[iface] && _network[iface].ms) {
    result.ms = Date.now() - _network[iface].ms;
    result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0;
    result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0;
    _network[iface].rx_bytes = rx_bytes;
    _network[iface].tx_bytes = tx_bytes;
    _network[iface].rx_sec = result.rx_sec;
    _network[iface].tx_sec = result.tx_sec;
    _network[iface].ms = Date.now();
    _network[iface].last_ms = result.ms;
    _network[iface].operstate = operstate;
  } else {
    if (!_network[iface]) _network[iface] = {};
    _network[iface].rx_bytes = rx_bytes;
    _network[iface].tx_bytes = tx_bytes;
    _network[iface].rx_sec = -1;
    _network[iface].tx_sec = -1;
    _network[iface].ms = Date.now();
    _network[iface].last_ms = 0;
    _network[iface].operstate = operstate;
  }
  return result;
}
629137
function Client(transport) {
	MCS.call(this, transport, DomainMCSPDU.SEND_DATA_INDICATION, DomainMCSPDU.SEND_DATA_REQUEST);
	
	// channel context automata
	this.channelsConnected = 0;
	
	// init gcc information
	this.clientCoreData = gcc.clientCoreData();
	this.clientNetworkData = gcc.clientNetworkData(new type.Component([]));
	this.clientSecurityData = gcc.clientSecurityData();
	
	// must be readed from protocol
	this.serverCoreData = null;
	this.serverSecurityData = null;
	this.serverNetworkData = null;
	
	var self = this;
	this.transport.on('connect', function(s) {
		self.connect(s);
	});
}
45809
private static boolean cs_vcount(Dcs A, Dcss S) {
        int i, k, p, pa, n = A.n, m = A.m, Ap[] = A.p, Ai[] = A.i, next[], head[], tail[], nque[], pinv[], leftmost[], w[], parent[] = S.parent;
        S.pinv = pinv = new int[m + n]; /* allocate pinv, */
        S.leftmost = leftmost = new int[m]; /* and leftmost */
        w = new int[m + 3 * n]; /* get workspace */
        next = w;
        head = w;
        int head_offset = m;
        tail = w;
        int tail_offset = m + n;
        nque = w;
        int nque_offset = m + 2 * n;
        for (k = 0; k < n; k++)
            head[head_offset + k] = -1; /* queue k is empty */
        for (k = 0; k < n; k++)
            tail[tail_offset + k] = -1;
        for (k = 0; k < n; k++)
            nque[nque_offset + k] = 0;
        for (i = 0; i < m; i++)
            leftmost[i] = -1;
        for (k = n - 1; k >= 0; k--) {
            for (p = Ap[k]; p < Ap[k + 1]; p++) {
                leftmost[Ai[p]] = k; /* leftmost[i] = min(find(A(i,:)))*/
            }
        }
        for (i = m - 1; i >= 0; i--) /* scan rows in reverse order */
        {
            pinv[i] = -1; /* row i is not yet ordered */
            k = leftmost[i];
            if (k == -1)
                continue; /* row i is empty */
            if (nque[nque_offset + k]++ == 0)
                tail[tail_offset + k] = i; /* first row in queue k */
            next[i] = head[head_offset + k]; /* put i at head of queue k */
            head[head_offset + k] = i;
        }
        S.lnz = 0;
        S.m2 = m;
        for (k = 0; k < n; k++) /* find row permutation and nnz(V)*/
        {
            i = head[head_offset + k]; /* remove row i from queue k */
            S.lnz++; /* count V(k,k) as nonzero */
            if (i < 0)
                i = S.m2++; /* add a fictitious row */
            pinv[i] = k; /* associate row i with V(:,k) */
            if (--nque[nque_offset + k] <= 0)
                continue; /* skip if V(k+1:m,k) is empty */
            S.lnz += nque[nque_offset + k]; /* nque [nque_offset+k] is nnz (V(k+1:m,k)) */
            if ((pa = parent[k]) != -1) /* move all rows to parent of k */
            {
                if (nque[nque_offset + pa] == 0)
                    tail[tail_offset + pa] = tail[tail_offset + k];
                next[tail[tail_offset + k]] = head[head_offset + pa];
                head[head_offset + pa] = next[i];
                nque[nque_offset + pa] += nque[nque_offset + k];
            }
        }
        for (i = 0; i < m; i++)
            if (pinv[i] < 0)
                pinv[i] = k++;
        w = null;
        return (true);
    }
661665
def ReadClientStats(self, client_id,
                      min_timestamp,
                      max_timestamp
                     ):
    """"""
    results = []
    for timestamp, stats in iteritems(self.client_stats[client_id]):
      if min_timestamp <= timestamp <= max_timestamp:
        results.append(stats)
    return results
417730
private void printRegionClientStats(final TSDB tsdb, final HttpQuery query) {
    final List<RegionClientStats> region_stats = tsdb.getClient().regionStats();
    final List<Map<String, Object>> stats = 
        new ArrayList<Map<String, Object>>(region_stats.size());
    for (final RegionClientStats rcs : region_stats) {
      final Map<String, Object> stat_map = new HashMap<String, Object>(8);
      stat_map.put("rpcsSent", rcs.rpcsSent());
      stat_map.put("rpcsInFlight", rcs.inflightRPCs());
      stat_map.put("pendingRPCs", rcs.pendingRPCs());
      stat_map.put("pendingBatchedRPCs", rcs.pendingBatchedRPCs());
      stat_map.put("dead", rcs.isDead());
      stat_map.put("rpcid", rcs.rpcID());
      stat_map.put("endpoint", rcs.remoteEndpoint());
      stat_map.put("rpcsTimedout", rcs.rpcsTimedout());
      stat_map.put("rpcResponsesTimedout", rcs.rpcResponsesTimedout());
      stat_map.put("rpcResponsesUnknown", rcs.rpcResponsesUnknown());
      stat_map.put("inflightBreached", rcs.inflightBreached());
      stat_map.put("pendingBreached", rcs.pendingBreached());
      stat_map.put("writesBlocked", rcs.writesBlocked());
      
      stats.add(stat_map);
    }
    query.sendReply(query.serializer().formatRegionStatsV1(stats));
  }
1141577
def todict(self):
        '''
        
        '''
        return {
            'Source port': self.srcport,
            'Destination port': self.destport,
            'Protocol': self.protocol,
            'Destination address': self.destaddr}
669945
function (msgtype, event) {
	
		// we only forward for non-SR user-defined events at lobby
		if (SR.Settings.SERVER_INFO.type !== 'lobby' || msgtype.startsWith('SR'))
			return false;
		
		// check if we're lobby and same-name app servers are available
		var list = SR.AppConn.queryAppServers();
		LOG.sys('check forward for: ' + msgtype + ' app server size: ' + Object.keys(list).length, l_name);
	
		var minload_id = undefined;
		var minload = 10000;
		
		for (var id in list) {
			var info = list[id];
			if (info.type === 'app' && info.name === SR.Settings.SERVER_INFO.name) {
				LOG.warn('found forward target [' + id + '] loading: ' + info.usercount, l_name);
				if (info.usercount < minload) {
					minload_id = id;
					minload = info.usercount;
				}
			}
		}
			
		// an app server with minimal loading is available, relay the event
		if (minload_id) {
			SR.RPC.relayEvent(minload_id, msgtype, event);	
			return true;
		}
		
		// no need to forward, local execution
		return false;
	}
762209
def _node_info(conn):
    '''
    
    '''
    raw = conn.getInfo()
    info = {'cpucores': raw[6],
            'cpumhz': raw[3],
            'cpumodel': six.text_type(raw[0]),
            'cpus': raw[2],
            'cputhreads': raw[7],
            'numanodes': raw[4],
            'phymemory': raw[1],
            'sockets': raw[5]}
    return info
779396
function chRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    let con;
    if (!client.chParam) {
        client.chParam = {};
    }
    if (client.chParam[serverType]) {
        con = client.chParam[serverType].consistentHash;
    } else {
        client.opts.station = client._station;
        con = new ConsistentHash(servers, client.opts);
    }
    const hashFieldIndex = client.opts.hashFieldIndex;
    const field = msg.args[hashFieldIndex] || JSON.stringify(msg);
    utils.invokeCallback(cb, null, con.getNode(field));
    client.chParam[serverType] = { consistentHash: con };
}
1342404
function rrRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    let index;
    if (!client.rrParam) {
        client.rrParam = {};
    }
    if (client.rrParam[serverType]) {
        index = client.rrParam[serverType];
    } else {
        index = 0;
    }
    utils.invokeCallback(cb, null, servers[index % servers.length]);
    if (index++ === Number.MAX_VALUE) {
        index = 0;
    }
    client.rrParam[serverType] = index;
}