Create project metrics for financial indicator
    Updates them if already exists
491145
def load_project_metrics():
    
    all_metrics = FinancialIndicator.METRICS
    for key in all_metrics:
        df = getattr(data, key)
        pronac = 'PRONAC'
        if key == 'planilha_captacao':
            pronac = 'Pronac'
        pronacs = df[pronac].unique().tolist()
        create_finance_metrics(all_metrics[key], pronacs)
681633
function(time, metrics) {
	var metricTypes = ['gauges', 'timer_data', 'timers', 'counters', 'sets'];

	metricTypes.forEach(function(type, i){
		var obj;

		for (var key in metrics[type]) {
			obj = aggregate[type](time, key, metrics[type][key]);

			insert(obj.db, obj.col, obj.data, function(err){
				if (err) console.log(err);
			});
		};
	});
}
31116
protected void updateMetricCounters(String metricName, Map<String, Integer> metricNameCounters) {
        if (metricNameCounters.containsKey(metricName)) {
            metricNameCounters.put(metricName, metricNameCounters.get(metricName) + 1);
        } else {
            metricNameCounters.put(metricName, 1);
        }
    }
614544
def dashboard(request):
    """"""
    sources = (models.Source.objects.all().prefetch_related('metric_set')
                                          .order_by('name'))
    metrics = SortedDict([(src, src.metric_set.all()) for src in sources])
    no_source_metrics = models.Metric.objects.filter(source__isnull=True)
    if no_source_metrics:
        metrics[''] = no_source_metrics

    if request.META.get('HTTP_X_PJAX', False):
        parent_template = 'pjax.html'
    else:
        parent_template = 'base.html'
    return render(request, 'metrics/dashboard.html', {
        'source_metrics': metrics,
        'parent_template': parent_template
    })
1118849
def update_project(config, task_presenter, results,
                   long_description, tutorial, watch): # pragma: no cover
    """"""
    if watch:
        res = _update_project_watch(config, task_presenter, results,
                                    long_description, tutorial)
    else:
        res = _update_project(config, task_presenter, results,
                              long_description, tutorial)
        click.echo(res)
609905
def insert_metric_changes(db, metrics, metric_mapping, commit):
    
    values = [
        [commit.sha, metric_mapping[metric.name], metric.value]
        for metric in metrics
        if metric.value != 0
    ]
    db.executemany(
        'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)',
        values,
    )
1238050
def process_build_metrics(context, build_processors):
    """"""
    build_metrics = OrderedDict()

    # reset all processors
    for p in build_processors:
        p.reset()

    # collect metrics from all processors
    for p in build_processors:
        build_metrics.update(p.build_metrics)

    return build_metrics
279280
public function createMetricAction()
    {
        $metricData = Binput::get('metric');

        try {
            execute(new CreateMetricCommand(
                $metricData['name'],
                $metricData['suffix'],
                $metricData['description'],
                $metricData['default_value'],
                $metricData['calc_type'],
                $metricData['display_chart'],
                $metricData['places'],
                $metricData['default_view'],
                $metricData['threshold'],
                0, // Default order
                $metricData['visible']
            ));
        } catch (ValidationException $e) {
            return cachet_redirect('dashboard.metrics.create')
                ->withInput(Binput::all())
                ->withTitle(sprintf('%s %s', trans('dashboard.notifications.whoops'), trans('dashboard.metrics.add.failure')))
                ->withErrors($e->getMessageBag());
        }

        return cachet_redirect('dashboard.metrics')
            ->withSuccess(sprintf('%s %s', trans('dashboard.notifications.awesome'), trans('dashboard.metrics.add.success')));
    }
324307
def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw):
        
        if not _type:
            raise ValueError('Metric type should be defined.')

        if _type in available_metrics:
            metric_obj = available_metrics[_type](None, self.routing_queue)  # create metric object
            metric_info = {'type': _type,
                           'source': source,
                           'name': name,
                           'hostname': hostname,
                           'group': group}
            if kw is not None:
                metric_info.update(kw)
            metric_meta = pd.DataFrame({metric_obj.local_id: metric_info}).T  # create metric meta
            self.metrics_meta = self.metrics_meta.append(metric_meta)  # register metric meta
            self.metrics[metric_obj.local_id] = metric_obj  # register metric object

            # find subscribers for this metric
            this_metric_subscribers = self.__reversed_filter(self.subscribers, metric_info)
            if this_metric_subscribers.empty:
                logger.debug('subscriber for metric %s not found', metric_obj.local_id)
            else:
                logger.debug('Found subscribers for this metric, subscribing...: %s', this_metric_subscribers)
                # attach this metric id to discovered subscribers and select id <-> callbacks
                this_metric_subscribers['id'] = metric_obj.local_id
                found_callbacks = this_metric_subscribers[['id', 'callback']].set_index('id')
                # add this metric callbacks to DataManager's callbacks
                self.callbacks = self.callbacks.append(found_callbacks)
            return metric_obj
        else:
            raise NotImplementedError('Unknown metric type: %s' % _type)
