Report the current statistics of sampling rules and
        get back the new assgiend quota/TTL froom the X-Ray service.
        The call is proxied and signed via X-Ray Daemon.
15452
def fetch_sampling_target(self, rules):
        
        now = int(time.time())
        report_docs = self._generate_reporting_docs(rules, now)
        resp = self._xray_client.get_sampling_targets(
            SamplingStatisticsDocuments=report_docs
        )
        new_docs = resp['SamplingTargetDocuments']

        targets_mapping = {}
        for doc in new_docs:
            TTL = self._dt_to_epoch(doc['ReservoirQuotaTTL']) if doc.get('ReservoirQuotaTTL', None) else None
            target = {
                'rate': doc['FixedRate'],
                'quota': doc.get('ReservoirQuota', None),
                'TTL': TTL,
                'interval': doc.get('Interval', None),
            }
            targets_mapping[doc['RuleName']] = target

        return targets_mapping, self._dt_to_epoch(resp['LastRuleModification'])
1008234
function SamplingRule(name, priority, rate, reservoirSize,
                      host, httpMethod, urlPath, serviceName, serviceType) {
  this.init(name, priority, rate, reservoirSize,
            host, httpMethod, urlPath, serviceName, serviceType);
}
970809
def sample_stats_to_xarray(self):
        """"""
        data = self.sample_stats
        if not isinstance(data, dict):
            raise TypeError("DictConverter.sample_stats is not a dictionary")

        return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims)
454100
def xray_requests_send(wrapped, instance, args, kwargs):
    """"""
    return generic_xray_wrapper(
        wrapped, instance, args, kwargs,
        name='requests',
        namespace='remote',
        metadata_extractor=extract_http_metadata,
    )
799572
def guard_sample(analysis_request):
    
    if analysis_request.getDateSampled() and analysis_request.getSampler():
        return True

    current_user = api.get_current_user()
    return "Sampler" in current_user.getRolesInContext(analysis_request)
899092
def updateData(self, signal, fs):
        
        # use a separate thread to calculate spectrogram so UI doesn't lag
        t = threading.Thread(target=_doSpectrogram, args=(self.spec_done, (fs, signal),), kwargs=self.specgramArgs)
        t.start()
763641
def get_samples(self, sample_count):
        
        if self.amplitude.value <= 0:
            return None
        # Build samples by rolling the period cache through the buffer
        rolled_array = numpy.roll(self.wave_cache,
                                  -1 * self.last_played_sample)
        # Append remaining partial period
        full_count, remainder = divmod(sample_count, self.cache_length)
        final_subarray = rolled_array[:int(remainder)]
        return_array = numpy.concatenate((numpy.tile(rolled_array, full_count),
                                          final_subarray))
        # Keep track of where we left off to prevent popping between chunks
        self.last_played_sample = int(((self.last_played_sample + remainder) %
                                       self.cache_length))
        # Multiply output by amplitude
        return return_array * (self.amplitude.value *
                               self.amplitude_multiplier)
1031065
def monitor(i):
    """"""
    count = 0
    for x in i:
        count+=1
        if count % 10000 == 0:
            logger.info("%d records so far, current record is %s",
                count, x["idx"])
        yield x
1133815
def borrow_or_take(now, borrowable)
      @lock.synchronize do
        reset_new_sec(now)
        # Don't borrow if the quota is available and fresh.
        if quota_fresh?(now)
          return SamplingDecision::NOT_SAMPLE if @taken_this_sec >= @quota
          @taken_this_sec += 1
          return SamplingDecision::TAKE
        end

        # Otherwise try to borrow if the quota is not present or expired.
        if borrowable
          return SamplingDecision::NOT_SAMPLE if @borrowed_this_sec >= 1
          @borrowed_this_sec += 1
          return SamplingDecision::BORROW
        end

        # Cannot sample if quota expires and cannot borrow
        SamplingDecision::NOT_SAMPLE
      end
    end
159364
def report_onlysize(bytes_so_far, total_size, speed, eta):
    '''
    
    '''
    percent = int(bytes_so_far * 100 / total_size)
    current = approximate_size(bytes_so_far).center(10)
    total = approximate_size(total_size).center(10)
    sys.stdout.write('D: {0}% -{1}/{2}'.format(percent, current, total) + "eta {0}".format(eta))
    sys.stdout.write("\r")
    sys.stdout.flush()
674948
def gauge(self, stat, value, sample_rate=1):
        
        stats = {stat: "%f|g" % value}
        self.send(stats, sample_rate)
