Helper to publish stats to statsD client
485810
private void exportToStatsD(List<Stat> stats) {
        // group stats by kafka group
        for (Stat stat : stats) {
            @SuppressWarnings("unchecked")
            Map<String, String> tags = (Map<String, String>) stat.get(Stat.STAT_KEYS.TAGS.getName());
            long value = Long.parseLong((String) stat.get(Stat.STAT_KEYS.VALUE.getName()));
            if (mConfig.getStatsdDogstatdsTagsEnabled()) {
                String metricName = (String) stat.get(Stat.STAT_KEYS.METRIC.getName());
                String[] tagArray = new String[tags.size()];
                int i = 0;
                for (Map.Entry<String, String> e : tags.entrySet()) {
                    tagArray[i++] = e.getKey() + ':' + e.getValue();
                }
                mStatsDClient.recordGaugeValue(metricName, value, tagArray);
            } else {
                StringBuilder builder = new StringBuilder();
                if (mConfig.getStatsDPrefixWithConsumerGroup()) {
                    builder.append(tags.get(Stat.STAT_KEYS.GROUP.getName()))
                            .append(PERIOD);
                }
                String metricName = builder
                        .append((String) stat.get(Stat.STAT_KEYS.METRIC.getName()))
                        .append(PERIOD)
                        .append(tags.get(Stat.STAT_KEYS.TOPIC.getName()))
                        .append(PERIOD)
                        .append(tags.get(Stat.STAT_KEYS.PARTITION.getName()))
                        .toString();
                mStatsDClient.recordGaugeValue(metricName, value);
            }
        }
    }
959656
def get_counter(self, name=None):
        '''
        '''
        return self.get_client(name=name, class_=statsd.Counter)
22430
def update(self, stats):
        """"""
        # Get the stats
        all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export())

        # Init data with timestamp (issue#708)
        if self.first_line:
            csv_header = ['timestamp']
        csv_data = [time.strftime('%Y-%m-%d %H:%M:%S')]

        # Loop over plugins to export
        for plugin in self.plugins_to_export():
            if isinstance(all_stats[plugin], list):
                for stat in all_stats[plugin]:
                    # First line: header
                    if self.first_line:
                        csv_header += ('{}_{}_{}'.format(
                            plugin, self.get_item_key(stat), item) for item in stat)
                    # Others lines: stats
                    csv_data += itervalues(stat)
            elif isinstance(all_stats[plugin], dict):
                # First line: header
                if self.first_line:
                    fieldnames = iterkeys(all_stats[plugin])
                    csv_header += ('{}_{}'.format(plugin, fieldname)
                                   for fieldname in fieldnames)
                # Others lines: stats
                csv_data += itervalues(all_stats[plugin])

        # Export to CSV
        if self.first_line:
            self.writer.writerow(csv_header)
            self.first_line = False
        self.writer.writerow(csv_data)
        self.csv_file.flush()
784392
def _post_stats(self, stats):
        '''
        
        '''
        end_time = time.time()
        if end_time - self.stat_clock > self.opts['master_stats_event_iter']:
            # Fire the event with the stats and wipe the tracker
            self.aes_funcs.event.fire_event({'time': end_time - self.stat_clock, 'worker': self.name, 'stats': stats}, tagify(self.name, 'stats'))
            self.stats = collections.defaultdict(lambda: {'mean': 0, 'latency': 0, 'runs': 0})
            self.stat_clock = end_time
115767
def WriteClientStats(self,
                       client_id,
                       stats,
                       cursor=None):
    """"""

    try:
      cursor.execute(
          """
          INSERT INTO client_stats (client_id, payload, timestamp)
          VALUES (%s, %s, FROM_UNIXTIME(%s))
          ON DUPLICATE KEY UPDATE payload=VALUES(payload)
          """, [
              db_utils.ClientIDToInt(client_id),
              stats.SerializeToString(),
              mysql_utils.RDFDatetimeToTimestamp(rdfvalue.RDFDatetime.Now())
          ])
    except MySQLdb.IntegrityError as e:
      if e.args[0] == mysql_error_constants.NO_REFERENCED_ROW_2:
        raise db.UnknownClientError(client_id, cause=e)
      else:
        raise
1288922
def stats(self, request):
        '''
        '''
        # scheme = 'wss' if request.is_secure else 'ws'
        # host = request.get('HTTP_HOST')
        # address = '%s://%s/stats' % (scheme, host)
        doc = HtmlDocument(title='Live server stats', media_path='/assets/')
        # docs.head.scripts
        return doc.http_response(request)
943280
def _publish_metrics(self, prev_keys, key, data, publishfn=None):
        """"""
        if key not in data:
            return
        value = data[key]
        keys = prev_keys + [key]
        if not publishfn:
            publishfn = self.publish
        if isinstance(value, dict):
            for new_key in value:
                self._publish_metrics(keys, new_key, value)
        elif isinstance(value, int) or isinstance(value, float):
            publishfn('.'.join(keys), value)
        elif isinstance(value, long):
            publishfn('.'.join(keys), float(value))
321582
def stats(self):
        
        response = self.requester.get(
            '/{endpoint}/{id}/stats',
            endpoint=self.endpoint, id=self.id
        )
        return response.json()
