text:
namespace translate {

// Translation frequency UMA histograms.
const char kTranslateTranslationSourceLanguage[] =
    "Translate.Translation.SourceLanguage";
const char kTranslateTranslationStatus[] = "Translate.Translation.Status";
const char kTranslateTranslationTargetLanguage[] =
    "Translate.Translation.TargetLanguage";
const char kTranslateTranslationTargetLanguageOrigin[] =
    "Translate.Translation.TargetLanguage.Origin";
const char kTranslateTranslationType[] = "Translate.Translation.Type";

// UI Interaction frequency UMA histograms.
const char kTranslateUiInteractionEvent[] = "Translate.UiInteraction.Event";

// Page-load frequency UMA histograms.
const char kTranslatePageLoadAutofillAssistantDeferredTriggerDecision[] =
    "Translate.PageLoad.AutofillAssistantDeferredTriggerDecision";
const char kTranslatePageLoadFinalSourceLanguage[] =
    "Translate.PageLoad.FinalSourceLanguage";
const char kTranslatePageLoadFinalState[] = "Translate.PageLoad.FinalState";
const char kTranslatePageLoadFinalTargetLanguage[] =
    "Translate.PageLoad.FinalTargetLanguage";
const char kTranslatePageLoadHrefTriggerDecision[] =
    "Translate.PageLoad.HrefHint.TriggerDecision";
const char kTranslatePageLoadInitialSourceLanguage[] =
    "Translate.PageLoad.InitialSourceLanguage";
const char kTranslatePageLoadInitialState[] = "Translate.PageLoad.InitialState";
const char kTranslatePageLoadInitialTargetLanguage[] =
    "Translate.PageLoad.InitialTargetLanguage";
const char kTranslatePageLoadInitialTargetLanguageOrigin[] =
    "Translate.PageLoad.InitialTargetLanguage.Origin";
const char kTranslatePageLoadIsInitialSourceLanguageInUsersContentLanguages[] =
    "Translate.PageLoad.IsInitialSourceLanguageInUsersContentLanguages";
const char kTranslatePageLoadNumTargetLanguageChanges[] =
    "Translate.PageLoad.NumTargetLanguageChanges";
const char kTranslatePageLoadNumTranslations[] =
    "Translate.PageLoad.NumTranslations";
const char kTranslatePageLoadNumReversions[] =
    "Translate.PageLoad.NumReversions";
const char kTranslatePageLoadRankerDecision[] =
    "Translate.PageLoad.Ranker.Decision";
const char kTranslatePageLoadRankerTimerShouldOfferTranslation[] =
    "Translate.PageLoad.Ranker.Timer.ShouldOffereTranslation";
const char kTranslatePageLoadRankerVersion[] =
    "Translate.PageLoad.Ranker.Version";
const char kTranslatePageLoadTriggerDecision[] =
    "Translate.PageLoad.TriggerDecision";

// Application frequency UMA histograms.
const char kTranslateApplicationStartAlwaysTranslateLanguage[] =
    "Translate.ApplicationStart.AlwaysTranslateLanguage";
const char kTranslateApplicationStartAlwaysTranslateLanguageCount[] =
    "Translate.ApplicationStart.AlwaysTranslateLanguage.Count";
const char kTranslateApplicationStartNeverTranslateLanguage[] =
    "Translate.ApplicationStart.NeverTranslateLanguage";
const char kTranslateApplicationStartNeverTranslateLanguageCount[] =
    "Translate.ApplicationStart.NeverTranslateLanguage.Count";
const char kTranslateApplicationStartNeverTranslateSiteCount[] =
    "Translate.ApplicationStart.NeverTranslateSite.Count";

TranslationType NullTranslateMetricsLogger::GetNextManualTranslationType(
    bool is_context_menu_initiated_translation) {
  return TranslationType::kUninitialized;
}

void TranslateMetricsLoggerImpl::LogApplicationStartMetrics(
    std::unique_ptr<TranslatePrefs> translate_prefs) {
  // TODO(1229371): These histograms are only recorded when Chrome starts up
  // using the preferences of whatever profile is logged in at the time. This
  // information should be recorded each time a profile logs in.

  std::vector<std::string> always_translate_languages =
      translate_prefs->GetAlwaysTranslateLanguages();
  for (const auto& always_translate_language : always_translate_languages) {
    base::UmaHistogramSparse(kTranslateApplicationStartAlwaysTranslateLanguage,
                             base::HashMetricName(always_translate_language));
  }
  base::UmaHistogramCounts100(
      kTranslateApplicationStartAlwaysTranslateLanguageCount,
      always_translate_languages.size());

  std::vector<std::string> never_translate_languages =
      translate_prefs->GetNeverTranslateLanguages();
  for (const auto& never_translate_language : never_translate_languages) {
    base::UmaHistogramSparse(kTranslateApplicationStartNeverTranslateLanguage,
                             base::HashMetricName(never_translate_language));
  }
  base::UmaHistogramCounts100(
      kTranslateApplicationStartNeverTranslateLanguageCount,
      never_translate_languages.size());

  std::vector<std::string> never_translate_sites =
      translate_prefs->GetNeverPromptSitesBetween(base::Time::UnixEpoch(),
                                                  base::Time::Now());
  base::UmaHistogramCounts100(kTranslateApplicationStartNeverTranslateSiteCount,
                              never_translate_sites.size());
}

TranslateMetricsLoggerImpl::TranslateMetricsLoggerImpl(
    base::WeakPtr<TranslateManager> translate_manager)
    : translate_manager_(translate_manager),
      clock_(base::DefaultTickClock::GetInstance()),
      time_of_last_state_change_(clock_->NowTicks()) {}

TranslateMetricsLoggerImpl::~TranslateMetricsLoggerImpl() = default;

void TranslateMetricsLoggerImpl::OnPageLoadStart(bool is_foreground) {
  if (translate_manager_)
    translate_manager_->RegisterTranslateMetricsLogger(
        weak_method_factory_.GetWeakPtr());

  is_foreground_ = is_foreground;
  time_of_last_state_change_ = clock_->NowTicks();
}

void TranslateMetricsLoggerImpl::OnForegroundChange(bool is_foreground) {
  UpdateTimeTranslated(current_state_is_translated_, is_foreground_);
  is_foreground_ = is_foreground;
}

void TranslateMetricsLoggerImpl::RecordMetrics(bool is_final) {
  UpdateTimeTranslated(current_state_is_translated_, is_foreground_);

  // If the status of the most recent translation hasn't be reported yet, report
  // it as a "success".
  if (is_translation_status_pending_)
    RecordTranslationStatus(ConvertTranslationTypeToSuccessfulTranslationStatus(
        is_translation_in_progress_, current_translation_type_));

  is_translation_status_pending_ = false;
  current_translation_type_ = TranslationType::kUninitialized;

  // If a translation is still in progress, then use the previous state.
  bool this_initial_state_is_translated =
      is_initial_state_dependent_on_in_progress_translation_
          ? previous_state_is_translated_
          : initial_state_is_translated_;
  bool this_current_state_is_translated = is_translation_in_progress_
                                              ? previous_state_is_translated_
                                              : current_state_is_translated_;

  // The first time |RecordMetrics| is called, record all page load frequency
  // UMA metrcis.
  if (sequence_no_ == 0) {
    RecordPageLoadUmaMetrics(this_initial_state_is_translated,
                             this_current_state_is_translated);
  }

  // Record metrics to UKM.
  ukm::UkmRecorder* ukm_recorder = ukm::UkmRecorder::Get();
  ukm::builders::TranslatePageLoad(ukm_source_id_)
      .SetSequenceNumber(sequence_no_)
      .SetTriggerDecision(int(trigger_decision_))
      .SetRankerDecision(int(ranker_decision_))
      .SetRankerVersion(int(ranker_version_))
      .SetInitialState(int(ConvertToTranslateState(
          this_initial_state_is_translated, initial_state_is_ui_shown_,
          initial_state_is_omnibox_icon_shown_)))
      .SetFinalState(int(ConvertToTranslateState(
          this_current_state_is_translated, current_state_is_ui_shown_,
          current_state_is_omnibox_icon_shown_)))
      .SetNumTranslations(
          ukm::GetExponentialBucketMinForCounts1000(num_translations_))
      .SetNumReversions(
          ukm::GetExponentialBucketMinForCounts1000(num_reversions_))
      .SetInitialSourceLanguage(
          int(base::HashMetricName(initial_source_language_)))
      .SetFinalSourceLanguage(
          int(base::HashMetricName(current_source_language_)))
      .SetInitialSourceLanguageInContentLanguages(
          int(is_initial_source_language_in_users_content_languages_))
      .SetInitialTargetLanguage(
          int(base::HashMetricName(initial_target_language_)))
      .SetFinalTargetLanguage(
          int(base::HashMetricName(current_target_language_)))
      .SetNumTargetLanguageChanges(ukm::GetExponentialBucketMinForCounts1000(
          num_target_language_changes_))
      .SetFirstUIInteraction(int(first_ui_interaction_))
      .SetNumUIInteractions(
          ukm::GetExponentialBucketMinForCounts1000(num_ui_interactions_))
      .SetFirstTranslateError(int(first_translate_error_type_))
      .SetNumTranslateErrors(
          ukm::GetExponentialBucketMinForCounts1000(num_translate_errors_))
      .SetTotalTimeTranslated(ukm::GetExponentialBucketMinForUserTiming(
          total_time_translated_.InSeconds()))
      .SetTotalTimeNotTranslated(ukm::GetExponentialBucketMinForUserTiming(
          total_time_not_translated_.InSeconds()))
      .SetMaxTimeToTranslate(ukm::GetExponentialBucketMinForUserTiming(
          max_time_to_translate_.InMilliseconds()))
      .SetModelDetectionReliabilityScore(ukm::GetLinearBucketMin(
          static_cast<int64_t>(100 * model_detection_reliability_score_), 5))
      .SetModelDetectedLanguage(
          int(base::HashMetricName(model_detected_language_)))
      .SetHTMLContentLanguage(int(base::HashMetricName(html_content_language_)))
      .SetHTMLDocumentLanguage(int(base::HashMetricName(html_doc_language_)))
      .SetWasContentEmpty(was_content_empty_)
      .Record(ukm_recorder);

  sequence_no_++;
}

void TranslateMetricsLoggerImpl::SetUkmSourceId(ukm::SourceId ukm_source_id) {
  ukm_source_id_ = ukm_source_id;
}

void TranslateMetricsLoggerImpl::RecordPageLoadUmaMetrics(
    bool initial_state_is_translated,
    bool current_state_is_translated) {
  base::UmaHistogramEnumeration(kTranslatePageLoadRankerDecision,
                                ranker_decision_);
  base::UmaHistogramSparse(kTranslatePageLoadRankerVersion,
                           int(ranker_version_));
  if (ranker_duration_)
    base::UmaHistogramTimes(kTranslatePageLoadRankerTimerShouldOfferTranslation,
                            ranker_duration_.value());

  base::UmaHistogramEnumeration(kTranslatePageLoadTriggerDecision,
                                trigger_decision_);
  if (has_href_translate_target_) {
    base::UmaHistogramEnumeration(kTranslatePageLoadHrefTriggerDecision,
                                  trigger_decision_);
  }
  base::UmaHistogramBoolean(
      kTranslatePageLoadAutofillAssistantDeferredTriggerDecision,
      autofill_assistant_deferred_trigger_decision_);

  base::UmaHistogramEnumeration(
      kTranslatePageLoadInitialState,
      ConvertToTranslateState(initial_state_is_translated,
                              initial_state_is_ui_shown_,
                              initial_state_is_omnibox_icon_shown_));
  base::UmaHistogramEnumeration(
      kTranslatePageLoadFinalState,
      ConvertToTranslateState(current_state_is_translated,
                              current_state_is_ui_shown_,
                              current_state_is_omnibox_icon_shown_));
  base::UmaHistogramCounts10000(kTranslatePageLoadNumTranslations,
                                num_translations_);
  base::UmaHistogramCounts10000(kTranslatePageLoadNumReversions,
                                num_reversions_);

  base::UmaHistogramSparse(kTranslatePageLoadInitialSourceLanguage,
                           base::HashMetricName(initial_source_language_));
  base::UmaHistogramSparse(kTranslatePageLoadFinalSourceLanguage,
                           base::HashMetricName(current_source_language_));
  base::UmaHistogramBoolean(
      kTranslatePageLoadIsInitialSourceLanguageInUsersContentLanguages,
      is_initial_source_language_in_users_content_languages_);
  base::UmaHistogramSparse(kTranslatePageLoadInitialTargetLanguage,
                           base::HashMetricName(initial_target_language_));
  base::UmaHistogramSparse(kTranslatePageLoadFinalTargetLanguage,
                           base::HashMetricName(current_target_language_));
  base::UmaHistogramCustomCounts(kTranslatePageLoadNumTargetLanguageChanges,
                                 num_target_language_changes_, 1, 50, 20);
  base::UmaHistogramEnumeration(kTranslatePageLoadInitialTargetLanguageOrigin,
                                initial_target_language_origin_);
}

void TranslateMetricsLoggerImpl::RecordTranslationHistograms(
    TranslationType translation_type,
    const std::string& source_language,
    const std::string& target_language,
    TranslateBrowserMetrics::TargetLanguageOrigin target_language_origin) {
  base::UmaHistogramEnumeration(kTranslateTranslationType, translation_type);
  base::UmaHistogramSparse(kTranslateTranslationSourceLanguage,
                           base::HashMetricName(source_language));
  base::UmaHistogramSparse(kTranslateTranslationTargetLanguage,
                           base::HashMetricName(target_language));
  base::UmaHistogramEnumeration(kTranslateTranslationTargetLanguageOrigin,
                                target_language_origin);
}

void TranslateMetricsLoggerImpl::RecordTranslationStatus(
    TranslationStatus translation_status) {
  base::UmaHistogramEnumeration(kTranslateTranslationStatus,
                                translation_status);
}

void TranslateMetricsLoggerImpl::LogRankerMetrics(
    RankerDecision ranker_decision,
    uint32_t ranker_version) {
  ranker_decision_ = ranker_decision;
  ranker_version_ = ranker_version;
}

void TranslateMetricsLoggerImpl::LogRankerStart() {
  if (!ranker_duration_)
    ranker_start_time_ = clock_->NowTicks();
}

void TranslateMetricsLoggerImpl::LogRankerFinish() {
  if (!ranker_duration_)
    ranker_duration_ = clock_->NowTicks() - ranker_start_time_;
}

void TranslateMetricsLoggerImpl::LogTriggerDecision(
    TriggerDecision trigger_decision) {
  // Only stores the first non-kUninitialized trigger decision that is logged,
  // except in the case that Href translate overrides the decision to either
  // auto translate or show the UI, while autotranslation to a predefined
  // target similarly overrides everything except autotranslation by Href.
  if (trigger_decision_ == TriggerDecision::kUninitialized ||
      trigger_decision == TriggerDecision::kAutomaticTranslationByHref ||
      (trigger_decision == TriggerDecision::kShowUIFromHref &&
       trigger_decision_ != TriggerDecision::kAutomaticTranslationByHref) ||
      (trigger_decision ==
           TriggerDecision::kAutomaticTranslationToPredefinedTarget &&
       trigger_decision_ != TriggerDecision::kAutomaticTranslationByHref)) {
    trigger_decision_ = trigger_decision;
  }
}

void TranslateMetricsLoggerImpl::LogAutofillAssistantDeferredTriggerDecision() {
  autofill_assistant_deferred_trigger_decision_ = true;
}

void TranslateMetricsLoggerImpl::LogInitialState() {
  // Sets the initial state to the current state.
  initial_state_is_translated_ = current_state_is_translated_;
  initial_state_is_ui_shown_ = current_state_is_ui_shown_;
  initial_state_is_omnibox_icon_shown_ = current_state_is_omnibox_icon_shown_;

  is_initial_state_set_ = true;

  // If the initial state is based on an in progress translation, we may need to
  // update the initial state if the translation fails or if we try to record
  // metrics before it finishes.
  if (is_translation_in_progress_)
    is_initial_state_dependent_on_in_progress_translation_ = true;
}

void TranslateMetricsLoggerImpl::LogTranslationStarted(
    TranslationType translation_type) {
  if (is_translation_status_pending_)
    RecordTranslationStatus(TranslationStatus::kNewTranslation);

  // Save the previous state in case the translation fails.
  previous_state_is_translated_ = current_state_is_translated_;

  current_state_is_translated_ = true;
  is_translation_in_progress_ = true;
  is_translation_status_pending_ = true;
  current_translation_type_ = translation_type;
  has_any_translation_started_ = true;

  time_of_last_translation_start_ = clock_->NowTicks();

  RecordTranslationHistograms(
      current_translation_type_, current_source_language_,
      current_target_language_, current_target_language_origin_);
}

void TranslateMetricsLoggerImpl::LogTranslationFinished(
    bool was_successful,
    TranslateErrors error_type) {
  // Note that a translation can fail (i.e. was_successful is false) and have an
  // error type of NONE in some cases. One case where this happens is when a
  // translation is interrupted midway through.
  if (was_successful) {
    UpdateTimeTranslated(previous_state_is_translated_, is_foreground_);
    num_translations_++;

    // Calculate the time it took to complete this translation, and check if is
    // the the longest translation for this page load.
    base::TimeDelta time_of_translation =
        clock_->NowTicks() - time_of_last_translation_start_;
    if (time_of_translation > max_time_to_translate_)
      max_time_to_translate_ = time_of_translation;
  } else {
    // If the translation fails, then undo the change to the current state.
    current_state_is_translated_ = previous_state_is_translated_;

    // Update the initial state if it was dependent on this translation..
    if (is_initial_state_dependent_on_in_progress_translation_)
      initial_state_is_translated_ = previous_state_is_translated_;

    if (is_translation_status_pending_)
      RecordTranslationStatus(ConvertTranslationTypeToFailedTranslationStatus(
          current_translation_type_, error_type != TranslateErrors::NONE));

    is_translation_status_pending_ = false;
    current_translation_type_ = TranslationType::kUninitialized;
  }

  // If there was some error, checks if this was the first error, and increments
  // the error count.
  if (error_type != TranslateErrors::NONE) {
    if (first_translate_error_type_ == TranslateErrors::NONE)
      first_translate_error_type_ = error_type;
    num_translate_errors_++;
  }

  is_translation_in_progress_ = false;
  is_initial_state_dependent_on_in_progress_translation_ = false;
}

void TranslateMetricsLoggerImpl::LogReversion() {
  UpdateTimeTranslated(current_state_is_translated_, is_foreground_);

  if (is_translation_status_pending_)
    RecordTranslationStatus(ConvertTranslationTypeToRevertedTranslationStatus(
        current_translation_type_));

  current_state_is_translated_ = false;
  is_translation_status_pending_ = false;
  current_translation_type_ = TranslationType::kUninitialized;
  num_reversions_++;
}

void TranslateMetricsLoggerImpl::LogUIChange(bool is_ui_shown) {
  current_state_is_ui_shown_ = is_ui_shown;
}

void TranslateMetricsLoggerImpl::LogOmniboxIconChange(
    bool is_omnibox_icon_shown) {
  current_state_is_omnibox_icon_shown_ = is_omnibox_icon_shown;
}

void TranslateMetricsLoggerImpl::LogInitialSourceLanguage(
    const std::string& source_language_code,
    bool is_in_users_content_languages) {
  initial_source_language_ = source_language_code;
  is_initial_source_language_in_users_content_languages_ =
      is_in_users_content_languages;

  current_source_language_ = source_language_code;
}

void TranslateMetricsLoggerImpl::LogSourceLanguage(
    const std::string& source_language_code) {
  current_source_language_ = source_language_code;
}

void TranslateMetricsLoggerImpl::LogTargetLanguage(
    const std::string& target_language_code,
    TranslateBrowserMetrics::TargetLanguageOrigin target_language_origin) {
  if (initial_target_language_ == "") {
    initial_target_language_ = target_language_code;
    initial_target_language_origin_ = target_language_origin;
  }

  // Only increment |num_target_language_changes_| if |current_target_language_|
  // changes between two languages.
  if (current_target_language_ != "" &&
      current_target_language_ != target_language_code)
    num_target_language_changes_++;

  current_target_language_ = target_language_code;
  current_target_language_origin_ = target_language_origin;
}

void TranslateMetricsLoggerImpl::LogUIInteraction(
    UIInteraction ui_interaction) {
  if (first_ui_interaction_ == UIInteraction::kUninitialized)
    first_ui_interaction_ = ui_interaction;

  num_ui_interactions_++;

  // Record this UI interaction to the Translate.UiInteraction.Event UMA
  // histogram immediately.
  base::UmaHistogramEnumeration(kTranslateUiInteractionEvent, ui_interaction);
}

TranslationType TranslateMetricsLoggerImpl::GetNextManualTranslationType(
    bool is_context_menu_initiated_translation) {
  if (is_context_menu_initiated_translation) {
    return has_any_translation_started_
               ? TranslationType::kManualContextMenuReTranslation
               : TranslationType::kManualContextMenuInitialTranslation;
  }

  // If the translation was not initiated from the context menu, then it must
  // have been triggered from the translate UI.
  return has_any_translation_started_
             ? TranslationType::kManualUiReTranslation
             : TranslationType::kManualUiInitialTranslation;
}

void TranslateMetricsLoggerImpl::SetHasHrefTranslateTarget(
    bool has_href_translate_target) {
  has_href_translate_target_ = has_href_translate_target;
}

TranslateState TranslateMetricsLoggerImpl::ConvertToTranslateState(
    bool is_translated,
    bool is_ui_shown,
    bool is_omnibox_shown) const {
  if (!is_initial_state_set_)
    return TranslateState::kUninitialized;

  if (!is_translated && !is_ui_shown && !is_omnibox_shown)
    return TranslateState::kNotTranslatedNoUI;

  if (!is_translated && !is_ui_shown && is_omnibox_shown)
    return TranslateState::kNotTranslatedOmniboxIconOnly;

  if (!is_translated && is_ui_shown)
    return TranslateState::kNotTranslatedUIShown;

  if (is_translated && !is_ui_shown && !is_omnibox_shown)
    return TranslateState::kTranslatedNoUI;

  if (is_translated && !is_ui_shown && is_omnibox_shown)
    return TranslateState::kTranslatedOmniboxIconOnly;

  if (is_translated && is_ui_shown)
    return TranslateState::kTranslatedUIShown;

  NOTREACHED();
  return TranslateState::kUninitialized;
}

void TranslateMetricsLoggerImpl::UpdateTimeTranslated(bool was_translated,
                                                      bool was_foreground) {
  base::TimeTicks current_time = clock_->NowTicks();
  if (was_foreground) {
    base::TimeDelta time_since_last_update =
        current_time - time_of_last_state_change_;
    if (was_translated)
      total_time_translated_ += time_since_last_update;
    else
      total_time_not_translated_ += time_since_last_update;
  }
  time_of_last_state_change_ = current_time;
}

TranslationStatus
TranslateMetricsLoggerImpl::ConvertTranslationTypeToRevertedTranslationStatus(
    TranslationType translation_type) {
  if (translation_type == TranslationType::kManualUiInitialTranslation ||
      translation_type == TranslationType::kManualUiReTranslation)
    return TranslationStatus::kRevertedManualUiTranslation;
  if (translation_type ==
          TranslationType::kManualContextMenuInitialTranslation ||
      translation_type == TranslationType::kManualContextMenuReTranslation)
    return TranslationStatus::kRevertedManualContextMenuTranslation;
  if (translation_type == TranslationType::kAutomaticTranslationByPref ||
      translation_type == TranslationType::kAutomaticTranslationByLink)
    return TranslationStatus::kRevertedAutomaticTranslation;
  return TranslationStatus::kUninitialized;
}

TranslationStatus
TranslateMetricsLoggerImpl::ConvertTranslationTypeToFailedTranslationStatus(
    TranslationType translation_type,
    bool was_translation_error) {
  if (translation_type == TranslationType::kManualUiInitialTranslation ||
      translation_type == TranslationType::kManualUiReTranslation) {
    if (was_translation_error)
      return TranslationStatus::kFailedWithErrorManualUiTranslation;
    else
      return TranslationStatus::kFailedWithNoErrorManualUiTranslation;
  }
  if (translation_type ==
          TranslationType::kManualContextMenuInitialTranslation ||
      translation_type == TranslationType::kManualContextMenuReTranslation) {
    if (was_translation_error)
      return TranslationStatus::kFailedWithErrorManualContextMenuTranslation;
    else
      return TranslationStatus::kFailedWithNoErrorManualContextMenuTranslation;
  }
  if (translation_type == TranslationType::kAutomaticTranslationByPref ||
      translation_type == TranslationType::kAutomaticTranslationByLink) {
    if (was_translation_error)
      return TranslationStatus::kFailedWithErrorAutomaticTranslation;
    else
      return TranslationStatus::kFailedWithNoErrorAutomaticTranslation;
  }
  return TranslationStatus::kUninitialized;
}

TranslationStatus
TranslateMetricsLoggerImpl::ConvertTranslationTypeToSuccessfulTranslationStatus(
    bool is_translation_in_progress,
    TranslationType translation_type) {
  if (is_translation_in_progress)
    return TranslationStatus::kTranslationAbandoned;
  if (translation_type == TranslationType::kManualUiInitialTranslation ||
      translation_type == TranslationType::kManualUiReTranslation)
    return TranslationStatus::kSuccessFromManualUiTranslation;
  if (translation_type ==
          TranslationType::kManualContextMenuInitialTranslation ||
      translation_type == TranslationType::kManualContextMenuReTranslation)
    return TranslationStatus::kSuccessFromManualContextMenuTranslation;
  if (translation_type == TranslationType::kAutomaticTranslationByPref)
    return TranslationStatus::kSuccessFromAutomaticTranslationByPref;
  if (translation_type == TranslationType::kAutomaticTranslationByLink)
    return TranslationStatus::kSuccessFromAutomaticTranslationByLink;
  return TranslationStatus::kUninitialized;
}

void TranslateMetricsLoggerImpl::SetInternalClockForTesting(
    base::TickClock* clock) {
  clock_ = clock;
  time_of_last_state_change_ = clock_->NowTicks();
}

void TranslateMetricsLoggerImpl::LogHTMLDocumentLanguage(
    const std::string& html_doc_language) {
  html_doc_language_ = html_doc_language;
}

void TranslateMetricsLoggerImpl::LogHTMLContentLanguage(
    const std::string& html_content_language) {
  html_content_language_ = html_content_language;
}
void TranslateMetricsLoggerImpl::LogDetectedLanguage(
    const std::string& model_detected_language) {
  model_detected_language_ = model_detected_language;
}

void TranslateMetricsLoggerImpl::LogDetectionReliabilityScore(
    const float& model_detection_reliability_score) {
  model_detection_reliability_score_ = model_detection_reliability_score;
}

void TranslateMetricsLoggerImpl::LogWasContentEmpty(bool was_content_empty) {
  was_content_empty_ = was_content_empty;
}

}  // namespace translate