822121
void sampleReceived(SolverAggregatorInterface aggregator,
			SampleMessage sample) {
		if (!this.sampleQueue.offer(sample) && this.warnBufferFull) {
			log.warn("Unable to insert a sample due to a full buffer.");
		}
	}
88754
void addSample(StopwatchSample sample) {
		total += sample.getTotal();
		counter += sample.getCounter();

		if (min > sample.getMin()) {
			min = sample.getMin();
			minTimestamp = sample.getMinTimestamp();
		}

		if (max < sample.getMax()) {
			max = sample.getMax();
			maxTimestamp = sample.getMaxTimestamp();
		}

		active += sample.getActive();

		if (maxActive < sample.getMaxActive()) {
			maxActive = sample.getMaxActive();
			maxActiveTimestamp = sample.getMaxActiveTimestamp();
		}
	}
430614
def report_bar(bytes_so_far, total_size, speed, eta):
    '''
    
    '''
    percent = int(bytes_so_far * 100 / total_size)
    current = approximate_size(bytes_so_far).center(9)
    total = approximate_size(total_size).center(9)
    shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
    sys.stdout.write(
        " {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}".format(str(percent).center(4),
                                                      '=' * (shaded - 1),
                                                      '>',
                                                      ' ' * (AVAIL_WIDTH - shaded),
                                                      current,
                                                      total,
                                                      (approximate_size(speed) + '/s').center(11),
                                                      eta.center(10)))
    sys.stdout.write("\r")
    sys.stdout.flush()
578125
def set_rule_name(self, rule_name):
        
        if not self.aws.get('xray', None):
            self.aws['xray'] = {}
        self.aws['xray']['sampling_rule_name'] = rule_name
1107342
public final void sample()
  {
    synchronized (_lock) {
      long count = _totalCount.get();
      long lastCount = _lastAvgTotalCount;
      _lastAvgTotalCount = count;

      long sum = _sum.get();
      double lastSum = _lastAvgSum;
      _lastAvgSum = sum;

      if (count == lastCount) {
        _avg =  0;
      }
      else {
        _avg = _scale * (sum - lastSum) / (double) (count - lastCount);
      }
    }
  }
495860
async def middleware(request, handler):
    
    # Create X-Ray headers
    xray_header = construct_xray_header(request.headers)
    # Get name of service or generate a dynamic one from host
    name = calculate_segment_name(request.headers['host'].split(':', 1)[0], xray_recorder)

    sampling_req = {
        'host': request.headers['host'],
        'method': request.method,
        'path': request.path,
        'service': name,
    }

    sampling_decision = calculate_sampling_decision(
        trace_header=xray_header,
        recorder=xray_recorder,
        sampling_req=sampling_req,
    )

    # Start a segment
    segment = xray_recorder.begin_segment(
        name=name,
        traceid=xray_header.root,
        parent_id=xray_header.parent,
        sampling=sampling_decision,
    )

    segment.save_origin_trace_header(xray_header)
    # Store request metadata in the current segment
    segment.put_http_meta(http.URL, str(request.url))
    segment.put_http_meta(http.METHOD, request.method)

    if 'User-Agent' in request.headers:
        segment.put_http_meta(http.USER_AGENT, request.headers['User-Agent'])

    if 'X-Forwarded-For' in request.headers:
        segment.put_http_meta(http.CLIENT_IP, request.headers['X-Forwarded-For'])
        segment.put_http_meta(http.X_FORWARDED_FOR, True)
    elif 'remote_addr' in request.headers:
        segment.put_http_meta(http.CLIENT_IP, request.headers['remote_addr'])
    else:
        segment.put_http_meta(http.CLIENT_IP, request.remote)

    try:
        # Call next middleware or request handler
        response = await handler(request)
    except HTTPException as exc:
        # Non 2XX responses are raised as HTTPExceptions
        response = exc
        raise
    except Exception as err:
        # Store exception information including the stacktrace to the segment
        response = None
        segment.put_http_meta(http.STATUS, 500)
        stack = stacktrace.get_stacktrace(limit=xray_recorder.max_trace_back)
        segment.add_exception(err, stack)
        raise
    finally:
        if response is not None:
            segment.put_http_meta(http.STATUS, response.status)
            if 'Content-Length' in response.headers:
                length = int(response.headers['Content-Length'])
                segment.put_http_meta(http.CONTENT_LENGTH, length)

            header_str = prepare_response_header(xray_header, segment)
            response.headers[http.XRAY_HEADER] = header_str

        xray_recorder.end_segment()

    return response