text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"

#include <set>
#include <string>
#include <utility>

#include "base/callback.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_filter_builder.h"
#include "chrome/browser/browsing_data/browsing_data_helper.h"
#include "chrome/browser/browsing_data/registrable_domain_filter_builder.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/domain_reliability/service_factory.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/web_history_service_factory.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/media/media_device_id_salt.h"
#include "chrome/browser/net/nqe/ui_network_quality_estimator_service.h"
#include "chrome/browser/net/nqe/ui_network_quality_estimator_service_factory.h"
#include "chrome/browser/net/predictor.h"
#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
#include "chrome/browser/ntp_snippets/content_suggestions_service_factory.h"
#include "chrome/browser/password_manager/password_store_factory.h"
#include "chrome/browser/permissions/permission_decision_auto_blocker.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/browser/previews/previews_service.h"
#include "chrome/browser/previews/previews_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/web_data_service_factory.h"
#include "chrome/common/features.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
#include "components/domain_reliability/service.h"
#include "components/history/core/browser/history_service.h"
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/browser/pnacl_host.h"
#include "components/ntp_snippets/bookmarks/bookmark_last_visit_utils.h"
#include "components/ntp_snippets/content_suggestions_service.h"
#include "components/omnibox/browser/omnibox_pref_names.h"
#include "components/password_manager/core/browser/password_store.h"
#include "components/prefs/pref_service.h"
#include "components/previews/core/previews_ui_service.h"
#include "components/search_engines/template_url_service.h"
#include "components/sessions/core/tab_restore_service.h"
#include "content/public/browser/plugin_data_remover.h"
#include "content/public/browser/ssl_host_state_delegate.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/user_metrics.h"
#include "net/cookies/cookie_store.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"

#if defined(OS_ANDROID)
#include "chrome/browser/android/offline_pages/offline_page_model_factory.h"
#include "chrome/browser/android/webapps/webapp_registry.h"
#include "chrome/browser/precache/precache_manager_factory.h"
#include "components/offline_pages/core/offline_page_feature.h"
#include "components/offline_pages/core/offline_page_model.h"
#include "components/precache/content/precache_manager.h"
#endif

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/activity_log/activity_log.h"
#include "extensions/browser/extension_prefs.h"
#endif

#if BUILDFLAG(ENABLE_SESSION_SERVICE)
#include "chrome/browser/sessions/session_service.h"
#include "chrome/browser/sessions/session_service_factory.h"
#endif

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chromeos/attestation/attestation_constants.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/user_manager/user.h"
#endif

#if BUILDFLAG(ENABLE_WEBRTC)
#include "chrome/browser/media/webrtc/webrtc_log_list.h"
#include "chrome/browser/media/webrtc/webrtc_log_util.h"
#endif

#if BUILDFLAG(ENABLE_PLUGINS)
#include "chrome/browser/browsing_data/browsing_data_flash_lso_helper.h"
#endif

using base::UserMetricsAction;
using content::BrowserContext;
using content::BrowserThread;

namespace {

void UIThreadTrampolineHelper(const base::Closure& callback) {
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
}

// Convenience method to create a callback that can be run on any thread and
// will post the given |callback| back to the UI thread.
base::Closure UIThreadTrampoline(const base::Closure& callback) {
  // We could directly bind &BrowserThread::PostTask, but that would require
  // evaluating FROM_HERE when this method is called, as opposed to when the
  // task is actually posted.
  return base::Bind(&UIThreadTrampolineHelper, callback);
}

template <typename T>
void IgnoreArgumentHelper(const base::Closure& callback, T unused_argument) {
  callback.Run();
}

// Another convenience method to turn a callback without arguments into one that
// accepts (and ignores) a single argument.
template <typename T>
base::Callback<void(T)> IgnoreArgument(const base::Closure& callback) {
  return base::Bind(&IgnoreArgumentHelper<T>, callback);
}

bool WebsiteSettingsFilterAdapter(
    const base::Callback<bool(const GURL&)> predicate,
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern) {
  // Ignore the default setting.
  if (primary_pattern == ContentSettingsPattern::Wildcard())
    return false;

  // Website settings only use origin-scoped patterns. The only content setting
  // currently supported by ChromeBrowsingDataRemoverDelegate is
  // DURABLE_STORAGE, which also only uses origin-scoped patterns. Such patterns
  // can be directly translated to a GURL.
  GURL url(primary_pattern.ToString());
  DCHECK(url.is_valid());
  return predicate.Run(url);
}

#if !defined(DISABLE_NACL)
void ClearNaClCacheOnIOThread(const base::Closure& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  nacl::NaClBrowser::GetInstance()->ClearValidationCache(callback);
}

void ClearPnaclCacheOnIOThread(base::Time begin,
                               base::Time end,
                               const base::Closure& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  pnacl::PnaclHost::GetInstance()->ClearTranslationCacheEntriesBetween(
      begin, end, callback);
}
#endif

void ClearCookiesOnIOThread(base::Time delete_begin,
                            base::Time delete_end,
                            net::URLRequestContextGetter* rq_context,
                            const base::Closure& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  net::CookieStore* cookie_store =
      rq_context->GetURLRequestContext()->cookie_store();
  cookie_store->DeleteAllCreatedBetweenAsync(delete_begin, delete_end,
                                             IgnoreArgument<int>(callback));
}

void ClearCookiesWithPredicateOnIOThread(
    base::Time delete_begin,
    base::Time delete_end,
    net::CookieStore::CookiePredicate predicate,
    net::URLRequestContextGetter* rq_context,
    const base::Closure& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  net::CookieStore* cookie_store =
      rq_context->GetURLRequestContext()->cookie_store();
  cookie_store->DeleteAllCreatedBetweenWithPredicateAsync(
      delete_begin, delete_end, predicate, IgnoreArgument<int>(callback));
}

void ClearNetworkPredictorOnIOThread(chrome_browser_net::Predictor* predictor) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  DCHECK(predictor);

  predictor->DiscardInitialNavigationHistory();
  predictor->DiscardAllResults();
}

void ClearHostnameResolutionCacheOnIOThread(
    IOThread* io_thread,
    base::Callback<bool(const std::string&)> host_filter) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  io_thread->ClearHostCache(host_filter);
}

void ClearHttpAuthCacheOnIOThread(
    scoped_refptr<net::URLRequestContextGetter> context_getter,
    base::Time delete_begin) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  net::HttpNetworkSession* http_session = context_getter->GetURLRequestContext()
                                              ->http_transaction_factory()
                                              ->GetSession();
  DCHECK(http_session);
  http_session->http_auth_cache()->ClearEntriesAddedWithin(base::Time::Now() -
                                                           delete_begin);
  http_session->CloseAllConnections();
}

}  // namespace

ChromeBrowsingDataRemoverDelegate::SubTask::SubTask(
    const base::Closure& forward_callback)
    : is_pending_(false),
      forward_callback_(forward_callback),
      weak_ptr_factory_(this) {
  DCHECK(!forward_callback_.is_null());
}

ChromeBrowsingDataRemoverDelegate::SubTask::~SubTask() {}

void ChromeBrowsingDataRemoverDelegate::SubTask::Start() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(!is_pending_);
  is_pending_ = true;
}

base::Closure
ChromeBrowsingDataRemoverDelegate::SubTask::GetCompletionCallback() {
  return base::Bind(&SubTask::CompletionCallback,
                    weak_ptr_factory_.GetWeakPtr());
}

void ChromeBrowsingDataRemoverDelegate::SubTask::CompletionCallback() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(is_pending_);
  is_pending_ = false;
  forward_callback_.Run();
}

ChromeBrowsingDataRemoverDelegate::ChromeBrowsingDataRemoverDelegate(
    BrowserContext* browser_context)
    : profile_(Profile::FromBrowserContext(browser_context)),
      sub_task_forward_callback_(
          base::Bind(&ChromeBrowsingDataRemoverDelegate::NotifyIfDone,
                     base::Unretained(this))),
      synchronous_clear_operations_(sub_task_forward_callback_),
      clear_autofill_origin_urls_(sub_task_forward_callback_),
      clear_flash_content_licenses_(sub_task_forward_callback_),
      clear_domain_reliability_monitor_(sub_task_forward_callback_),
      clear_form_(sub_task_forward_callback_),
      clear_history_(sub_task_forward_callback_),
      clear_keyword_data_(sub_task_forward_callback_),
#if !defined(DISABLE_NACL)
      clear_nacl_cache_(sub_task_forward_callback_),
      clear_pnacl_cache_(sub_task_forward_callback_),
#endif
      clear_hostname_resolution_cache_(sub_task_forward_callback_),
      clear_network_predictor_(sub_task_forward_callback_),
      clear_networking_history_(sub_task_forward_callback_),
      clear_passwords_(sub_task_forward_callback_),
      clear_passwords_stats_(sub_task_forward_callback_),
      clear_http_auth_cache_(sub_task_forward_callback_),
      clear_platform_keys_(sub_task_forward_callback_),
#if defined(OS_ANDROID)
      clear_precache_history_(sub_task_forward_callback_),
      clear_offline_page_data_(sub_task_forward_callback_),
#endif
#if BUILDFLAG(ENABLE_WEBRTC)
      clear_webrtc_logs_(sub_task_forward_callback_),
#endif
      clear_auto_sign_in_(sub_task_forward_callback_),
#if BUILDFLAG(ENABLE_PLUGINS)
      flash_lso_helper_(BrowsingDataFlashLSOHelper::Create(browser_context)),
#endif
#if defined(OS_ANDROID)
      webapp_registry_(new WebappRegistry()),
#endif
      weak_ptr_factory_(this) {}

ChromeBrowsingDataRemoverDelegate::~ChromeBrowsingDataRemoverDelegate() {
  history_task_tracker_.TryCancelAll();
  template_url_sub_.reset();
}