text:
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Domain.Repositories
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class AdventureWorks2008R2Entities : DbContext
    {
        public AdventureWorks2008R2Entities()
            : base("name=AdventureWorks2008R2Entities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Address> Address { get; set; }
        public DbSet<AddressType> AddressType { get; set; }
        public DbSet<BusinessEntity> BusinessEntity { get; set; }
        public DbSet<BusinessEntityAddress> BusinessEntityAddress { get; set; }
        public DbSet<BusinessEntityContact> BusinessEntityContact { get; set; }
        public DbSet<ContactType> ContactType { get; set; }
        public DbSet<CountryRegion> CountryRegion { get; set; }
        public DbSet<EmailAddress> EmailAddress { get; set; }
        public DbSet<Password> Password { get; set; }
        public DbSet<Person> Person { get; set; }
        public DbSet<PersonPhone> PersonPhone { get; set; }
        public DbSet<PhoneNumberType> PhoneNumberType { get; set; }
        public DbSet<StateProvince> StateProvince { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Yoanm\ComposerConfigManager\Infrastructure\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Yoanm\ComposerConfigManager\Application\Loader\ConfigurationFileLoaderInterface;
use Yoanm\ComposerConfigManager\Domain\Model\ConfigurationFile;

abstract class AbstractTemplatableCommand extends Command
{
    const OPTION_TEMPLATE = 'template';

    /** @var ConfigurationFileLoaderInterface */
    private $configurationFileLoader;

    /**
     * @param ConfigurationFileLoaderInterface $configurationFileLoader
     */
    public function __construct(ConfigurationFileLoaderInterface $configurationFileLoader)
    {
        parent::__construct();
        $this->configurationFileLoader = $configurationFileLoader;
    }
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->addOption(
                self::OPTION_TEMPLATE,
                null,
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
                'Path of the json template file. Will be used as default values.'
            )
        ;
    }

    /**
     * @return ConfigurationFileLoaderInterface
     */
    public function getConfigurationFileLoader()
    {
        return $this->configurationFileLoader;
    }

    /**
     * @param InputInterface $input
     *
     * @return ConfigurationFile[]
     */
    protected function loadTemplateConfigurationFileList(InputInterface $input)
    {
        $templatePathList = $input->getOption(self::OPTION_TEMPLATE);
        $templateConfigurationList = [];
        if (count($templatePathList)) {
            foreach ($templatePathList as $templatePath) {
                if (is_dir($templatePath)) {
                    $templateConfigurationList[] = $this->configurationFileLoader->fromPath($templatePath);
                } elseif (is_file($templatePath)) {
                    $templateConfigurationList[] = $this->configurationFileLoader->fromString(
                        file_get_contents($templatePath)
                    );
                } else {
                    throw new \UnexpectedValueException('Template path is nor a file or a path !');
                }
            }
        }

        return $templateConfigurationList;
    }
}


text:
import {isArray, values as objectValues} from "../util.js";

//Reduce an array
let reduce = function (array, initialValue, callback) {
    return array.reduce(callback, initialValue);
};

//Convert an argument to array
let toArray = function (values) {
    //Check if values is an array
    if (isArray(values) === true) {
        return values;
    }
    //Default: return the value as an item of an array
    return [values];
};

//Group data
let groupData = function (data, keys, index) {
    if (keys.length <= index) {
        return [data];
    }
    //Get the key to apply
    let key = keys[index];
    let groups = {};
    //Iterate over all data items
    data.forEach(function (datum, index) {
        if (typeof groups[datum[key]] === "undefined") {
            groups[datum[key]] = [];
        }
        //Save this datum item
        groups[datum[key]].push(datum);
    });
    return reduce(objectValues(groups), [], function (current, items) {
        return current.concat(groupData(items, keys, index + 1));
    });
};

//Get context source data
export function source (props) {
    let context = this;
    //Check if data props is defined
    if (typeof props === "object" && props !== null) {
        //Check for array data
        if (isArray(props) === true) {
            return [props];
        }
        //Check for forces data
        if (typeof props.force === "string") {
            return [context.forces.value[props.force]]; //Get from force data
        }
        //Check for undefined data source
        if (typeof props.data !== "string") {
            //TODO: throw error
        }
        //Initialize the output data object
        let data = [context.data[props.data].value];
        //console.log(context);
        //Check for group data by the provided key
        if (typeof props.groupby === "string" || isArray(props.groupby) === true) {
            data =  groupData(data[0], toArray(props.groupby), 0);
        }
        //Check for transform to apply to this data
        //if (isArray(props.transform) === true) {
        //    data = data.map(function (dataItem) {
        //        return context.transform(dataItem, props.transform);
        //    });
        //}
        //Return processed data
        return data;
    }
    //Default: return an empty data object
    return [[null]];
}


text:
#pragma once

#include <functional>
#include <string>
#include <unordered_map>
#include <vector>

#include "envoy/access_log/access_log.h"
#include "envoy/common/time.h"
#include "envoy/stream_info/stream_info.h"

#include "common/common/utility.h"

#include "absl/types/optional.h"

namespace Envoy {
namespace AccessLog {

/**
 * Access log format parser.
 */
class AccessLogFormatParser {
public:
  static std::vector<FormatterProviderPtr> parse(const std::string& format);

private:
  /**
   * Parse a header format rule of the form: %REQ(X?Y):Z% .
   * Will populate a main_header and an optional alternative header if specified.
   * See doc:
   * docs/root/configuration/access_log.rst#format-rules
   */
  static void parseCommandHeader(const std::string& token, const size_t start,
                                 std::string& main_header, std::string& alternative_header,
                                 absl::optional<size_t>& max_length);

  /**
   * General parse command utility. Will parse token from start position. Token is expected to end
   * with ')'. An optional ":max_length" may be specified after the closing ')' char. Token may
   * contain multiple values separated by "separator" string. First value will be populated in
   * "main" and any additional sub values will be set in the vector "subitems". For example token
   * of: "com.test.my_filter:test_object:inner_key):100" with separator of ":" will set the
   * following:
   * - main: com.test.my_filter
   * - subitems: {test_object, inner_key}
   * - max_length: 100
   *
   * @param token the token to parse
   * @param start the index to start parsing from
   * @param separator separator between values
   * @param main the first value
   * @param sub_items any additional values
   * @param max_length optional max_length will be populated if specified
   *
   * TODO(glicht) Rewrite with a parser library. See:
   * https://github.com/envoyproxy/envoy/issues/2967
   */
  static void parseCommand(const std::string& token, const size_t start,
                           const std::string& separator, std::string& main,
                           std::vector<std::string>& sub_items, absl::optional<size_t>& max_length);

  // the indexes of where the parameters for each directive is expected to begin
  static const size_t ReqParamStart{sizeof("REQ(") - 1};
  static const size_t RespParamStart{sizeof("RESP(") - 1};
  static const size_t TrailParamStart{sizeof("TRAILER(") - 1};
  static const size_t StartTimeParamStart{sizeof("START_TIME(") - 1};
};

/**
 * Util class for access log format.
 */
class AccessLogFormatUtils {
public:
  static FormatterPtr defaultAccessLogFormatter();
  static const std::string& protocolToString(const absl::optional<Http::Protocol>& protocol);
  static std::string durationToString(const absl::optional<std::chrono::nanoseconds>& time);
  static std::string durationToString(const std::chrono::nanoseconds& time);

private:
  AccessLogFormatUtils();

  static const std::string DEFAULT_FORMAT;
};

/**
 * Composite formatter implementation.
 */
class FormatterImpl : public Formatter {
public:
  FormatterImpl(const std::string& format);

  // Formatter::format
  std::string format(const Http::HeaderMap& request_headers,
                     const Http::HeaderMap& response_headers,
                     const Http::HeaderMap& response_trailers,
                     const StreamInfo::StreamInfo& stream_info) const override;

private:
  std::vector<FormatterProviderPtr> providers_;
};

class JsonFormatterImpl : public Formatter {
public:
  JsonFormatterImpl(std::unordered_map<std::string, std::string>& format_mapping);

  // Formatter::format
  std::string format(const Http::HeaderMap& request_headers,
                     const Http::HeaderMap& response_headers,
                     const Http::HeaderMap& response_trailers,
                     const StreamInfo::StreamInfo& stream_info) const override;

private:
  std::vector<FormatterProviderPtr> providers_;
  std::map<const std::string, Envoy::AccessLog::FormatterPtr> json_output_format_;

  std::unordered_map<std::string, std::string>
  toMap(const Http::HeaderMap& request_headers, const Http::HeaderMap& response_headers,
        const Http::HeaderMap& response_trailers, const StreamInfo::StreamInfo& stream_info) const;
};

/**
 * Formatter for string literal. It ignores headers and stream info and returns string by which it
 * was initialized.
 */
class PlainStringFormatter : public FormatterProvider {
public:
  PlainStringFormatter(const std::string& str);

  // Formatter::format
  std::string format(const Http::HeaderMap&, const Http::HeaderMap&, const Http::HeaderMap&,
                     const StreamInfo::StreamInfo&) const override;

private:
  std::string str_;
};

class HeaderFormatter {
public:
  HeaderFormatter(const std::string& main_header, const std::string& alternative_header,
                  absl::optional<size_t> max_length);

  std::string format(const Http::HeaderMap& headers) const;

private:
  Http::LowerCaseString main_header_;
  Http::LowerCaseString alternative_header_;
  absl::optional<size_t> max_length_;
};

/**
 * Formatter based on request header.
 */
class RequestHeaderFormatter : public FormatterProvider, HeaderFormatter {
public:
  RequestHeaderFormatter(const std::string& main_header, const std::string& alternative_header,
                         absl::optional<size_t> max_length);

  // Formatter::format
  std::string format(const Http::HeaderMap& request_headers, const Http::HeaderMap&,
                     const Http::HeaderMap&, const StreamInfo::StreamInfo&) const override;
};

/**
 * Formatter based on the response header.
 */
class ResponseHeaderFormatter : public FormatterProvider, HeaderFormatter {
public:
  ResponseHeaderFormatter(const std::string& main_header, const std::string& alternative_header,
                          absl::optional<size_t> max_length);

  // Formatter::format
  std::string format(const Http::HeaderMap&, const Http::HeaderMap& response_headers,
                     const Http::HeaderMap&, const StreamInfo::StreamInfo&) const override;
};

/**
 * Formatter based on the response trailer.
 */
class ResponseTrailerFormatter : public FormatterProvider, HeaderFormatter {
public:
  ResponseTrailerFormatter(const std::string& main_header, const std::string& alternative_header,
                           absl::optional<size_t> max_length);

  // Formatter::format
  std::string format(const Http::HeaderMap&, const Http::HeaderMap&,
                     const Http::HeaderMap& response_trailers,
                     const StreamInfo::StreamInfo&) const override;
};

/**
 * Formatter based on the StreamInfo field.
 */
class StreamInfoFormatter : public FormatterProvider {
public:
  StreamInfoFormatter(const std::string& field_name);

  // Formatter::format
  std::string format(const Http::HeaderMap&, const Http::HeaderMap&, const Http::HeaderMap&,
                     const StreamInfo::StreamInfo& stream_info) const override;

  using FieldExtractor = std::function<std::string(const StreamInfo::StreamInfo&)>;

private:
  FieldExtractor field_extractor_;
};

/**
 * Base formatter for formatting Metadata objects
 */
class MetadataFormatter {
public:
  MetadataFormatter(const std::string& filter_namespace, const std::vector<std::string>& path,
                    absl::optional<size_t> max_length);

  std::string format(const envoy::api::v2::core::Metadata& metadata) const;

private:
  std::string filter_namespace_;
  std::vector<std::string> path_;
  absl::optional<size_t> max_length_;
};

/**
 * Formatter based on the DynamicMetadata from StreamInfo.
 */
class DynamicMetadataFormatter : public FormatterProvider, MetadataFormatter {
public:
  DynamicMetadataFormatter(const std::string& filter_namespace,
                           const std::vector<std::string>& path, absl::optional<size_t> max_length);

  // FormatterProvider::format
  std::string format(const Http::HeaderMap&, const Http::HeaderMap&, const Http::HeaderMap&,
                     const StreamInfo::StreamInfo& stream_info) const override;
};

/**
 * Formatter
 */
class StartTimeFormatter : public FormatterProvider {
public:
  StartTimeFormatter(const std::string& format);
  std::string format(const Http::HeaderMap&, const Http::HeaderMap&, const Http::HeaderMap&,
                     const StreamInfo::StreamInfo&) const override;

private:
  const Envoy::DateFormatter date_formatter_;
};

} // namespace AccessLog
} // namespace Envoy


text:
package com.hevelian.olastic.core.elastic.requests;

import com.hevelian.olastic.core.elastic.pagination.Pagination;

import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.action.search.SearchResponse;

import com.hevelian.olastic.core.edm.ElasticEdmEntitySet;
import com.hevelian.olastic.core.elastic.queries.Query;

/**
 * Interface to provide behavior for all single requests implementations.
 *
 * @author rdidyk
 */
public interface ESRequest {

    /**
     * Gets query.
     *
     * @return query
     */
    Query getQuery();

    /**
     * Gets pagination.
     *
     * @return pagination
     */
    Pagination getPagination();

    /**
     * Gets entity set.
     *
     * @return the edm entity set
     */
    ElasticEdmEntitySet getEntitySet();

    /**
     * Executes request and returns search response.
     *
     * @return found data
     * @throws ODataApplicationException
     *             if any error appeared during executing request
     */
    SearchResponse execute() throws ODataApplicationException;

}


text:
function hoozit(o) {
    if (o.constructor === String) {
        return "string";

    } else if (o.constructor === Boolean) {
        return "boolean";

    } else if (o.constructor === Number) {

        if (isNaN(o)) {
            return "nan";
        } else {
            return "number";
        }

    } else if (typeof o === "undefined") {
        return "undefined";

    // consider: typeof null === object
    } else if (o === null) {
        return "null";

    // consider: typeof [] === object
    } else if (o instanceof Array) {
        return "array";

    // consider: typeof new Date() === object
    } else if (o instanceof Date) {
        return "date";

    // consider: /./ instanceof Object;
    //           /./ instanceof RegExp;
    //          typeof /./ === "function"; // => false in IE and Opera,
    //                                          true in FF and Safari
    } else if (o instanceof RegExp) {
        return "regexp";

    } else if (typeof o === "object") {
        return "object";

    } else if (o instanceof Function) {
        return "function";
    } else {
        return undefined;
    }
}

// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
    var prop = hoozit(o);
    if (prop) {
        if (hoozit(callbacks[prop]) === "function") {
            return callbacks[prop].apply(callbacks, args);
        } else {
            return callbacks[prop]; // or undefined
        }
    }
}
// Test for equality any JavaScript type.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: Philippe Rathé <prathe@gmail.com>

var equiv = function () {

    var innerEquiv; // the real equiv function
    var callers = []; // stack to decide between skip/abort functions

    var callbacks = function () {

        // for string, boolean, number and null
        function useStrictEquality(b, a) {
            if (b instanceof a.constructor || a instanceof b.constructor) {
                // to catch short annotaion VS 'new' annotation of a declaration
                // e.g. var i = 1;
                //      var j = new Number(1);
                return a == b;
            } else {
                return a === b;
            }
        }

        return {
            "string": useStrictEquality,
            "boolean": useStrictEquality,
            "number": useStrictEquality,
            "null": useStrictEquality,
            "undefined": useStrictEquality,

            "nan": function (b) {
                return isNaN(b);
            },

            "date": function (b, a) {
                return hoozit(b) === "date" && a.valueOf() === b.valueOf();
            },

            "regexp": function (b, a) {
                return hoozit(b) === "regexp" &&
                    a.source === b.source && // the regex itself
                    a.global === b.global && // and its modifers (gmi) ...
                    a.ignoreCase === b.ignoreCase &&
                    a.multiline === b.multiline;
            },

            // - skip when the property is a method of an instance (OOP)
            // - abort otherwise,
            //   initial === would have catch identical references anyway
            "function": function () {
                var caller = callers[callers.length - 1];
                return caller !== Object &&
                        typeof caller !== "undefined";
            },

            "array": function (b, a) {
                var i;
                var len;

                // b could be an object literal here
                if ( ! (hoozit(b) === "array")) {
                    return false;
                }

                len = a.length;
                if (len !== b.length) { // safe and faster
                    return false;
                }
                for (i = 0; i < len; i++) {
                    if( ! innerEquiv(a[i], b[i])) {
                        return false;
                    }
                }
                return true;
            },

            "object": function (b, a) {
                var i;
                var eq = true; // unless we can proove it
                var aProperties = [], bProperties = []; // collection of strings

                // comparing constructors is more strict than using instanceof
                if ( a.constructor !== b.constructor) {
                    return false;
                }

                // stack constructor before traversing properties
                callers.push(a.constructor);

                for (i in a) { // be strict: don't ensures hasOwnProperty and go deep

                    aProperties.push(i); // collect a's properties

                    if ( ! innerEquiv(a[i], b[i])) {
                        eq = false;
                    }
                }

                callers.pop(); // unstack, we are done

                for (i in b) {
                    bProperties.push(i); // collect b's properties
                }

                // Ensures identical properties name
                return eq && innerEquiv(aProperties.sort(), bProperties.sort());
            }
        };
    }();

    innerEquiv = function () { // can take multiple arguments
        var args = Array.prototype.slice.apply(arguments);
        if (args.length < 2) {
            return true; // end transition
        }

        return (function (a, b) {
            if (a === b) {
                return true; // catch the most you can
            } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
                return false; // don't lose time with error prone cases
            } else {
                return bindCallbacks(a, callbacks, [b, a]);
            }

        // apply transition with (1..n) arguments
        })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
    };

    return innerEquiv;

}();