813752
private void addMetric(
      List<Metric> metrics,
      String name,
      TagList tags,
      Object value) {
    long now = System.currentTimeMillis();
    if (onlyNumericMetrics) {
      value = asNumber(value);
    }
    if (value != null) {

      TagList newTags = counters.matches(MonitorConfig.builder(name).withTags(tags).build())
          ? getTagListWithAdditionalTag(tags, DataSourceType.COUNTER)
          : getTagListWithAdditionalTag(tags, DataSourceType.GAUGE);
      Metric m = new Metric(name, newTags, now, value);
      metrics.add(m);
    }
  }
587976
private ListenableFuture<TaskStatus> attachCallbacks(final Task task, final ListenableFuture<TaskStatus> statusFuture)
  {
    final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder();
    IndexTaskUtils.setTaskDimensions(metricBuilder, task);

    Futures.addCallback(
        statusFuture,
        new FutureCallback<TaskStatus>()
        {
          @Override
          public void onSuccess(final TaskStatus status)
          {
            log.info("Received %s status for task: %s", status.getStatusCode(), status.getId());
            handleStatus(status);
          }

          @Override
          public void onFailure(final Throwable t)
          {
            log.makeAlert(t, "Failed to run task")
               .addData("task", task.getId())
               .addData("type", task.getType())
               .addData("dataSource", task.getDataSource())
               .emit();
            handleStatus(TaskStatus.failure(task.getId()));
          }

          private void handleStatus(final TaskStatus status)
          {
            try {
              // If we're not supposed to be running anymore, don't do anything. Somewhat racey if the flag gets set
              // after we check and before we commit the database transaction, but better than nothing.
              if (!active) {
                log.info("Abandoning task due to shutdown: %s", task.getId());
                return;
              }

              notifyStatus(task, status, "notified status change from task");

              // Emit event and log, if the task is done
              if (status.isComplete()) {
                IndexTaskUtils.setTaskStatusDimensions(metricBuilder, status);
                emitter.emit(metricBuilder.build("task/run/time", status.getDuration()));

                log.info(
                    "Task %s: %s (%d run duration)",
                    status.getStatusCode(),
                    task,
                    status.getDuration()
                );

                if (status.isSuccess()) {
                  Counters.incrementAndGetLong(totalSuccessfulTaskCount, task.getDataSource());
                } else {
                  Counters.incrementAndGetLong(totalFailedTaskCount, task.getDataSource());
                }
              }
            }
            catch (Exception e) {
              log.makeAlert(e, "Failed to handle task status")
                 .addData("task", task.getId())
                 .addData("statusCode", status.getStatusCode())
                 .emit();
            }
          }
        }
    );
    return statusFuture;
  }
118259
def create_new_project(self):
        """"""
        self.switch_to_plugin()
        active_project = self.current_active_project
        dlg = ProjectDialog(self)
        dlg.sig_project_creation_requested.connect(self._create_project)
        dlg.sig_project_creation_requested.connect(self.sig_project_created)
        if dlg.exec_():
            if (active_project is None
                    and self.get_option('visible_if_project_open')):
                self.show_explorer()
            self.sig_pythonpath_changed.emit()
            self.restart_consoles()
904435
def _set_or_sum_metric(self, metrics, metric_path, value):
        """"""
        if metric_path in metrics:
            metrics[metric_path] += value
        else:
            metrics[metric_path] = value