474797
def _print_stats(self, env, stats):
        

        def _format_time(mins):
            """ Generates formatted time string.
                """
            mins = int(mins)

            if mins < MINS_IN_HOUR:
                time_str = '0:{0:02}'.format(mins)
            else:
                hours = mins // MINS_IN_HOUR
                mins %= MINS_IN_HOUR

                if mins > 0:
                    time_str = '{0}:{1:02}'.format(hours, mins)
                else:
                    time_str = '{0}'.format(hours)

            return time_str

        if not stats:
            env.io.write('No stats found.')
            return

        for date, tasks in stats:
            env.io.write('')
            total_mins = float(sum(v[1] for v in tasks))
            env.io.write('[ {0} ]'.format(date.strftime('%Y-%m-%d')))
            env.io.write('')

            for name, mins in tasks:
                # format time
                time_str = _format_time(mins)

                # generate stat line
                line = '   {0:>5}'.format(time_str)
                line += ' ({0:2.0f}%) - '.format(mins * 100.0 / total_mins)
                if len(name) > 55:
                    name = name[:55] + '...'
                line += name
                env.io.write(line)

            # generate total line
            env.io.write('_' * len(line))
            time_str = _format_time(total_mins)
            env.io.write('   {0:>5} (total)'.format(time_str))
            env.io.write('')
1337264
function updateStatistics() {
  raddecRate.textContent = Math.round(1000 * raddecCount /
                                      STATISTICS_INTERVAL_MILLISECONDS);
  numTransmitters.textContent = Object.keys(beaver.transmitters).length;
  raddecCount = 0;
}
849004
def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None):
    
    def error(msg):
      # Report aleady closed, so just print error.
      print('WARNING: Failed to upload stats to {}. due to {}'.format(stats_url, msg),
            file=sys.stderr)
      return False

    # TODO(benjy): The upload protocol currently requires separate top-level params, with JSON
    # values.  Probably better for there to be one top-level JSON value, namely json.dumps(stats).
    # But this will first require changing the upload receiver at every shop that uses this.
    params = {k: cls._json_dump_options(v) for (k, v) in stats.items()}
    cookies = Cookies.global_instance()
    auth_provider = auth_provider or '<provider>'

    # We can't simply let requests handle redirects, as we only allow them for specific codes:
    # 307 and 308 indicate that the redirected request must use the same method, POST in this case.
    # So they indicate a true redirect of the POST itself, and we allow them.
    # The other redirect codes either must, or in practice do, cause the user agent to switch the
    # method to GET. So when they are encountered on a POST, it indicates an auth problem (a
    # redirection to a login page).
    def do_post(url, num_redirects_allowed):
      if num_redirects_allowed < 0:
        return error('too many redirects.')
      r = requests.post(url, data=params, timeout=timeout,
                        cookies=cookies.get_cookie_jar(), allow_redirects=False)
      if r.status_code in {307, 308}:
        return do_post(r.headers['location'], num_redirects_allowed - 1)
      elif r.status_code != 200:
        error('HTTP error code: {}. Reason: {}.'.format(r.status_code, r.reason))
        if 300 <= r.status_code < 400 or r.status_code == 401:
          print('Use `path/to/pants login --to={}` to authenticate against the stats '
                'upload service.'.format(auth_provider), file=sys.stderr)
        return False
      return True

    try:
      return do_post(stats_url, num_redirects_allowed=6)
    except Exception as e:  # Broad catch - we don't want to fail the build over upload errors.
      return error('Error: {}'.format(e))
965326
def render_stats(stats, sort, format):
    
    output = StdoutWrapper()
    if hasattr(stats, "stream"):
        stats.stream = output.stream
    stats.sort_stats(*sort)
    getattr(stats, format)()
    return output.stream
871089
def summary_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
        
        schema = SummaryStatsSchema()
        resp = self.service.get(self.base+str(id)+'/', params={'stats': 'summary'})
        return self.service.decode(schema, resp)
1189678
def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
        ''''''
        time_length = datetime.timedelta(
            seconds=int(stats.stop_time - stats.start_time)
        )
        file_size = wpull.string.format_size(stats.size)

        if stats.bandwidth_meter.num_samples:
            speed = stats.bandwidth_meter.speed()

            if human_format_speed:
                speed_size_str = wpull.string.format_size(speed)
            else:
                speed_size_str = '{:.1f} b'.format(speed * 8)
        else:
            speed_size_str = _('-- B')

        _logger.info(_('FINISHED.'))
        _logger.info(__(
            _(
                'Duration: {preformatted_timedelta}. '
                'Speed: {preformatted_speed_size}/s.'
            ),
            preformatted_timedelta=time_length,
            preformatted_speed_size=speed_size_str,
        ))
        _logger.info(__(
            gettext.ngettext(
                'Downloaded: {num_files} file, {preformatted_file_size}.',
                'Downloaded: {num_files} files, {preformatted_file_size}.',
                stats.files
            ),
            num_files=stats.files,
            preformatted_file_size=file_size
        ))

        if stats.is_quota_exceeded:
            _logger.info(_('Download quota exceeded.'))
258596
def stats_for(self, dt):
        
        # TODO - this would be nicer if we formatted the stats
        if not isinstance(dt, datetime):
            raise TypeError('stats_for requires a datetime object!')
        return self._client.get('{}/stats/'.format(dt.strftime('%Y/%m')))
1162686
def stats(filename,*args)
    fn = OptArg.quote(filename)
    opt = OptArg.parse(*args)
    puts send_cmd "stats #{fn} #{opt}"
  end
1192369
def _send(self, subname, value):
        '''
        '''
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})