text:
class FacebookScrapeReloadWorker
  include Sidekiq::Worker
  sidekiq_options retry: false, queue: 'actions'

  def perform(url)
    Typhoeus.post('https://graph.facebook.com', params: {
      id: url,
      scrape: true,
      access_token: "#{CatarseSettings[:fb_app_id]}|#{CatarseSettings[:fb_app_secret]}"
    })
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Negru & Sándor, Acta bot. hung. 11: 217 (1965)

#### Original name
Ubrizsya Negru

### Remarks
null


text:
<html>
  <head>
    <title>DataSource Update Quicktest</title>
    <link rel="stylesheet" type="text/css" href="../../plottable.css">
    <script src="../bower_components/d3/d3.min.js"></script>
    <script src="../../plottable_multifile.js"></script>
    <script src="../../examples/exampleUtil.js"></script>

    <script>
      var ds;

      window.onload = function() {
        var dataseries = makeRandomData(20, 0.3);

        var xScale = new Plottable.Scale.Linear();
        var xAxis = new Plottable.Axis.XAxis(xScale, "bottom");

        var yScale = new Plottable.Scale.Linear();
        var yAxis = new Plottable.Axis.YAxis(yScale, "left");

        ds = new Plottable.DataSource(dataseries);

        renderAreaD1 = new Plottable.Plot.Area(ds, xScale, yScale);
        renderAreaD1.animate(true);

        var fillAccessor = function() { return "steelblue"; }
        var fillAccessorTop = function() { return "pink"; }
        renderAreaD1.project("fill", fillAccessor)

        var gridlines = new Plottable.Component.Gridlines(xScale, yScale);
        var renderGroup = new Plottable.Component.Group([gridlines, renderAreaD1]);

        var chart = new Plottable.Template.StandardChart()
                        .center(renderGroup).xAxis(xAxis).yAxis(yAxis)
                        .renderTo("#areaRenderer-test");
      }

      function newData() {
        ds.data(makeRandomData(20, Math.random()));
      }
    </script>
  </head>
  <body>
    <svg id="areaRenderer-test" width="480" height="320"></svg>
    <button onclick="newData()">new data</button>
  </body>