void ChromeBrowsingDataRemoverDelegate::RemoveEmbedderData(
    const base::Time& delete_begin,
    const base::Time& delete_end,
    int remove_mask,
    const BrowsingDataFilterBuilder& filter_builder,
    int origin_type_mask,
    const base::Closure& callback) {
  //////////////////////////////////////////////////////////////////////////////
  // INITIALIZATION
  synchronous_clear_operations_.Start();
  callback_ = callback;

  delete_begin_ = delete_begin;
  delete_end_ = delete_end;

  base::Callback<bool(const GURL& url)> filter =
      filter_builder.BuildGeneralFilter();

  // Some backends support a filter that |is_null()| to make complete deletion
  // more efficient.
  base::Callback<bool(const GURL&)> nullable_filter =
      filter_builder.IsEmptyBlacklist() ? base::Callback<bool(const GURL&)>()
                                        : filter;

  // Managed devices and supervised users can have restrictions on history
  // deletion.
  PrefService* prefs = profile_->GetPrefs();
  bool may_delete_history = prefs->GetBoolean(
      prefs::kAllowDeletingBrowserHistory);

  // All the UI entry points into the BrowsingDataRemoverImpl should be
  // disabled, but this will fire if something was missed or added.
  DCHECK(may_delete_history ||
         (remove_mask & BrowsingDataRemover::REMOVE_NOCHECKS) ||
         (!(remove_mask & BrowsingDataRemover::REMOVE_HISTORY) &&
          !(remove_mask & BrowsingDataRemover::REMOVE_DOWNLOADS)));

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_HISTORY
  if ((remove_mask & BrowsingDataRemover::REMOVE_HISTORY) &&
      may_delete_history) {
    history::HistoryService* history_service =
        HistoryServiceFactory::GetForProfile(
            profile_, ServiceAccessType::EXPLICIT_ACCESS);
    if (history_service) {
      // TODO(dmurph): Support all backends with filter (crbug.com/113621).
      content::RecordAction(UserMetricsAction("ClearBrowsingData_History"));
      clear_history_.Start();
      history_service->ExpireLocalAndRemoteHistoryBetween(
          WebHistoryServiceFactory::GetForProfile(profile_), std::set<GURL>(),
          delete_begin_, delete_end_,
          clear_history_.GetCompletionCallback(),
          &history_task_tracker_);
    }

    // Currently, ContentSuggestionService instance exists only on Android.
    ntp_snippets::ContentSuggestionsService* content_suggestions_service =
        ContentSuggestionsServiceFactory::GetForProfileIfExists(profile_);
    if (content_suggestions_service) {
      content_suggestions_service->ClearHistory(delete_begin_, delete_end_,
                                                filter);
    }

    // Remove the last visit dates meta-data from the bookmark model.
    bookmarks::BookmarkModel* bookmark_model =
        BookmarkModelFactory::GetForBrowserContext(profile_);
    if (bookmark_model) {
      ntp_snippets::RemoveLastVisitedDatesBetween(delete_begin_, delete_end_,
                                                  filter, bookmark_model);
    }

#if BUILDFLAG(ENABLE_EXTENSIONS)
    // The extension activity log contains details of which websites extensions
    // were active on. It therefore indirectly stores details of websites a
    // user has visited so best clean from here as well.
    // TODO(msramek): Support all backends with filter (crbug.com/589586).
    extensions::ActivityLog::GetInstance(profile_)->RemoveURLs(
        std::set<GURL>());

    // Clear launch times as they are a form of history.
    // BrowsingDataFilterBuilder currently doesn't support extension origins.
    // Therefore, clearing history for a small set of origins (WHITELIST) should
    // never delete any extension launch times, while clearing for almost all
    // origins (BLACKLIST) should always delete all of extension launch times.
    if (filter_builder.mode() == BrowsingDataFilterBuilder::BLACKLIST) {
      extensions::ExtensionPrefs* extension_prefs =
          extensions::ExtensionPrefs::Get(profile_);
      extension_prefs->ClearLastLaunchTimes();
    }
#endif

    // Need to clear the host cache and accumulated speculative data, as it also
    // reveals some history. We have no mechanism to track when these items were
    // created, so we'll not honor the time range.
    // TODO(msramek): We can use the plugin filter here because plugins, same
    // as the hostname resolution cache, key their entries by hostname. Rename
    // BuildPluginFilter() to something more general to reflect this use.
    if (g_browser_process->io_thread()) {
      clear_hostname_resolution_cache_.Start();
      BrowserThread::PostTaskAndReply(
          BrowserThread::IO, FROM_HERE,
          base::Bind(&ClearHostnameResolutionCacheOnIOThread,
                     g_browser_process->io_thread(),
                     filter_builder.BuildPluginFilter()),
          clear_hostname_resolution_cache_.GetCompletionCallback());
    }
    if (profile_->GetNetworkPredictor()) {
      // TODO(dmurph): Support all backends with filter (crbug.com/113621).
      clear_network_predictor_.Start();
      BrowserThread::PostTaskAndReply(
          BrowserThread::IO, FROM_HERE,
          base::Bind(&ClearNetworkPredictorOnIOThread,
                     profile_->GetNetworkPredictor()),
          clear_network_predictor_.GetCompletionCallback());
      profile_->GetNetworkPredictor()->ClearPrefsOnUIThread();
    }

    // As part of history deletion we also delete the auto-generated keywords.
    TemplateURLService* keywords_model =
        TemplateURLServiceFactory::GetForProfile(profile_);

    if (keywords_model && !keywords_model->loaded()) {
      // TODO(msramek): Store filters from the currently executed task on the
      // object to avoid having to copy them to callback methods.
      template_url_sub_ = keywords_model->RegisterOnLoadedCallback(
          base::Bind(&ChromeBrowsingDataRemoverDelegate::OnKeywordsLoaded,
                     weak_ptr_factory_.GetWeakPtr(), filter));
      keywords_model->Load();
      clear_keyword_data_.Start();
    } else if (keywords_model) {
      keywords_model->RemoveAutoGeneratedForUrlsBetween(filter, delete_begin_,
                                                        delete_end_);
    }

    // The PrerenderManager keeps history of prerendered pages, so clear that.
    // It also may have a prerendered page. If so, the page could be
    // considered to have a small amount of historical information, so delete
    // it, too.
    prerender::PrerenderManager* prerender_manager =
        prerender::PrerenderManagerFactory::GetForBrowserContext(profile_);
    if (prerender_manager) {
      // TODO(dmurph): Support all backends with filter (crbug.com/113621).
      prerender_manager->ClearData(
          prerender::PrerenderManager::CLEAR_PRERENDER_CONTENTS |
          prerender::PrerenderManager::CLEAR_PRERENDER_HISTORY);
    }

    // If the caller is removing history for all hosts, then clear ancillary
    // historical information.
    if (filter_builder.IsEmptyBlacklist()) {
      // We also delete the list of recently closed tabs. Since these expire,
      // they can't be more than a day old, so we can simply clear them all.
      sessions::TabRestoreService* tab_service =
          TabRestoreServiceFactory::GetForProfile(profile_);
      if (tab_service) {
        tab_service->ClearEntries();
        tab_service->DeleteLastSession();
      }

#if BUILDFLAG(ENABLE_SESSION_SERVICE)
      // We also delete the last session when we delete the history.
      SessionService* session_service =
          SessionServiceFactory::GetForProfile(profile_);
      if (session_service)
        session_service->DeleteLastSession();
#endif
    }

    // The saved Autofill profiles and credit cards can include the origin from
    // which these profiles and credit cards were learned.  These are a form of
    // history, so clear them as well.
    // TODO(dmurph): Support all backends with filter (crbug.com/113621).
    scoped_refptr<autofill::AutofillWebDataService> web_data_service =
        WebDataServiceFactory::GetAutofillWebDataForProfile(
            profile_, ServiceAccessType::EXPLICIT_ACCESS);
    if (web_data_service.get()) {
      clear_autofill_origin_urls_.Start();
      web_data_service->RemoveOriginURLsModifiedBetween(
          delete_begin_, delete_end_);
      // The above calls are done on the UI thread but do their work on the DB
      // thread. So wait for it.
      BrowserThread::PostTaskAndReply(
          BrowserThread::DB, FROM_HERE, base::Bind(&base::DoNothing),
          clear_autofill_origin_urls_.GetCompletionCallback());

      autofill::PersonalDataManager* data_manager =
          autofill::PersonalDataManagerFactory::GetForProfile(profile_);
      if (data_manager)
        data_manager->Refresh();
    }

#if BUILDFLAG(ENABLE_WEBRTC)
    clear_webrtc_logs_.Start();
    BrowserThread::PostTaskAndReply(
        BrowserThread::FILE, FROM_HERE,
        base::Bind(
            &WebRtcLogUtil::DeleteOldAndRecentWebRtcLogFiles,
            WebRtcLogList::GetWebRtcLogDirectoryForProfile(profile_->GetPath()),
            delete_begin_),
        clear_webrtc_logs_.GetCompletionCallback());
#endif

#if defined(OS_ANDROID)
    precache::PrecacheManager* precache_manager =
        precache::PrecacheManagerFactory::GetForBrowserContext(profile_);
    // |precache_manager| could be nullptr if the profile is off the record.
    if (!precache_manager) {
      clear_precache_history_.Start();
      precache_manager->ClearHistory();
      // The above calls are done on the UI thread but do their work on the DB
      // thread. So wait for it.
      BrowserThread::PostTaskAndReply(
          BrowserThread::DB, FROM_HERE, base::Bind(&base::DoNothing),
          clear_precache_history_.GetCompletionCallback());
    }

    // Clear the history information (last launch time and origin URL) of any
    // registered webapps.
    webapp_registry_->ClearWebappHistoryForUrls(filter);
#endif

    data_reduction_proxy::DataReductionProxySettings*
        data_reduction_proxy_settings =
            DataReductionProxyChromeSettingsFactory::GetForBrowserContext(
                profile_);
    // |data_reduction_proxy_settings| is null if |profile_| is off the record.
    if (data_reduction_proxy_settings) {
      data_reduction_proxy::DataReductionProxyService*
          data_reduction_proxy_service =
              data_reduction_proxy_settings->data_reduction_proxy_service();
      if (data_reduction_proxy_service) {
        data_reduction_proxy_service->compression_stats()
            ->DeleteBrowsingHistory(delete_begin_, delete_end_);
      }
    }

    // |previews_service| is null if |profile_| is off the record.
    PreviewsService* previews_service =
        PreviewsServiceFactory::GetForProfile(profile_);
    if (previews_service && previews_service->previews_ui_service()) {
      previews_service->previews_ui_service()->ClearBlackList(delete_begin_,
                                                              delete_end_);
    }

    // The SSL Host State that tracks SSL interstitial "proceed" decisions may
    // include origins that the user has visited, so it must be cleared.
    // TODO(msramek): We can reuse the plugin filter here, since both plugins
    // and SSL host state are scoped to hosts and represent them as std::string.
    // Rename the method to indicate its more general usage.
    if (profile_->GetSSLHostStateDelegate()) {
      profile_->GetSSLHostStateDelegate()->Clear(
          filter_builder.IsEmptyBlacklist()
              ? base::Callback<bool(const std::string&)>()
              : filter_builder.BuildPluginFilter());
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_DOWNLOADS
  if ((remove_mask & BrowsingDataRemover::REMOVE_DOWNLOADS) &&
      may_delete_history) {
    DownloadPrefs* download_prefs = DownloadPrefs::FromDownloadManager(
        BrowserContext::GetDownloadManager(profile_));
    download_prefs->SetSaveFilePath(download_prefs->DownloadPath());
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_COOKIES
  // We ignore the REMOVE_COOKIES request if UNPROTECTED_WEB is not set,
  // so that callers who request REMOVE_SITE_DATA with PROTECTED_WEB
  // don't accidentally remove the cookies that are associated with the
  // UNPROTECTED_WEB origin. This is necessary because cookies are not separated
  // between UNPROTECTED_WEB and PROTECTED_WEB.
  if (remove_mask & BrowsingDataRemover::REMOVE_COOKIES &&
      origin_type_mask & BrowsingDataHelper::UNPROTECTED_WEB) {
    content::RecordAction(UserMetricsAction("ClearBrowsingData_Cookies"));

    // Clear the safebrowsing cookies only if time period is for "all time".  It
    // doesn't make sense to apply the time period of deleting in the last X
    // hours/days to the safebrowsing cookies since they aren't the result of
    // any user action.
    if (delete_begin_ == base::Time()) {
      safe_browsing::SafeBrowsingService* sb_service =
          g_browser_process->safe_browsing_service();
      if (sb_service) {
        scoped_refptr<net::URLRequestContextGetter> sb_context =
            sb_service->url_request_context();
        ++clear_cookies_count_;
        if (filter_builder.IsEmptyBlacklist()) {
          BrowserThread::PostTask(
              BrowserThread::IO, FROM_HERE,
              base::Bind(
                  &ClearCookiesOnIOThread, delete_begin_, delete_end_,
                  base::RetainedRef(std::move(sb_context)),
                  UIThreadTrampoline(
                      base::Bind(
                          &ChromeBrowsingDataRemoverDelegate::OnClearedCookies,
                          weak_ptr_factory_.GetWeakPtr()))));
        } else {
          BrowserThread::PostTask(
              BrowserThread::IO, FROM_HERE,
              base::Bind(
                  &ClearCookiesWithPredicateOnIOThread, delete_begin_,
                  delete_end_, filter_builder.BuildCookieFilter(),
                  base::RetainedRef(std::move(sb_context)),
                  UIThreadTrampoline(
                      base::Bind(
                          &ChromeBrowsingDataRemoverDelegate::OnClearedCookies,
                          weak_ptr_factory_.GetWeakPtr()))));
        }
      }
    }

    MediaDeviceIDSalt::Reset(profile_->GetPrefs());
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_DURABLE_PERMISSION
  if (remove_mask & BrowsingDataRemover::REMOVE_DURABLE_PERMISSION) {
    HostContentSettingsMapFactory::GetForProfile(profile_)
        ->ClearSettingsForOneTypeWithPredicate(
            CONTENT_SETTINGS_TYPE_DURABLE_STORAGE,
            base::Bind(&WebsiteSettingsFilterAdapter, filter));
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_SITE_USAGE_DATA
  if (remove_mask & BrowsingDataRemover::REMOVE_SITE_USAGE_DATA) {
    HostContentSettingsMapFactory::GetForProfile(profile_)
        ->ClearSettingsForOneTypeWithPredicate(
            CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT,
            base::Bind(&WebsiteSettingsFilterAdapter, filter));
  }

  if ((remove_mask & BrowsingDataRemover::REMOVE_SITE_USAGE_DATA) ||
      (remove_mask & BrowsingDataRemover::REMOVE_HISTORY)) {
    HostContentSettingsMapFactory::GetForProfile(profile_)
        ->ClearSettingsForOneTypeWithPredicate(
            CONTENT_SETTINGS_TYPE_APP_BANNER,
            base::Bind(&WebsiteSettingsFilterAdapter, filter));

    PermissionDecisionAutoBlocker::RemoveCountsByUrl(profile_, filter);
  }

  //////////////////////////////////////////////////////////////////////////////
  // Password manager
  if (remove_mask & BrowsingDataRemover::REMOVE_PASSWORDS) {
    content::RecordAction(UserMetricsAction("ClearBrowsingData_Passwords"));
    password_manager::PasswordStore* password_store =
        PasswordStoreFactory::GetForProfile(
            profile_, ServiceAccessType::EXPLICIT_ACCESS).get();

    if (password_store) {
      clear_passwords_.Start();
      password_store->RemoveLoginsByURLAndTime(
          filter, delete_begin_, delete_end_,
          clear_passwords_.GetCompletionCallback());
    }

    scoped_refptr<net::URLRequestContextGetter> request_context =
        BrowserContext::GetDefaultStoragePartition(profile_)
            ->GetURLRequestContext();
    clear_http_auth_cache_.Start();
    BrowserThread::PostTaskAndReply(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&ClearHttpAuthCacheOnIOThread, std::move(request_context),
                   delete_begin_),
        clear_http_auth_cache_.GetCompletionCallback());
  }

  if (remove_mask & BrowsingDataRemover::REMOVE_COOKIES) {
    password_manager::PasswordStore* password_store =
        PasswordStoreFactory::GetForProfile(profile_,
                                            ServiceAccessType::EXPLICIT_ACCESS)
            .get();

    if (password_store) {
      clear_auto_sign_in_.Start();
      password_store->DisableAutoSignInForOrigins(
          filter, clear_auto_sign_in_.GetCompletionCallback());
    }
  }

  if (remove_mask & BrowsingDataRemover::REMOVE_HISTORY) {
    password_manager::PasswordStore* password_store =
        PasswordStoreFactory::GetForProfile(
            profile_, ServiceAccessType::EXPLICIT_ACCESS).get();

    if (password_store) {
      clear_passwords_stats_.Start();
      password_store->RemoveStatisticsByOriginAndTime(
          nullable_filter, delete_begin_, delete_end_,
          clear_passwords_stats_.GetCompletionCallback());
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_FORM_DATA
  // TODO(dmurph): Support all backends with filter (crbug.com/113621).
  if (remove_mask & BrowsingDataRemover::REMOVE_FORM_DATA) {
    content::RecordAction(UserMetricsAction("ClearBrowsingData_Autofill"));
    scoped_refptr<autofill::AutofillWebDataService> web_data_service =
        WebDataServiceFactory::GetAutofillWebDataForProfile(
            profile_, ServiceAccessType::EXPLICIT_ACCESS);

    if (web_data_service.get()) {
      clear_form_.Start();
      web_data_service->RemoveFormElementsAddedBetween(delete_begin_,
          delete_end_);
      web_data_service->RemoveAutofillDataModifiedBetween(
          delete_begin_, delete_end_);
      // The above calls are done on the UI thread but do their work on the DB
      // thread. So wait for it.
      BrowserThread::PostTaskAndReply(
          BrowserThread::DB, FROM_HERE, base::Bind(&base::DoNothing),
          clear_form_.GetCompletionCallback());

      autofill::PersonalDataManager* data_manager =
          autofill::PersonalDataManagerFactory::GetForProfile(profile_);
      if (data_manager)
        data_manager->Refresh();
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_CACHE
  if (remove_mask & BrowsingDataRemover::REMOVE_CACHE) {
#if !defined(DISABLE_NACL)
    clear_nacl_cache_.Start();

    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&ClearNaClCacheOnIOThread,
                   UIThreadTrampoline(
                       clear_nacl_cache_.GetCompletionCallback())));

    clear_pnacl_cache_.Start();
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(
            &ClearPnaclCacheOnIOThread, delete_begin_, delete_end_,
            UIThreadTrampoline(clear_pnacl_cache_.GetCompletionCallback())));
#endif

    // The PrerenderManager may have a page actively being prerendered, which
    // is essentially a preemptively cached page.
    prerender::PrerenderManager* prerender_manager =
        prerender::PrerenderManagerFactory::GetForBrowserContext(profile_);
    if (prerender_manager) {
      prerender_manager->ClearData(
          prerender::PrerenderManager::CLEAR_PRERENDER_CONTENTS);
    }

    // When clearing cache, wipe accumulated network related data
    // (TransportSecurityState and HttpServerPropertiesManager data).
    clear_networking_history_.Start();
    profile_->ClearNetworkingHistorySince(
        delete_begin_,
        clear_networking_history_.GetCompletionCallback());

    ntp_snippets::ContentSuggestionsService* content_suggestions_service =
        ContentSuggestionsServiceFactory::GetForProfileIfExists(profile_);
    if (content_suggestions_service)
      content_suggestions_service->ClearAllCachedSuggestions();

    // |ui_nqe_service| may be null if |profile_| is not a regular profile.
    UINetworkQualityEstimatorService* ui_nqe_service =
        UINetworkQualityEstimatorServiceFactory::GetForProfile(profile_);
    DCHECK(profile_->GetProfileType() !=
               Profile::ProfileType::REGULAR_PROFILE ||
           ui_nqe_service != nullptr);
    if (ui_nqe_service) {
      // Network Quality Estimator (NQE) stores the quality (RTT, bandwidth
      // etc.) of different networks in prefs. The stored quality is not
      // broken down by URLs or timestamps, so clearing the cache should
      // completely clear the prefs.
      ui_nqe_service->ClearPrefs();
    }

#if defined(OS_ANDROID)
    // For now we're considering offline pages as cache, so if we're removing
    // cache we should remove offline pages as well.
    if ((remove_mask & BrowsingDataRemover::REMOVE_CACHE)) {
      clear_offline_page_data_.Start();
      offline_pages::OfflinePageModelFactory::GetForBrowserContext(profile_)
          ->DeleteCachedPagesByURLPredicate(
              filter,
              IgnoreArgument<offline_pages::OfflinePageModel::DeletePageResult>(
                  clear_offline_page_data_.GetCompletionCallback()));
    }
#endif
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_PLUGINS
  // Plugins are known to //content and their bulk deletion is implemented in
  // PluginDataRemover. However, the filtered deletion uses
  // BrowsingDataFlashLSOHelper which (currently) has strong dependencies
  // on //chrome.
  // TODO(msramek): Investigate these dependencies and move the plugin deletion
  // to BrowsingDataRemoverImpl in //content. Note that code in //content
  // can simply take advantage of PluginDataRemover directly to delete plugin
  // data in bulk.
#if BUILDFLAG(ENABLE_PLUGINS)
  // Plugin is data not separated for protected and unprotected web origins. We
  // check the origin_type_mask_ to prevent unintended deletion.
  if (remove_mask & BrowsingDataRemover::REMOVE_PLUGIN_DATA &&
      origin_type_mask & BrowsingDataHelper::UNPROTECTED_WEB) {
    content::RecordAction(UserMetricsAction("ClearBrowsingData_LSOData"));
    clear_plugin_data_count_ = 1;

    if (filter_builder.IsEmptyBlacklist()) {
      DCHECK(!plugin_data_remover_);
      plugin_data_remover_.reset(
          content::PluginDataRemover::Create(profile_));
      base::WaitableEvent* event =
          plugin_data_remover_->StartRemoving(delete_begin_);

      base::WaitableEventWatcher::EventCallback watcher_callback = base::Bind(
          &ChromeBrowsingDataRemoverDelegate::OnWaitableEventSignaled,
          weak_ptr_factory_.GetWeakPtr());
      watcher_.StartWatching(event, watcher_callback);
    } else {
      // TODO(msramek): Store filters from the currently executed task on the
      // object to avoid having to copy them to callback methods.
      flash_lso_helper_->StartFetching(base::Bind(
          &ChromeBrowsingDataRemoverDelegate::OnSitesWithFlashDataFetched,
          weak_ptr_factory_.GetWeakPtr(),
          filter_builder.BuildPluginFilter()));
    }
  }
#endif

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_MEDIA_LICENSES
  if (remove_mask & BrowsingDataRemover::REMOVE_MEDIA_LICENSES) {
    // TODO(jrummell): This UMA should be renamed to indicate it is for Media
    // Licenses.
    content::RecordAction(
        UserMetricsAction("ClearBrowsingData_ContentLicenses"));

#if BUILDFLAG(ENABLE_PLUGINS)
    clear_flash_content_licenses_.Start();
    if (!pepper_flash_settings_manager_.get()) {
      pepper_flash_settings_manager_.reset(
          new PepperFlashSettingsManager(this, profile_));
    }
    deauthorize_flash_content_licenses_request_id_ =
        pepper_flash_settings_manager_->DeauthorizeContentLicenses(prefs);
#if defined(OS_CHROMEOS)
    // On Chrome OS, also delete any content protection platform keys.
    const user_manager::User* user =
        chromeos::ProfileHelper::Get()->GetUserByProfile(profile_);
    if (!user) {
      LOG(WARNING) << "Failed to find user for current profile.";
    } else {
      clear_platform_keys_.Start();
      chromeos::DBusThreadManager::Get()
          ->GetCryptohomeClient()
          ->TpmAttestationDeleteKeys(
              chromeos::attestation::KEY_USER,
              cryptohome::Identification(user->GetAccountId()),
              chromeos::attestation::kContentProtectionKeyPrefix,
              base::Bind(
                  &ChromeBrowsingDataRemoverDelegate::OnClearPlatformKeys,
                  weak_ptr_factory_.GetWeakPtr()));
    }
#endif  // defined(OS_CHROMEOS)
#endif  // BUILDFLAG(ENABLE_PLUGINS)
  }

  //////////////////////////////////////////////////////////////////////////////
  // Zero suggest.
  // Remove omnibox zero-suggest cache results. Filtering is not supported.
  // This is not a problem, as deleting more data than necessary will just cause
  // another server round-trip; no data is actually lost.
  if ((remove_mask & (BrowsingDataRemover::REMOVE_CACHE |
                      BrowsingDataRemover::REMOVE_COOKIES))) {
    prefs->SetString(omnibox::kZeroSuggestCachedResults, std::string());
  }

  //////////////////////////////////////////////////////////////////////////////
  // Domain reliability service.
  if (remove_mask & (BrowsingDataRemover::REMOVE_COOKIES |
                     BrowsingDataRemover::REMOVE_HISTORY)) {
    domain_reliability::DomainReliabilityService* service =
      domain_reliability::DomainReliabilityServiceFactory::
          GetForBrowserContext(profile_);
    if (service) {
      domain_reliability::DomainReliabilityClearMode mode;
      if (remove_mask & BrowsingDataRemover::REMOVE_COOKIES)
        mode = domain_reliability::CLEAR_CONTEXTS;
      else
        mode = domain_reliability::CLEAR_BEACONS;

      clear_domain_reliability_monitor_.Start();
      service->ClearBrowsingData(
          mode,
          filter,
          clear_domain_reliability_monitor_.GetCompletionCallback());
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // REMOVE_WEBAPP_DATA
#if defined(OS_ANDROID)
  // Clear all data associated with registered webapps.
  if (remove_mask & BrowsingDataRemover::REMOVE_WEBAPP_DATA)
    webapp_registry_->UnregisterWebappsForUrls(filter);
#endif

  synchronous_clear_operations_.GetCompletionCallback().Run();
}

void ChromeBrowsingDataRemoverDelegate::NotifyIfDone() {
  if (!AllDone())
    return;

  DCHECK(!callback_.is_null());
  callback_.Run();
}

bool ChromeBrowsingDataRemoverDelegate::AllDone() {
  return !clear_cookies_count_ && !synchronous_clear_operations_.is_pending() &&
         !clear_autofill_origin_urls_.is_pending() &&
         !clear_flash_content_licenses_.is_pending() &&
         !clear_domain_reliability_monitor_.is_pending() &&
         !clear_form_.is_pending() && !clear_history_.is_pending() &&
         !clear_hostname_resolution_cache_.is_pending() &&
         !clear_keyword_data_.is_pending() &&
#if !defined(DISABLE_NACL)
         !clear_nacl_cache_.is_pending() && !clear_pnacl_cache_.is_pending() &&
#endif
         !clear_network_predictor_.is_pending() &&
         !clear_networking_history_.is_pending() &&
         !clear_passwords_.is_pending() &&
         !clear_passwords_stats_.is_pending() &&
         !clear_http_auth_cache_.is_pending() &&
         !clear_platform_keys_.is_pending() &&
#if defined(OS_ANDROID)
         !clear_precache_history_.is_pending() &&
         !clear_offline_page_data_.is_pending() &&
#endif
#if BUILDFLAG(ENABLE_WEBRTC)
         !clear_webrtc_logs_.is_pending() &&
#endif
         !clear_auto_sign_in_.is_pending() &&
         !clear_plugin_data_count_;
}

#if defined(OS_ANDROID)
void ChromeBrowsingDataRemoverDelegate::OverrideWebappRegistryForTesting(
    std::unique_ptr<WebappRegistry> webapp_registry) {
  webapp_registry_ = std::move(webapp_registry);
}
#endif

#if BUILDFLAG(ENABLE_PLUGINS)
void ChromeBrowsingDataRemoverDelegate::OverrideFlashLSOHelperForTesting(
    scoped_refptr<BrowsingDataFlashLSOHelper> flash_lso_helper) {
  flash_lso_helper_ = flash_lso_helper;
}
#endif

void ChromeBrowsingDataRemoverDelegate::OnKeywordsLoaded(
    base::Callback<bool(const GURL&)> url_filter) {
  // Deletes the entries from the model.
  TemplateURLService* model =
      TemplateURLServiceFactory::GetForProfile(profile_);
  model->RemoveAutoGeneratedForUrlsBetween(url_filter, delete_begin_,
                                           delete_end_);
  template_url_sub_.reset();
  clear_keyword_data_.GetCompletionCallback().Run();
}

void ChromeBrowsingDataRemoverDelegate::OnClearedCookies() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  DCHECK_GT(clear_cookies_count_, 0);
  --clear_cookies_count_;
  NotifyIfDone();
}

#if defined(OS_CHROMEOS)
void ChromeBrowsingDataRemoverDelegate::OnClearPlatformKeys(
    chromeos::DBusMethodCallStatus call_status,
    bool result) {
  LOG_IF(ERROR, call_status != chromeos::DBUS_METHOD_CALL_SUCCESS || !result)
      << "Failed to clear platform keys.";
  clear_platform_keys_.GetCompletionCallback().Run();
}
#endif

#if BUILDFLAG(ENABLE_PLUGINS)
void ChromeBrowsingDataRemoverDelegate::OnWaitableEventSignaled(
    base::WaitableEvent* waitable_event) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  DCHECK_EQ(1, clear_plugin_data_count_);
  clear_plugin_data_count_ = 0;

  plugin_data_remover_.reset();
  watcher_.StopWatching();
  NotifyIfDone();
}

void ChromeBrowsingDataRemoverDelegate::OnSitesWithFlashDataFetched(
    base::Callback<bool(const std::string&)> plugin_filter,
    const std::vector<std::string>& sites) {
  DCHECK_EQ(1, clear_plugin_data_count_);
  clear_plugin_data_count_ = 0;

  std::vector<std::string> sites_to_delete;
  for (const std::string& site : sites) {
    if (plugin_filter.Run(site))
      sites_to_delete.push_back(site);
  }

  clear_plugin_data_count_ = sites_to_delete.size();

  for (const std::string& site : sites_to_delete) {
    flash_lso_helper_->DeleteFlashLSOsForSite(
        site,
        base::Bind(&ChromeBrowsingDataRemoverDelegate::OnFlashDataDeleted,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  NotifyIfDone();
}

void ChromeBrowsingDataRemoverDelegate::OnFlashDataDeleted() {
  clear_plugin_data_count_--;
  NotifyIfDone();
}

void ChromeBrowsingDataRemoverDelegate::
OnDeauthorizeFlashContentLicensesCompleted(
    uint32_t request_id,
    bool /* success */) {
  DCHECK_EQ(request_id, deauthorize_flash_content_licenses_request_id_);
  clear_flash_content_licenses_.GetCompletionCallback().Run();
}
#endif


text:
package org.weakref.jmx;

import com.google.inject.name.Names;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.lang.annotation.Annotation;
import java.util.ArrayList;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.weakref.jmx.ObjectNames.generatedNameOf;

public class TestObjectNames {

  @interface Ann {}

  static class AnnImpl implements Ann {
    @Override
    public Class<? extends Annotation> annotationType() {
      return Ann.class;
    }
  }

  static class Inner {}

  @Test
  public void testGeneratedNameOf1() {
    assertEquals(
        generatedNameOf(SimpleObject.class),
        "org.weakref.jmx:name=SimpleObject");
  }

  @Test
  public void testGeneratedNameOf2() {
    assertEquals(
        generatedNameOf(SimpleObject.class, Names.named("1")),
        "org.weakref.jmx:type=SimpleObject,name=1");
  }

  @Test
  public void testGeneratedNameOf3() {
    assertEquals(
        generatedNameOf(SimpleObject.class, Ann.class),
        "org.weakref.jmx:type=SimpleObject,name=Ann");
  }

  @Test
  public void testGeneratedNameOf4() {
    assertEquals(
        generatedNameOf(SimpleObject.class, new AnnImpl()),
        "org.weakref.jmx:type=SimpleObject,name=Ann");
  }

  @Test
  public void testGeneratedNameOf5() {
    assertEquals(
        generatedNameOf(Inner.class),
        "org.weakref.jmx:name=Inner");
  }

   @Test
   public void testGeneratedNameOfStringWithQuoting() {
     assertEquals(
        generatedNameOf(SimpleObject.class, "bar,baz"),
        "org.weakref.jmx:type=SimpleObject,name=\"bar,baz\"");
   }

  @Test(dataProvider = "names")
  public void testQuotesName(String name, boolean shouldQuote)
          throws MalformedObjectNameException
  {
      ObjectName objectName = ObjectName.getInstance(generatedNameOf(SimpleObject.class, Names.named(name)));
      if (shouldQuote) {
          String quotedName = objectName.getKeyProperty("name");
          int index = 0;
          StringBuilder builder = new StringBuilder();
          assertEquals(quotedName.charAt(index++), '\"');
          char c;
          while ((c = quotedName.charAt(index++)) != '\"') {
              if (c == '\\') {
                  c = quotedName.charAt(index++);
                  assertTrue("*?n\\\"".indexOf(c) != -1, "valid character '" + c + "' after backslash");
                  if (c == 'n') {
                      builder.append('\n');
                  }
                  else {
                      builder.append(c);
                  }
              }
              else {
                builder.append(c);
              }
          }
          assertEquals(index, quotedName.length());
          assertEquals(builder.toString(), name);
      }
      else {
          assertEquals(objectName.getKeyProperty("name"), name);
      }
  }

  @DataProvider(name = "names")
  public Object[][] getNames()
  {
      ArrayList<Object[]> names = new ArrayList<>();
      for (char c = 0; c < 500; ++c) {
          names.add(new Object[] {String.valueOf(c), ",=:*?\"\n".indexOf(c) != -1});
      }
      names.add(new Object[] {":\\", true});
      return names.toArray(new Object[][]{});
  }
}

redpajama_set_name: RedPajamaGithub


text:
package ru.kurs.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.kurs.addressbook.appmanager.GroupHelper;
import ru.kurs.addressbook.model.GroupData;
import ru.kurs.addressbook.model.Groups;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;

/**
 * Created by yana on 3/2/2016.
 */
public class GroupModificationTest extends TestBase {
    @BeforeMethod
    public void ensurePreconditions(){
        final GroupHelper h = app.group();
        if (app.db().groups().size() == 0){
        app.goTo().groupPage();
            h.create(new GroupData().withName("test_create_if_does_not_exist"));
        }
    }

    @Test //(enabled = false)
    public void testGroupModification() {
        final GroupHelper h = app.group();
        Groups before = app.db().groups();
        GroupData modifiedGroup = before.iterator().next();
        GroupData group = new GroupData()
                .withId(modifiedGroup.getId()).withName("test1").withHeader("test2").withFooter("test3");
        app.goTo().groupPage();
        h.modify(group);
        Groups after = app.db().groups();
        assertEquals(after.size(), before.size());
        assertThat(after, equalTo(before.without(modifiedGroup).withAdded(group)));
        verifyGroupListInUI();
    }

}


text:
package com.intellij.openapi.vcs.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Separator;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorGutterComponentEx;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.localVcs.UpToDateLineNumberProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.annotate.AnnotationGutterActionProvider;
import com.intellij.openapi.vcs.annotate.AnnotationSourceSwitcher;
import com.intellij.openapi.vcs.annotate.FileAnnotation;
import com.intellij.openapi.vcs.annotate.LineAnnotationAspect;
import com.intellij.openapi.vcs.history.VcsFileRevision;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.impl.UpToDateLineNumberProviderImpl;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Konstantin Bulenkov
 * @author: lesya
 */
public class AnnotateToggleAction extends ToggleAction implements DumbAware, AnnotationColors {
  public static final ExtensionPointName<Provider> EP_NAME =
    ExtensionPointName.create("com.intellij.openapi.vcs.actions.AnnotateToggleAction.Provider");

  @Override
  public void update(@NotNull AnActionEvent e) {
    super.update(e);
    Provider provider = getProvider(e);
    e.getPresentation().setEnabled(provider != null && !provider.isSuspended(e));
  }

  @Override
  public boolean isSelected(AnActionEvent e) {
    Provider provider = getProvider(e);
    return provider != null && provider.isAnnotated(e);
  }

  @Override
  public void setSelected(AnActionEvent e, boolean selected) {
    Provider provider = getProvider(e);
    if (provider != null) provider.perform(e, selected);
  }

  public static void doAnnotate(@NotNull final Editor editor,
                                @NotNull final Project project,
                                @Nullable final VirtualFile currentFile,
                                @NotNull final FileAnnotation fileAnnotation,
                                @NotNull final AbstractVcs vcs) {
    doAnnotate(editor, project, currentFile, fileAnnotation, vcs, null);
  }

  public static void doAnnotate(@NotNull final Editor editor,
                                @NotNull final Project project,
                                @Nullable final VirtualFile currentFile,
                                @NotNull final FileAnnotation fileAnnotation,
                                @NotNull final AbstractVcs vcs,
                                @Nullable UpToDateLineNumberProvider getUpToDateLineNumber) {
    if (fileAnnotation.getFile() != null && fileAnnotation.getFile().isInLocalFileSystem()) {
      ProjectLevelVcsManager.getInstance(project).getAnnotationLocalChangesListener().registerAnnotation(fileAnnotation.getFile(), fileAnnotation);
    }

    editor.getGutter().closeAllAnnotations();

    fileAnnotation.setCloser(new Runnable() {
      @Override
      public void run() {
        if (project.isDisposed()) return;
        UIUtil.invokeLaterIfNeeded(new Runnable() {
          @Override
          public void run() {
            if (project.isDisposed()) return;
            editor.getGutter().closeAllAnnotations();
          }
        });
      }
    });

    final EditorGutterComponentEx editorGutter = (EditorGutterComponentEx)editor.getGutter();
    final List<AnnotationFieldGutter> gutters = new ArrayList<AnnotationFieldGutter>();
    final AnnotationSourceSwitcher switcher = fileAnnotation.getAnnotationSourceSwitcher();
    if (getUpToDateLineNumber == null) getUpToDateLineNumber = new UpToDateLineNumberProviderImpl(editor.getDocument(), project);

    final AnnotationPresentation presentation = new AnnotationPresentation(fileAnnotation, getUpToDateLineNumber, switcher);
    if (currentFile != null && vcs.getCommittedChangesProvider() != null) {
      presentation.addAction(new ShowDiffFromAnnotation(fileAnnotation, vcs, currentFile));
    }
    presentation.addAction(new CopyRevisionNumberFromAnnotateAction(fileAnnotation));
    presentation.addAction(Separator.getInstance());

    final Couple<Map<VcsRevisionNumber, Color>> bgColorMap =
      Registry.is("vcs.show.colored.annotations") ? computeBgColors(fileAnnotation) : null;
    final Map<VcsRevisionNumber, Integer> historyIds = Registry.is("vcs.show.history.numbers") ? computeLineNumbers(fileAnnotation) : null;

    if (switcher != null) {
      switcher.switchTo(switcher.getDefaultSource());
      final LineAnnotationAspect revisionAspect = switcher.getRevisionAspect();
      final CurrentRevisionAnnotationFieldGutter currentRevisionGutter =
        new CurrentRevisionAnnotationFieldGutter(fileAnnotation, revisionAspect, presentation, bgColorMap);
      final MergeSourceAvailableMarkerGutter mergeSourceGutter =
        new MergeSourceAvailableMarkerGutter(fileAnnotation, null, presentation, bgColorMap);

      SwitchAnnotationSourceAction switchAction = new SwitchAnnotationSourceAction(switcher, editorGutter);
      presentation.addAction(switchAction);
      switchAction.addSourceSwitchListener(currentRevisionGutter);
      switchAction.addSourceSwitchListener(mergeSourceGutter);

      currentRevisionGutter.consume(switcher.getDefaultSource());
      mergeSourceGutter.consume(switcher.getDefaultSource());

      gutters.add(currentRevisionGutter);
      gutters.add(mergeSourceGutter);
    }

    final LineAnnotationAspect[] aspects = fileAnnotation.getAspects();
    for (LineAnnotationAspect aspect : aspects) {
      gutters.add(new AnnotationFieldGutter(fileAnnotation, aspect, presentation, bgColorMap));
    }

    if (historyIds != null) {
      gutters.add(new HistoryIdColumn(fileAnnotation, presentation, bgColorMap, historyIds));
    }
    gutters.add(new HighlightedAdditionalColumn(fileAnnotation, null, presentation, bgColorMap));
    final AnnotateActionGroup actionGroup = new AnnotateActionGroup(gutters, editorGutter);
    presentation.addAction(actionGroup, 1);
    gutters.add(new ExtraFieldGutter(fileAnnotation, presentation, bgColorMap, actionGroup));

    presentation.addAction(new AnnotateCurrentRevisionAction(fileAnnotation, vcs));
    presentation.addAction(new AnnotatePreviousRevisionAction(fileAnnotation, vcs));
    addActionsFromExtensions(presentation, fileAnnotation);

    for (AnnotationFieldGutter gutter : gutters) {
      final AnnotationGutterLineConvertorProxy proxy = new AnnotationGutterLineConvertorProxy(getUpToDateLineNumber, gutter);
      if (gutter.isGutterAction()) {
        editor.getGutter().registerTextAnnotation(proxy, proxy);
      }
      else {
        editor.getGutter().registerTextAnnotation(proxy);
      }
    }
  }

  private static void addActionsFromExtensions(@NotNull AnnotationPresentation presentation, @NotNull FileAnnotation fileAnnotation) {
    AnnotationGutterActionProvider[] extensions = AnnotationGutterActionProvider.EP_NAME.getExtensions();
    if (extensions.length > 0) {
      presentation.addAction(new Separator());
    }
    for (AnnotationGutterActionProvider provider : extensions) {
      presentation.addAction(provider.createAction(fileAnnotation));
    }
  }

  @Nullable
  private static Map<VcsRevisionNumber, Integer> computeLineNumbers(@NotNull FileAnnotation fileAnnotation) {
    final Map<VcsRevisionNumber, Integer> numbers = new HashMap<VcsRevisionNumber, Integer>();
    final List<VcsFileRevision> fileRevisionList = fileAnnotation.getRevisions();
    if (fileRevisionList != null) {
      int size = fileRevisionList.size();
      for (int i = 0; i < size; i++) {
        VcsFileRevision revision = fileRevisionList.get(i);
        final VcsRevisionNumber number = revision.getRevisionNumber();

        numbers.put(number, size - i);
      }
    }
    return numbers.size() < 2 ? null : numbers;
  }

  @NotNull
  private static Couple<Map<VcsRevisionNumber, Color>> computeBgColors(@NotNull FileAnnotation fileAnnotation) {
    final Map<VcsRevisionNumber, Color> commitOrderColors = new HashMap<VcsRevisionNumber, Color>();
    final Map<VcsRevisionNumber, Color> commitAuthorColors = new HashMap<VcsRevisionNumber, Color>();
    final Map<String, Color> authorColors = new HashMap<String, Color>();
    final List<VcsFileRevision> fileRevisionList = fileAnnotation.getRevisions();
    if (fileRevisionList != null) {
      final int colorsCount = BG_COLORS.length;
      final int revisionsCount = fileRevisionList.size();

      for (int i = 0; i < fileRevisionList.size(); i++) {
        VcsFileRevision revision = fileRevisionList.get(i);
        final VcsRevisionNumber number = revision.getRevisionNumber();
        final String author = revision.getAuthor();
        if (number == null) continue;

        if (!commitAuthorColors.containsKey(number)) {
          if (author != null && !authorColors.containsKey(author)) {
            final int index = authorColors.size();
            Color color = BG_COLORS[index * BG_COLORS_PRIME % colorsCount];
            authorColors.put(author, color);
          }

          commitAuthorColors.put(number, authorColors.get(author));
        }
        if (!commitOrderColors.containsKey(number)) {
          Color color = BG_COLORS[colorsCount * i / revisionsCount];
          commitOrderColors.put(number, color);
        }
      }
    }
    return Couple.of(commitOrderColors.size() > 1 ? commitOrderColors : null,
                     commitAuthorColors.size() > 1 ? commitAuthorColors : null);
  }

  @Nullable
  private static Provider getProvider(AnActionEvent e) {
    for (Provider provider : EP_NAME.getExtensions()) {
      if (provider.isEnabled(e)) return provider;
    }
    return null;
  }

  public interface Provider {
    boolean isEnabled(AnActionEvent e);

    boolean isSuspended(AnActionEvent e);

    boolean isAnnotated(AnActionEvent e);

    void perform(AnActionEvent e, boolean selected);
  }
}


text:
extern zend_class_entry *phalcon_application_ce;

ZEPHIR_INIT_CLASS(Phalcon_Application);

PHP_METHOD(Phalcon_Application, __construct);
PHP_METHOD(Phalcon_Application, setEventsManager);
PHP_METHOD(Phalcon_Application, getEventsManager);
PHP_METHOD(Phalcon_Application, registerModules);
PHP_METHOD(Phalcon_Application, getModules);
PHP_METHOD(Phalcon_Application, getModule);
PHP_METHOD(Phalcon_Application, setDefaultModule);
PHP_METHOD(Phalcon_Application, getDefaultModule);
PHP_METHOD(Phalcon_Application, handle);
zend_object_value zephir_init_properties_Phalcon_Application(zend_class_entry *class_type TSRMLS_DC);

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_application___construct, 0, 0, 0)
	ZEND_ARG_OBJ_INFO(0, dependencyInjector, Phalcon\\DiInterface, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_application_seteventsmanager, 0, 0, 1)
	ZEND_ARG_OBJ_INFO(0, eventsManager, Phalcon\\Events\\ManagerInterface, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_application_registermodules, 0, 0, 1)
	ZEND_ARG_ARRAY_INFO(0, modules, 0)
	ZEND_ARG_INFO(0, merge)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_application_getmodule, 0, 0, 1)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_application_setdefaultmodule, 0, 0, 1)
	ZEND_ARG_INFO(0, defaultModule)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(phalcon_application_method_entry) {
	PHP_ME(Phalcon_Application, __construct, arginfo_phalcon_application___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
	PHP_ME(Phalcon_Application, setEventsManager, arginfo_phalcon_application_seteventsmanager, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, getEventsManager, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, registerModules, arginfo_phalcon_application_registermodules, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, getModules, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, getModule, arginfo_phalcon_application_getmodule, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, setDefaultModule, arginfo_phalcon_application_setdefaultmodule, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, getDefaultModule, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Application, handle, NULL, ZEND_ACC_ABSTRACT|ZEND_ACC_PUBLIC)
	PHP_FE_END
};


text:
using System;
using Affecto.IdentityManagement.Commanding.Commands;
using Affecto.IdentityManagement.Commanding.Validation;
using Affecto.IdentityManagement.Interfaces.Exceptions;
using Affecto.IdentityManagement.Store.Model;
using Affecto.Patterns.Cqrs;

namespace Affecto.IdentityManagement.Commanding.CommandHandlers
{
    internal class UpdateUserAccountCommandHandler : ICommandHandler<UpdateUserAccountCommand>
    {
        private readonly IDbRepository repository;
        private readonly IAuditTrailWriter auditTrail;

        public UpdateUserAccountCommandHandler(IDbRepository repository, IAuditTrailWriter auditTrail)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }
            if (auditTrail == null)
            {
                throw new ArgumentNullException("auditTrail");
            }
            this.repository = repository;
            this.auditTrail = auditTrail;
        }

        public void Execute(UpdateUserAccountCommand command)
        {
            var specification = new UserIdAndNameSpecification();
            if (!specification.IsSatisfiedBy(command))
            {
                throw new ArgumentException(specification.GetReasonsForDissatisfactionSeparatedWithNewLine());
            }

            AccountType type = Map(command.Type);

            User user = repository.GetUser(command.UserId);
            Account account = repository.GetUserAccount(command.UserId, type);

            ThrowIfAccountNameIsAlreadyAssigned(type, account.Name, command.Name);

            account.Name = command.Name;

            repository.SaveChanges();

            auditTrail.AddEntry(command.UserId, user.Name, command.Name, "Käyttäjätunnus päivitetty");
        }

        private static AccountType Map(Interfaces.Model.AccountType type)
        {
            return (AccountType)Enum.Parse(typeof(AccountType), type.ToString());
        }

        private void ThrowIfAccountNameIsAlreadyAssigned(AccountType type, string name, string newName)
        {
            if (!name.Equals(newName, StringComparison.InvariantCultureIgnoreCase) && repository.AccountExists(type, newName))
            {
                throw new UserAccountAlreadyAssignedException(newName);
            }
        }
    }
}


text:
// Code generated by client-gen. DO NOT EDIT.

package v1alpha1

import (
	"context"
	"time"

	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
	v1alpha1 "sigs.k8s.io/kube-storage-version-migrator/pkg/apis/migration/v1alpha1"
	scheme "sigs.k8s.io/kube-storage-version-migrator/pkg/clients/clientset/scheme"
)

// StorageVersionMigrationsGetter has a method to return a StorageVersionMigrationInterface.
// A group's client should implement this interface.
type StorageVersionMigrationsGetter interface {
	StorageVersionMigrations() StorageVersionMigrationInterface
}

// StorageVersionMigrationInterface has methods to work with StorageVersionMigration resources.
type StorageVersionMigrationInterface interface {
	Create(ctx context.Context, storageVersionMigration *v1alpha1.StorageVersionMigration, opts v1.CreateOptions) (*v1alpha1.StorageVersionMigration, error)
	Update(ctx context.Context, storageVersionMigration *v1alpha1.StorageVersionMigration, opts v1.UpdateOptions) (*v1alpha1.StorageVersionMigration, error)
	UpdateStatus(ctx context.Context, storageVersionMigration *v1alpha1.StorageVersionMigration, opts v1.UpdateOptions) (*v1alpha1.StorageVersionMigration, error)
	Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
	DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
	Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.StorageVersionMigration, error)
	List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.StorageVersionMigrationList, error)
	Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
	Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StorageVersionMigration, err error)
	StorageVersionMigrationExpansion
}

// storageVersionMigrations implements StorageVersionMigrationInterface
type storageVersionMigrations struct {
	client rest.Interface
}

// newStorageVersionMigrations returns a StorageVersionMigrations
func newStorageVersionMigrations(c *MigrationV1alpha1Client) *storageVersionMigrations {
	return &storageVersionMigrations{
		client: c.RESTClient(),
	}
}

// Get takes name of the storageVersionMigration, and returns the corresponding storageVersionMigration object, and an error if there is any.
func (c *storageVersionMigrations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.StorageVersionMigration, err error) {
	result = &v1alpha1.StorageVersionMigration{}
	err = c.client.Get().
		Resource("storageversionmigrations").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do(ctx).
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of StorageVersionMigrations that match those selectors.
func (c *storageVersionMigrations) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.StorageVersionMigrationList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1alpha1.StorageVersionMigrationList{}
	err = c.client.Get().
		Resource("storageversionmigrations").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do(ctx).
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested storageVersionMigrations.
func (c *storageVersionMigrations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Resource("storageversionmigrations").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch(ctx)
}

// Create takes the representation of a storageVersionMigration and creates it.  Returns the server's representation of the storageVersionMigration, and an error, if there is any.
func (c *storageVersionMigrations) Create(ctx context.Context, storageVersionMigration *v1alpha1.StorageVersionMigration, opts v1.CreateOptions) (result *v1alpha1.StorageVersionMigration, err error) {
	result = &v1alpha1.StorageVersionMigration{}
	err = c.client.Post().
		Resource("storageversionmigrations").
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(storageVersionMigration).
		Do(ctx).
		Into(result)
	return
}

// Update takes the representation of a storageVersionMigration and updates it. Returns the server's representation of the storageVersionMigration, and an error, if there is any.
func (c *storageVersionMigrations) Update(ctx context.Context, storageVersionMigration *v1alpha1.StorageVersionMigration, opts v1.UpdateOptions) (result *v1alpha1.StorageVersionMigration, err error) {
	result = &v1alpha1.StorageVersionMigration{}
	err = c.client.Put().
		Resource("storageversionmigrations").
		Name(storageVersionMigration.Name).
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(storageVersionMigration).
		Do(ctx).
		Into(result)
	return
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *storageVersionMigrations) UpdateStatus(ctx context.Context, storageVersionMigration *v1alpha1.StorageVersionMigration, opts v1.UpdateOptions) (result *v1alpha1.StorageVersionMigration, err error) {
	result = &v1alpha1.StorageVersionMigration{}
	err = c.client.Put().
		Resource("storageversionmigrations").
		Name(storageVersionMigration.Name).
		SubResource("status").
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(storageVersionMigration).
		Do(ctx).
		Into(result)
	return
}

// Delete takes name of the storageVersionMigration and deletes it. Returns an error if one occurs.
func (c *storageVersionMigrations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	return c.client.Delete().
		Resource("storageversionmigrations").
		Name(name).
		Body(&opts).
		Do(ctx).
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *storageVersionMigrations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	var timeout time.Duration
	if listOpts.TimeoutSeconds != nil {
		timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Resource("storageversionmigrations").
		VersionedParams(&listOpts, scheme.ParameterCodec).
		Timeout(timeout).
		Body(&opts).
		Do(ctx).
		Error()
}

// Patch applies the patch and returns the patched storageVersionMigration.
func (c *storageVersionMigrations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StorageVersionMigration, err error) {
	result = &v1alpha1.StorageVersionMigration{}
	err = c.client.Patch(pt).
		Resource("storageversionmigrations").
		Name(name).
		SubResource(subresources...).
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(data).
		Do(ctx).
		Into(result)
	return
}


text:
package persistency.cassandra;

import de.tudarmstadt.informatik.tk.assistanceplatform.persistency.cassandra.CassandraSessionProxy;
import persistency.cassandra.config.CassandraConfig;
import play.Play;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CassandraSessionProxyFactory {
    private static CassandraSessionProxy sessionProxy;

    private CassandraSessionProxyFactory() {
    }

    public static CassandraSessionProxy getSessionProxy() {
        if (sessionProxy == null) {
            sessionProxy = new CassandraSessionProxy(
                    CassandraConfig.getContactPointsAsAddr(), CassandraConfig.getKeyspace(), CassandraConfig.getUser(),
                    CassandraConfig.getPassword(), getSchemaCQL());
        }

        return sessionProxy;
    }

    private static String getSchemaCQL() {
        Path evolutionPath = Play.application()
                .getFile("conf/CassandraEvolutions/1.cql").toPath();
        String schemaCQL = "";
        try {
            schemaCQL = new String(Files.readAllBytes(evolutionPath)).replace(
                    "\n", "");
        } catch (IOException e) {
        }
        return schemaCQL;
    }
}


text:
package org.semanticweb.elk.owl.managers;

import java.lang.ref.ReferenceQueue;

import org.semanticweb.elk.owl.interfaces.ElkNamedIndividual;
import org.semanticweb.elk.util.hashing.HashGenerator;

class WeakElkNamedIndividualWrapper extends WeakWrapper<ElkNamedIndividual> {

	WeakElkNamedIndividualWrapper(ElkNamedIndividual referent,
			ReferenceQueue<? super ElkNamedIndividual> q) {
		super(referent, q);
	}

	@Override
	protected int hashCode(ElkNamedIndividual referent) {
		return HashGenerator.combinedHashCode("ElkNamedIndividual", referent.getIri());
	}

	@Override
	protected boolean equal(ElkNamedIndividual referent, Object obj) {
		if (obj instanceof ElkNamedIndividual)
			return referent.getIri().equals(((ElkNamedIndividual) obj).getIri());
		return false;
	}

}


text:
<title>Ignored Title</title>

Hello, World!

This is some e-mail content.
  Even though it has whitespace and newlines, the e-mail converter
  will handle it correctly.

Even mismatched tags.

A div

Another div

A div
within a div

Another line
Yet another line

  A link


text:
/**
 * Created by josh on 8/24/15.
 */
var test = require('tape');
var Model = require('../src/model');
var Dom   = require('../src/dom');
var VirtualDoc = require('./virtualdom');
var Editor = require('../src/editor');
var Keystrokes = require('../src/keystrokes');

test('create a list item',function(t) {
    var dom_root = VirtualDoc.createElement('div');
    var editor = Editor.makeEditor(dom_root);
    var model  = editor.getModel();
    var blk = model.makeBlock().setStyle('body');
    blk.append(model.makeText("abc"));
    model.getRoot().append(blk);
    editor.syncDom();
    Model.print(editor.getModel());

    //verify
    t.equals(model.getRoot().childCount(),1);
    t.equals(model.getRoot().child(0).childCount(),1);
    t.equals(model.getRoot().child(0).style,'body');

    editor.setSelectionAtDocumentOffset(1,1);

    Keystrokes.changeBlockStyle(null,editor,'list-item');
    Model.print(editor.getModel());

    t.end();

});

test('back delete inside of a list item',function(t){
    var dom_root = VirtualDoc.createElement('div');
    var editor = Editor.makeEditor(dom_root);
    var model  = editor.getModel();
    var list = model.makeBlock().setStyle('ordered-list');
    model.getRoot().append(list);
    list.append(model.makeBlock().setStyle('list-item').append(model.makeText("abcdef")));
    list.append(model.makeBlock().setStyle('list-item').append(model.makeText("ghijkl")));
    editor.syncDom();
    Model.print(model);

    editor.setSelectionAtDocumentOffset(2,2);
    Keystrokes.deleteBackwards(null,editor);
    Model.print(model);

    t.end();
});

test('enter at end of document',function(t){
    var dom_root = VirtualDoc.createElement('div');
    var editor = Editor.makeEditor(dom_root);
    var model  = editor.getModel();
    var block = model.makeBlock();
    block.append(model.makeText("foo"));
    model.getRoot().append(block);
    Model.print(model);
    editor.syncDom();

    editor.setSelectionAtDocumentOffset(3,3,false);
    Keystrokes.splitLine(null,editor);

    Model.print(editor.getModel());

    t.end();
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <!-- MY Setting -->

    <beans:bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <beans:property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />

        <!--  Maqbool PC -->
        <!--   <beans:property name="url" value="jdbc:sqlserver://163.180.116.140:50251;instance=MAQBOOLUCLAB;databaseName=HibernateTutorialDB" /> -->

        <!-- Taqdir PC -->
        <beans:property name="url" value="jdbc:sqlserver://163.180.116.194:1433;instance=SQLEXPRESS;databaseName=MMIKATDB_V2_GCH" />
        <beans:property name="username" value="sa" />
        <!-- Maqbool PC -->
        <!--  <beans:property name="password" value="123" />  -->

        <!-- Taqdir PC -->
        <beans:property name="password" value="adminsa" />

    </beans:bean>

	<!-- Hibernate 4 SessionFactory Bean definition -->
	<beans:bean id="hibernate4AnnotatedSessionFactory"
	        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	        <beans:property name="dataSource" ref="dataSource1" />
	        <beans:property name="annotatedClasses">
	            <beans:list>
	            	 <!--<beans:value type="rule" />-->
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.SituationRuleWrapper</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.Situations</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.Rule</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.WellnessConceptsModel</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.Conclusion</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.Condition</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.User</beans:value>
	               <beans:value>org.uclab.mm.kcl.edkat.datamodel.WellnessConceptsRelationships</beans:value>
	            </beans:list>

	        </beans:property>
	        <beans:property name="hibernateProperties">
	            <beans:props>
	                <beans:prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</beans:prop>
	                <beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
	                <beans:prop key="hibernate.show_sql">false</beans:prop>
	                <beans:prop key="use_jdbc_metadata_defaults">false</beans:prop>
	                <beans:prop key="maxwait">10000</beans:prop>
		            <beans:prop key="maxidle">25</beans:prop>
		            <beans:prop key="minidle">5</beans:prop>
	            </beans:props>
	        </beans:property>
	  </beans:bean>

    <!-- Wrapper Class -->

     <beans:bean id="situationRuleWrapper" class="org.uclab.mm.kcl.edkat.datamodel.SituationRuleWrapper">
	    <beans:property name="rule" ref="rule"/>
	    <beans:property name="situations" ref="situations"/>
	    <beans:property name="user" ref="user"/>
	 </beans:bean>

    <!-- MY Setting -->
 	 <beans:bean id="rule" class="org.uclab.mm.kcl.edkat.datamodel.Rule">
	    <beans:property name="conclusionList" ref="conclusion"/>
	    <beans:property name="conditionList" ref="condition"/>
	 </beans:bean>

	 <beans:bean id="situations" class="org.uclab.mm.kcl.edkat.datamodel.Situations">
	    <beans:property name="rulesList" ref="rule"/>
	    <beans:property name="situationConditionList" ref="condition"/>
	 </beans:bean>

	 <beans:bean id="conclusion" class="org.uclab.mm.kcl.edkat.datamodel.Conclusion">

	  </beans:bean>
	  <beans:bean id="user" class="org.uclab.mm.kcl.edkat.datamodel.User">

	  </beans:bean>
	  <beans:bean id="condition" class="org.uclab.mm.kcl.edkat.datamodel.Condition">
	 	<beans:property name="ruleList" ref="rule"/>
	 	<beans:property name="situationList" ref="situations"/>
	  </beans:bean>

 	 <beans:bean id="ruleDAO" class="org.uclab.mm.kcl.edkat.dao.RuleDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="objRuleService" class="org.uclab.mm.kcl.edkat.service.RuleServiceImpl">
        <beans:property name="ruleDAO" ref="ruleDAO"></beans:property>
    </beans:bean>

    <beans:bean id="situationDAO" class="org.uclab.mm.kcl.edkat.dao.SituationDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="objSituationService" class="org.uclab.mm.kcl.edkat.service.SituationServiceImpl">
        <beans:property name="situationDAO" ref="situationDAO"></beans:property>
    </beans:bean>

    <beans:bean id="conditionDAO" class="org.uclab.mm.kcl.edkat.dao.ConditionDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="objConditionService" class="org.uclab.mm.kcl.edkat.service.ConditionServiceImpl">
        <beans:property name="conditionDAO" ref="conditionDAO"></beans:property>
    </beans:bean>

    <beans:bean id="userDAO" class="org.uclab.mm.kcl.edkat.dao.UserDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="objUserService" class="org.uclab.mm.kcl.edkat.service.UserServiceImpl">
        <beans:property name="userDAO" ref="userDAO"></beans:property>
    </beans:bean>

    <!-- <beans:bean id="ruleDAO" class="org.uclab.mm.kcl.edkat.dao.RuleDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean> -->

    <beans:bean id="wellnessConceptsModelDAO" class="org.uclab.mm.kcl.edkat.dao.WellnessConceptsModelDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="objWellnessConceptsModelService" class="org.uclab.mm.kcl.edkat.service.WellnessConceptsModelServiceImpl">
        <beans:property name="wellnessConceptsModelDAO" ref="wellnessConceptsModelDAO"></beans:property>
    </beans:bean>

    <beans:bean id="conclusionDAO" class="org.uclab.mm.kcl.edkat.dao.ConclusionDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="objConclusionService" class="org.uclab.mm.kcl.edkat.service.ConclusionServiceImpl">
        <beans:property name="conclusionDAO" ref="conclusionDAO"></beans:property>
    </beans:bean>

    <context:component-scan base-package="org.uclab.mm.kcl.edkat.controller" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>

</beans:beans>


text:
Returns an initializer performing "Xavier" initialization for weights.

This function implements the weight initialization from:

Xavier Glorot and Yoshua Bengio (2010):
         Understanding the difficulty of training deep feedforward neural
         networks. International conference on artificial intelligence and
         statistics.

This initializer is designed to keep the scale of the gradients roughly the
same in all layers. In uniform distribution this ends up being the range:
`x = sqrt(6. / (in + out)); [-x, x]` and for normal distribution a standard
deviation of `sqrt(3. / (in + out))` is used.

##### Args:

*  <b>`uniform`</b>: Whether to use uniform or normal distributed random initialization.
*  <b>`seed`</b>: A Python integer. Used to create random seeds. See
    [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
    for behavior.
*  <b>`dtype`</b>: The data type. Only floating point types are supported.

##### Returns:

  An initializer for a weight matrix.


text:
package com.communote.server.core.vo.query.java.note;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.communote.common.matcher.Matcher;
import com.communote.server.api.core.common.NotFoundException;
import com.communote.server.api.core.note.NoteData;
import com.communote.server.api.core.property.PropertyManagement;
import com.communote.server.api.core.property.PropertyType;
import com.communote.server.api.core.property.StringPropertyTO;
import com.communote.server.api.core.security.AuthorizationException;
import com.communote.server.core.vo.query.filter.PropertyFilter;

/**
 * Matcher for property filters like content types.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class PropertyFilterMatcher extends Matcher<NoteData> {

    /** Logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyFilterMatcher.class);

    private Collection<PropertyFilter> filters = new HashSet<PropertyFilter>();
    private final PropertyManagement propertyManagement;

    /**
     * Constructor.
     *
     * @param propertyManagement
     *            The PropertyManagement to use.
     *
     * @param filters
     *            The filters to match. All filters are AND combined. Might be null, which means all
     *            filters will match.
     */
    public PropertyFilterMatcher(PropertyManagement propertyManagement,
            Collection<PropertyFilter> filters) {
        this.propertyManagement = propertyManagement;
        if (filters != null) {
            this.filters = filters;
        }
    }

    /**
     * Constructor.
     *
     * @param propertyManagement
     *            The PropertyManagement to use.
     * @param filters
     *            The filters to match. All filters are AND combined. Might be null, which means all
     *            filters will match.
     */
    public PropertyFilterMatcher(PropertyManagement propertyManagement, PropertyFilter... filters) {
        this.propertyManagement = propertyManagement;
        if (filters != null) {
            for (PropertyFilter filter : filters) {
                this.filters.add(filter);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean matches(NoteData entity) {
        if (filters.isEmpty()) {
            return true;
        }
        try {
            Set<StringPropertyTO> noteProperties = propertyManagement.getAllObjectProperties(
                    PropertyType.NoteProperty, entity.getId());
            // Filters are AND combined,
            // Properties within filters are OR combined.
            boolean result = true;
            outer: for (PropertyFilter filter : filters) {
                for (StringPropertyTO noteProperty : noteProperties) {
                    if (filter.matches(noteProperty.getKeyGroup(), noteProperty.getPropertyKey(),
                            noteProperty.getPropertyValue())) {
                        continue outer;
                    }
                }
                result = false;
                break outer;
            }
            return result;
        } catch (NotFoundException e) {
            LOGGER.warn("The note with id {} can't be found. It might have been deleted.",
                    entity.getId());
        } catch (AuthorizationException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return false;
    }
}