213742
def create_tpu_eval_metrics_fn(problem, model_hparams):
  """"""

  metric_fns = []
  eval_metrics = problem.eval_metric_fns(model_hparams)

  tm = _create_target_modality(problem.get_hparams(model_hparams).modality)
  if isinstance(tm, dict):
    for k, v in six.iteritems(tm):
      weights_fn = modalities.get_weights_fn(v)

      def make_metric_fn(metric_fn):
        def wrapped_metric_fn(logits, labels, features, weights_fn=weights_fn):
          kwargs = {}
          args, _, keywords, _ = inspect.getargspec(metric_fn)
          if ("features" in args) or keywords:
            kwargs["features"] = features
          num, den = metric_fn(logits, labels, weights_fn=weights_fn, **kwargs)
          return tf.metrics.mean(num, den)

        return wrapped_metric_fn

      for metric, metric_fn in six.iteritems(eval_metrics):
        if metric in TPU_METRIC_BLACKLIST:
          log_warn("Skipping eval metric %s in TPU_METRIC_BLACKLIST", metric)
          continue
        name = "%s/metrics-%s/%s" % (k, problem.name, metric)
        metric_fns.append((name, make_metric_fn(metric_fn)))
  else:
    weights_fn = modalities.get_weights_fn(tm)

    def make_metric_fn(metric_fn):
      def wrapped_metric_fn(logits, labels, features):
        kwargs = {}
        args, _, keywords, _ = inspect.getargspec(metric_fn)
        if ("features" in args) or keywords:
          kwargs["features"] = features
        num, den = metric_fn(logits, labels, weights_fn=weights_fn, **kwargs)
        return tf.metrics.mean(num, den)

      return wrapped_metric_fn

    for metric, metric_fn in six.iteritems(eval_metrics):
      if metric in TPU_METRIC_BLACKLIST:
        log_warn("Skipping eval metric %s in TPU_METRIC_BLACKLIST", metric)
        continue
      name = "metrics-%s/%s" % (problem.name, metric)
      metric_fns.append((name, make_metric_fn(metric_fn)))

  def all_metrics_fn(**kwargs):
    """Construct metrics dictionary."""

    original_kwargs = _unflatten_dict(kwargs, prefixes=["logits", "features"])
    del kwargs

    logits = original_kwargs["logits"]
    labels = original_kwargs["labels"]
    features = original_kwargs["features"]
    del original_kwargs

    metrics_dict = {}

    for name, fn in metric_fns:
      if isinstance(logits, dict) and isinstance(labels, dict):
        for k, v in six.iteritems(logits):
          metrics_dict["%s/%s" % (k, name)] = fn(v, labels[k], features)
      elif isinstance(logits, dict):
        tf.logging.warning("Logits is a dict, but labels is not; only "
                           "evaluating logits['targets'] against labels.")
        metrics_dict["%s/%s" % ("targets", name)] = fn(logits["targets"],
                                                       labels, features)
      else:
        metrics_dict[name] = fn(logits, labels, features)

    return metrics_dict

  return all_metrics_fn
1366002
def _update_projects(self):
        ''''''
        now = time.time()
        if (
                not self._force_update_project
                and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now
        ):
            return
        for project in self.projectdb.check_update(self._last_update_project):
            self._update_project(project)
            logger.debug("project: %s updated.", project['name'])
        self._force_update_project = False
        self._last_update_project = now
813876
def details(project):
    
    indicators = project.indicator_set.all()
    indicators_detail = [(indicator_details(i)
                         for i in indicators)][0]
    if not indicators:
        indicators_detail = [
                        {'FinancialIndicator':
                            {'valor': 0.0,
                             'metrics': default_metrics, }, }]
    indicators_detail = convert_list_into_dict(indicators_detail)

    return {'pronac': project.pronac,
            'nome': project.nome,
            'indicadores': indicators_detail,
            }
638970
def update(site=False, organizations=False, users=False, datasets=False,
           reuses=False):
    ''''''
    do_all = not any((site, organizations, users, datasets, reuses))

    if do_all or site:
        log.info('Update site metrics')
        update_site_metrics()

    if do_all or datasets:
        log.info('Update datasets metrics')
        for dataset in Dataset.objects.timeout(False):
            update_metrics_for(dataset)

    if do_all or reuses:
        log.info('Update reuses metrics')
        for reuse in Reuse.objects.timeout(False):
            update_metrics_for(reuse)

    if do_all or organizations:
        log.info('Update organizations metrics')
        for organization in Organization.objects.timeout(False):
            update_metrics_for(organization)

    if do_all or users:
        log.info('Update user metrics')
        for user in User.objects.timeout(False):
            update_metrics_for(user)

    success('All metrics have been updated')