</html>


text:
@font-face { /* FIXME - temp placeholder until I get a real image for the homepage */
  font-family: 'Ruthie';
  font-style: normal;
  font-weight: 400;
  src: local('Ruthie'), local('Ruthie-Regular'), url(http://themes.googleusercontent.com/static/fonts/ruthie/v3/Di1LdjRzoaEvDmrQy1l_ww.woff) format('woff');
}

.elation_homepage_section {
  background: white;
  border: 1px solid #d6d6d6;
  border-radius: 6px;
  margin: 1em 0;
  box-shadow: 1px 1px 2px #999;
  position: relative;
  padding: 1em 2em;
}
.elation_homepage_section.elation_homepage_main {
  background: -webkit-linear-gradient(left, rgba(255,255,255,1), rgba(255,255,255,.5)),
                    white url(/images/elation/homepage-main-medium.png) top right no-repeat;
  background: -moz-linear-gradient(left, rgba(255,255,255,1), rgba(255,255,255,.5)),
                    white url(/images/elation/homepage-main-medium.png) top right no-repeat;
  background: -ms-linear-gradient(left, rgba(255,255,255,1), rgba(255,255,255,.5)),
                    white url(/images/elation/homepage-main-medium.png) top right no-repeat;
  background: -o-linear-gradient(left, rgba(255,255,255,1), rgba(255,255,255,.5)),
                    white url(/images/elation/homepage-main-medium.png) top right no-repeat;
  background: linear-gradient(left, rgba(255,255,255,1), rgba(255,255,255,.5)),
                    white url(/images/elation/homepage-main-medium.png) top right no-repeat;
}
/* homepage, main content, left panel */
.elation_homepage_main .panel_left {
  padding: 2em 2em;
  margin-right: 250px;
  text-align: center;
}
.elation_homepage_main .panel_left h1 {
  font-size: 3em;
  letter-spacing: -1px;
  margin: 0;
  color: #404040;
}
.elation_homepage_main .panel_left h2 {
  font-size: 1.6em;
  color: #777;
  margin: .5em 0;
  white-space: nowrap;
}
.elation_homepage_main .panel_left p {
  text-align: center;
  line-height: 1.5em;
}

.elation_homepage_main .panel_left ul {
  text-align: left;
  font-size: .8em;
  margin: 0;
  padding: 0 0 0 2em;
  margin-bottom: 2em;
}
.elation_homepage_main .panel_left ul li {
  padding: .5em 0;
}
/* homepage, main content, right panel */
.elation_homepage_main .panel_right {
  width: 250px;
  padding: 2em 2em;
  position: absolute;
  right: 0;
  top: 0;
}
.elation_homepage_main .panel_right h1 {
  font-family: Ruthie, sans-serif;
  text-align: center;
  font-size: 3.5em;
  font-weight: normal;
}
.elation_homepage_whatis {
  padding: 0 2em;
  line-height: 1.5em;
}
/* homepage, demos */
.elation_homepage_demos {
  width: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
  vertical-align: middle;
}
.elation_homepage_demos .elation_demo:first-child {
  margin-left: 0;
}
.elation_homepage_demos .elation_demo:last-child {
  margin-right: 0;
}
.elation_homepage_demos .elation_demo {
  background: white;
  margin: 0;
  padding: 0;
  width: 32.5%;
  display: inline-block;
  box-shadow: 1px 1px 2px #999;
  vertical-align: middle;
  -webkit-transform: scale(.9) rotateZ(0deg);
  -webkit-transition: all 100ms ease-out;
  -moz-transform: scale(.9) rotateZ(0deg);
  -moz-transition: all 100ms ease-out;
  -ie-transform: scale(.9) rotateZ(0deg);
  -ie-transition: all 100ms ease-out;
  transform: scale(.9) rotateZ(0deg);
  transition: all 100ms ease-out;
  overflow: hidden;
}
.elation_homepage_demos .elation_demo:hover {
  -webkit-transform: scale(1) rotateZ(2deg);
  -moz-transform: scale(1) rotateZ(2deg);
  -ie-transform: scale(1) rotateZ(2deg);
  transform: scale(1) rotateZ(2deg);
}
.elation_homepage_demos .elation_demo a.elation_demo_link {
  display: block;
  border: 1px solid #d6d6d6;
  width: auto;
  padding: 10px;
  text-decoration: none;
}
.elation_homepage_demos .elation_demo h3 {
  font-size: 1em;
  text-align: left;
  font-weight: normal;
  font-family: verdana, sans-serif;
  text-transform: uppercase;
  margin: 0;
  padding: .7em 0 0 0;
  color: #999;
  border-bottom: 0;
  vertical-align: middle;
}
.elation_homepage_demos .elation_demo .elation_demo_content {
  width: 100%;
  max-width: 25em;
  height: 180px;
  margin: 0 auto;
  background: #ccc;
  background: rgba(255,255,255,.2);
  display: inline-block;
  vertical-align: middle;
  line-height: 180px;
  overflow: hidden;
  text-align: center;
}
.elation_homepage_demos .elation_demo .elation_demo_content img {
  min-width: 100%;
  min-height: 100%;
  max-width: 400%;
  max-height: 150%;
  vertical-align: middle;
}

.elation_homepage_demos .elation_demo .elation_demo_content {
  background: rgba(255,255,255,.5);
  padding: 2em;
}
.elation_homepage_demos .elation_demo .elation_demo_content {
  padding: 0;
}

/* screen size overrides */
@media all and (max-width: 750px) {
  .elation_homepage_main .panel_left {
    padding: 2em 2em;
    margin-right: 0;
    margin: 0 auto;
    text-align: center;
  }
  .elation_homepage_main .panel_right {
    display: none;
  }
}


text:
package org.apache.skywalking.apm.collector.analysis.jvm.provider.service;

import org.apache.skywalking.apm.collector.analysis.jvm.define.graph.GraphIdDefine;
import org.apache.skywalking.apm.collector.analysis.jvm.define.service.IMemoryPoolMetricService;
import org.apache.skywalking.apm.collector.core.graph.Graph;
import org.apache.skywalking.apm.collector.core.graph.GraphManager;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.collector.core.util.ObjectUtils;
import org.apache.skywalking.apm.collector.storage.table.jvm.MemoryPoolMetric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author peng-yongsheng
 */
public class MemoryPoolMetricService implements IMemoryPoolMetricService {

    private final Logger logger = LoggerFactory.getLogger(MemoryPoolMetricService.class);

    private Graph<MemoryPoolMetric> memoryPoolMetricGraph;

    private Graph<MemoryPoolMetric> getMemoryPoolMetricGraph() {
        if (ObjectUtils.isEmpty(memoryPoolMetricGraph)) {
            this.memoryPoolMetricGraph = GraphManager.INSTANCE.findGraph(GraphIdDefine.MEMORY_POOL_METRIC_PERSISTENCE_GRAPH_ID, MemoryPoolMetric.class);
        }
        return memoryPoolMetricGraph;
    }

    @Override
    public void send(int instanceId, long timeBucket, int poolType, long init, long max, long used, long committed) {
        String metricId = instanceId + Const.ID_SPLIT + String.valueOf(poolType);
        String id = timeBucket + Const.ID_SPLIT + metricId;

        MemoryPoolMetric memoryPoolMetric = new MemoryPoolMetric();
        memoryPoolMetric.setId(id);
        memoryPoolMetric.setMetricId(metricId);
        memoryPoolMetric.setInstanceId(instanceId);
        memoryPoolMetric.setPoolType(poolType);
        memoryPoolMetric.setInit(init);
        memoryPoolMetric.setMax(max);
        memoryPoolMetric.setUsed(used);
        memoryPoolMetric.setCommitted(committed);
        memoryPoolMetric.setTimes(1L);
        memoryPoolMetric.setTimeBucket(timeBucket);

        logger.debug("push to memory pool metric graph, id: {}", memoryPoolMetric.getId());
        getMemoryPoolMetricGraph().start(memoryPoolMetric);
    }
}