text:
namespace chromeos {

namespace {

// A dictionary that maps user_ids to old user image data with images stored in
// PNG format. Deprecated.
// TODO(ivankr): remove this const char after migration is gone.
const char kUserImages[] = "UserImages";

// A dictionary that maps user_ids to user image data with images stored in
// JPEG format.
const char kUserImageProperties[] = "user_image_info";

// Names of user image properties.
const char kImagePathNodeName[] = "path";
const char kImageIndexNodeName[] = "index";
const char kImageURLNodeName[] = "url";

// Delay betweeen user login and attempt to update user's profile data.
const int kProfileDataDownloadDelaySec = 10;

// Interval betweeen retries to update user's profile data.
const int kProfileDataDownloadRetryIntervalSec = 300;

// Delay betweeen subsequent profile refresh attempts (24 hrs).
const int kProfileRefreshIntervalSec = 24 * 3600;

const char kSafeImagePathExtension[] = ".jpg";

// Enum for reporting histograms about profile picture download.
enum ProfileDownloadResult {
  kDownloadSuccessChanged,
  kDownloadSuccess,
  kDownloadFailure,
  kDownloadDefault,
  kDownloadCached,

  // Must be the last, convenient count.
  kDownloadResultsCount
};

// Time histogram prefix for a cached profile image download.
const char kProfileDownloadCachedTime[] =
    "UserImage.ProfileDownloadTime.Cached";
// Time histogram prefix for the default profile image download.
const char kProfileDownloadDefaultTime[] =
    "UserImage.ProfileDownloadTime.Default";
// Time histogram prefix for a failed profile image download.
const char kProfileDownloadFailureTime[] =
    "UserImage.ProfileDownloadTime.Failure";
// Time histogram prefix for a successful profile image download.
const char kProfileDownloadSuccessTime[] =
    "UserImage.ProfileDownloadTime.Success";
// Time histogram suffix for a profile image download after login.
const char kProfileDownloadReasonLoggedIn[] = "LoggedIn";
// Time histogram suffix for a profile image download when the user chooses the
// profile image but it has not been downloaded yet.
const char kProfileDownloadReasonProfileImageChosen[] = "ProfileImageChosen";
// Time histogram suffix for a scheduled profile image download.
const char kProfileDownloadReasonScheduled[] = "Scheduled";
// Time histogram suffix for a profile image download retry.
const char kProfileDownloadReasonRetry[] = "Retry";

static bool g_ignore_profile_data_download_delay_ = false;

// Add a histogram showing the time it takes to download profile image.
// Separate histograms are reported for each download |reason| and |result|.
void AddProfileImageTimeHistogram(ProfileDownloadResult result,
                                  const std::string& download_reason,
                                  const base::TimeDelta& time_delta) {
  std::string histogram_name;
  switch (result) {
    case kDownloadFailure:
      histogram_name = kProfileDownloadFailureTime;
      break;
    case kDownloadDefault:
      histogram_name = kProfileDownloadDefaultTime;
      break;
    case kDownloadSuccess:
      histogram_name = kProfileDownloadSuccessTime;
      break;
    case kDownloadCached:
      histogram_name = kProfileDownloadCachedTime;
      break;
    default:
      NOTREACHED();
  }
  if (!download_reason.empty()) {
    histogram_name += ".";
    histogram_name += download_reason;
  }

  static const base::TimeDelta min_time = base::TimeDelta::FromMilliseconds(1);
  static const base::TimeDelta max_time = base::TimeDelta::FromSeconds(50);
  const size_t bucket_count(50);

  base::HistogramBase* counter = base::Histogram::FactoryTimeGet(
      histogram_name, min_time, max_time, bucket_count,
      base::HistogramBase::kUmaTargetedHistogramFlag);
  counter->AddTime(time_delta);

  DVLOG(1) << "Profile image download time: " << time_delta.InSecondsF();
}

// Converts |image_index| to UMA histogram value.
int ImageIndexToHistogramIndex(int image_index) {
  switch (image_index) {
    case User::kExternalImageIndex:
      // TODO(ivankr): Distinguish this from selected from file.
      return kHistogramImageFromCamera;
    case User::kProfileImageIndex:
      return kHistogramImageFromProfile;
    default:
      return image_index;
  }
}

bool SaveImage(const UserImage& user_image, const base::FilePath& image_path) {
  UserImage safe_image;
  const UserImage::RawImage* encoded_image = NULL;
  if (!user_image.is_safe_format()) {
    safe_image = UserImage::CreateAndEncode(user_image.image());
    encoded_image = &safe_image.raw_image();
    UMA_HISTOGRAM_MEMORY_KB("UserImage.RecodedJpegSize", encoded_image->size());
  } else if (user_image.has_raw_image()) {
    encoded_image = &user_image.raw_image();
  } else {
    NOTREACHED() << "Raw image missing.";
    return false;
  }

  if (!encoded_image->size() ||
      file_util::WriteFile(image_path,
                           reinterpret_cast<const char*>(&(*encoded_image)[0]),
                           encoded_image->size()) == -1) {
    LOG(ERROR) << "Failed to save image to file.";
    return false;
  }

  return true;
}

}  // namespace

// static
void UserImageManager::RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterDictionaryPref(kUserImages);
  registry->RegisterDictionaryPref(kUserImageProperties);
}

// Every image load or update is encapsulated by a Job. The Job is allowed to
// perform tasks on background threads or in helper processes but:
// * Changes to User objects and local state as well as any calls to the
//   |parent_| must be performed on the thread that the Job is created on only.
// * File writes and deletions must be performed via the |parent_|'s
//   |background_task_runner_| only.
//
// Only one of the Load*() and Set*() methods may be called per Job.
class UserImageManagerImpl::Job {
 public:
  // The |Job| will update the |user| object for |user_id|.
  Job(UserImageManagerImpl* parent, const std::string& user_id);
  ~Job();

  // Loads the image at |image_path| or one of the default images, depending on
  // |image_index|, and updates the |user| object for |user_id_| with the new
  // image.
  void LoadImage(base::FilePath image_path,
                 const int image_index,
                 const GURL& image_url);

  // Sets the user image for |user_id_| in local state to the default image
  // indicated by |default_image_index|. Also updates the |user| object for
  // |user_id_| with the new image.
  void SetToDefaultImage(int default_image_index);

  // Saves the |user_image| to disk and sets the user image for |user_id_| in
  // local state to that image. Also updates the |user| object for |user_id_|
  // with the new image.
  void SetToImage(int image_index, const UserImage& user_image);

  // Decodes the JPEG image |data|, crops and resizes the image, saves it to
  // disk and sets the user image for |user_id_| in local state to that image.
  // Also updates the |user| object for |user_id_| with the new image.
  void SetToImageData(scoped_ptr<std::string> data);

  // Loads the image at |path|, transcodes it to JPEG format, saves the image to
  // disk and sets the user image for |user_id_| in local state to that image.
  // If |resize| is true, the image is cropped and resized before transcoding.
  // Also updates the |user| object for |user_id_| with the new image.
  void SetToPath(const base::FilePath& path,
                 int image_index,
                 const GURL& image_url,
                 bool resize);

 private:
  // Called back after an image has been loaded from disk.
  void OnLoadImageDone(bool save, const UserImage& user_image);

  // Updates the |user| object for |user_id_| with |user_image_|.
  void UpdateUser();

  // Saves |user_image_| to disk in JPEG format. Local state will be updated
  // when a callback indicates that the image has been saved.
  void SaveImageAndUpdateLocalState();

  // Called back after the |user_image_| has been saved to disk. Updates the
  // user image information for |user_id_| in local state. The information is
  // only updated if |success| is true (indicating that the image was saved
  // successfully) or the user image is the profile image (indicating that even
  // if the image could not be saved because it is not available right now, it
  // will be downloaded eventually).
  void OnSaveImageDone(bool success);

  // Updates the user image for |user_id_| in local state, setting it to
  // one of the default images or the saved |user_image_|, depending on
  // |image_index_|.
  void UpdateLocalState();

  // Notifies the |parent_| that the Job is done.
  void NotifyJobDone();

  UserImageManagerImpl* parent_;
  const std::string user_id_;

  // Whether one of the Load*() or Set*() methods has been run already.
  bool run_;

  int image_index_;
  GURL image_url_;
  base::FilePath image_path_;

  UserImage user_image_;

  base::WeakPtrFactory<Job> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(Job);
};

UserImageManagerImpl::Job::Job(UserImageManagerImpl* parent,
                               const std::string& user_id)
    : parent_(parent),
      user_id_(user_id),
      run_(false),
      weak_factory_(this) {
}

UserImageManagerImpl::Job::~Job() {
}

void UserImageManagerImpl::Job::LoadImage(base::FilePath image_path,
                                          const int image_index,
                                          const GURL& image_url) {
  DCHECK(!run_);
  run_ = true;

  image_index_ = image_index;
  image_url_ = image_url;
  image_path_ = image_path;

  if (image_index_ >= 0 && image_index_ < kDefaultImagesCount) {
    // Load one of the default images. This happens synchronously.
    user_image_ = UserImage(GetDefaultImage(image_index_));
    UpdateUser();
    NotifyJobDone();
  } else if (image_index_ == User::kExternalImageIndex ||
             image_index_ == User::kProfileImageIndex) {
    // Load the user image from a file referenced by |image_path|. This happens
    // asynchronously. The JPEG image loader can be used here because
    // LoadImage() is called only for users whose user image has previously
    // been set by one of the Set*() methods, which transcode to JPEG format.
    DCHECK(!image_path_.empty());
    parent_->image_loader_->Start(image_path_.value(),
                                  0,
                                  base::Bind(&Job::OnLoadImageDone,
                                             weak_factory_.GetWeakPtr(),
                                             false));
  } else {
    NOTREACHED();
    NotifyJobDone();
  }
}

void UserImageManagerImpl::Job::SetToDefaultImage(int default_image_index) {
  DCHECK(!run_);
  run_ = true;

  DCHECK_LE(0, default_image_index);
  DCHECK_GT(kDefaultImagesCount, default_image_index);

  image_index_ = default_image_index;
  user_image_ = UserImage(GetDefaultImage(image_index_));

  UpdateUser();
  UpdateLocalState();
  NotifyJobDone();
}

void UserImageManagerImpl::Job::SetToImage(int image_index,
                                           const UserImage& user_image) {
  DCHECK(!run_);
  run_ = true;

  DCHECK(image_index == User::kExternalImageIndex ||
         image_index == User::kProfileImageIndex);

  image_index_ = image_index;
  user_image_ = user_image;

  UpdateUser();
  SaveImageAndUpdateLocalState();
}

void UserImageManagerImpl::Job::SetToImageData(scoped_ptr<std::string> data) {
  DCHECK(!run_);
  run_ = true;

  image_index_ = User::kExternalImageIndex;

  // This method uses the image_loader_, not the unsafe_image_loader_:
  // * This is necessary because the method is used to update the user image
  //   whenever the policy for a user is set. In the case of device-local
  //   accounts, policy may change at any time, even if the user is not
  //   currently logged in (and thus, the unsafe_image_loader_ may not be used).
  // * This is possible because only JPEG |data| is accepted. No support for
  //   other image file formats is needed.
  // * This is safe because the image_loader_ employs a hardened JPEG decoder
  //   that protects against malicious invalid image data being used to attack
  //   the login screen or another user session currently in progress.
  parent_->image_loader_->Start(data.Pass(),
                                login::kMaxUserImageSize,
                                base::Bind(&Job::OnLoadImageDone,
                                           weak_factory_.GetWeakPtr(),
                                           true));
}

void UserImageManagerImpl::Job::SetToPath(const base::FilePath& path,
                                          int image_index,
                                          const GURL& image_url,
                                          bool resize) {
  DCHECK(!run_);
  run_ = true;

  image_index_ = image_index;
  image_url_ = image_url;

  DCHECK(!path.empty());
  parent_->unsafe_image_loader_->Start(path.value(),
                                       resize ? login::kMaxUserImageSize : 0,
                                       base::Bind(&Job::OnLoadImageDone,
                                                  weak_factory_.GetWeakPtr(),
                                                  true));
}

void UserImageManagerImpl::Job::OnLoadImageDone(bool save,
                                                const UserImage& user_image) {
  user_image_ = user_image;
  UpdateUser();
  if (save)
    SaveImageAndUpdateLocalState();
  else
    NotifyJobDone();
}

void UserImageManagerImpl::Job::UpdateUser() {
  User* user = parent_->user_manager_->FindUserAndModify(user_id_);
  if (!user)
    return;

  if (!user_image_.image().isNull())
    user->SetImage(user_image_, image_index_);
  else
    user->SetStubImage(image_index_, false);
  user->SetImageURL(image_url_);

  parent_->OnJobChangedUserImage(user);
}

void UserImageManagerImpl::Job::SaveImageAndUpdateLocalState() {
  base::FilePath user_data_dir;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  image_path_ = user_data_dir.Append(user_id_ + kSafeImagePathExtension);

  base::PostTaskAndReplyWithResult(
      parent_->background_task_runner_,
      FROM_HERE,
      base::Bind(&SaveImage, user_image_, image_path_),
      base::Bind(&Job::OnSaveImageDone, weak_factory_.GetWeakPtr()));
}

void UserImageManagerImpl::Job::OnSaveImageDone(bool success) {
  if (success || image_index_ == User::kProfileImageIndex)
    UpdateLocalState();
  NotifyJobDone();
}

void UserImageManagerImpl::Job::UpdateLocalState() {
  // Ignore if data stored or cached outside the user's cryptohome is to be
  // treated as ephemeral.
  if (parent_->user_manager_->IsUserNonCryptohomeDataEphemeral(user_id_))
    return;

  scoped_ptr<base::DictionaryValue> entry(new base::DictionaryValue);
  entry->Set(kImagePathNodeName, new base::StringValue(image_path_.value()));
  entry->Set(kImageIndexNodeName, new base::FundamentalValue(image_index_));
  if (!image_url_.is_empty())
    entry->Set(kImageURLNodeName, new StringValue(image_url_.spec()));
  DictionaryPrefUpdate update(g_browser_process->local_state(),
                              kUserImageProperties);
  update->SetWithoutPathExpansion(user_id_, entry.release());

  parent_->user_manager_->NotifyLocalStateChanged();
}

void UserImageManagerImpl::Job::NotifyJobDone() {
  parent_->OnJobDone(user_id_);
}

UserImageManagerImpl::UserImageManagerImpl(CrosSettings* cros_settings,
                                           UserManager* user_manager)
    : user_manager_(user_manager),
      downloading_profile_image_(false),
      profile_image_requested_(false),
      weak_factory_(this) {
  base::SequencedWorkerPool* blocking_pool =
      content::BrowserThread::GetBlockingPool();
  background_task_runner_ =
      blocking_pool->GetSequencedTaskRunnerWithShutdownBehavior(
          blocking_pool->GetSequenceToken(),
          base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN);
  image_loader_ = new UserImageLoader(ImageDecoder::ROBUST_JPEG_CODEC,
                                      background_task_runner_);
  unsafe_image_loader_ = new UserImageLoader(ImageDecoder::DEFAULT_CODEC,
                                             background_task_runner_);
  policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
      cros_settings,
      user_manager,
      g_browser_process->browser_policy_connector()->
          GetDeviceLocalAccountPolicyService(),
      policy::key::kUserAvatarImage,
      this));
  policy_observer_->Init();
}

UserImageManagerImpl::~UserImageManagerImpl() {
}

void UserImageManagerImpl::LoadUserImages(const UserList& users) {
  PrefService* local_state = g_browser_process->local_state();
  const DictionaryValue* prefs_images_unsafe =
      local_state->GetDictionary(kUserImages);
  const DictionaryValue* prefs_images =
      local_state->GetDictionary(kUserImageProperties);
  if (!prefs_images && !prefs_images_unsafe)
    return;

  for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
    User* user = *it;
    const std::string& user_id = user->email();
    bool needs_migration = false;

    // If entries are found in both |prefs_images_unsafe| and |prefs_images|,
    // |prefs_images| is honored for now but |prefs_images_unsafe| will be
    // migrated, overwriting the |prefs_images| entry, when the user logs in.
    const base::DictionaryValue* image_properties = NULL;
    if (prefs_images_unsafe) {
      needs_migration = prefs_images_unsafe->GetDictionaryWithoutPathExpansion(
          user_id, &image_properties);
      if (needs_migration)
        users_to_migrate_.insert(user_id);
    }
    if (prefs_images) {
      prefs_images->GetDictionaryWithoutPathExpansion(user_id,
                                                      &image_properties);
    }

    // If the user image for |user_id| is managed by policy and the policy-set
    // image is being loaded and persisted right now, let that job continue. It
    // will update the user image when done.
    if (IsUserImageManaged(user_id) && ContainsKey(jobs_, user_id))
      continue;

    if (!image_properties) {
      SetInitialUserImage(user_id);
      continue;
    }

    int image_index = User::kInvalidImageIndex;
    image_properties->GetInteger(kImageIndexNodeName, &image_index);
    if (image_index >= 0 && image_index < kDefaultImagesCount) {
      user->SetImage(UserImage(GetDefaultImage(image_index)),
                     image_index);
      continue;
    }

    if (image_index != User::kExternalImageIndex &&
        image_index != User::kProfileImageIndex) {
      NOTREACHED();
      continue;
    }

    std::string image_url_string;
    image_properties->GetString(kImageURLNodeName, &image_url_string);
    GURL image_url(image_url_string);
    std::string image_path;
    image_properties->GetString(kImagePathNodeName, &image_path);

    user->SetImageURL(image_url);
    user->SetStubImage(image_index, true);
    DCHECK(!image_path.empty() || image_index == User::kProfileImageIndex);
    if (image_path.empty() || needs_migration) {
      // Return if either of the following is true:
      // * The profile image is to be used but has not been downloaded yet. The
      //   profile image will be downloaded after login.
      // * The image needs migration. Migration will be performed after login.
      continue;
    }

    linked_ptr<Job>& job = jobs_[user_id];
    job.reset(new Job(this, user_id));
    job->LoadImage(base::FilePath(image_path), image_index, image_url);
  }
}

void UserImageManagerImpl::UserLoggedIn(const std::string& user_id,
                                        bool user_is_new,
                                        bool user_is_local) {
  User* user = user_manager_->GetLoggedInUser();
  if (user_is_new) {
    if (!user_is_local)
      SetInitialUserImage(user_id);
  } else {
    UMA_HISTOGRAM_ENUMERATION("UserImage.LoggedIn",
                              ImageIndexToHistogramIndex(user->image_index()),
                              kHistogramImagesCount);

    if (!IsUserImageManaged(user_id) &&
        ContainsKey(users_to_migrate_, user_id)) {
      const DictionaryValue* prefs_images_unsafe =
          g_browser_process->local_state()->GetDictionary(kUserImages);
      const base::DictionaryValue* image_properties = NULL;
      if (prefs_images_unsafe->GetDictionaryWithoutPathExpansion(
              user_id, &image_properties)) {
        std::string image_path;
        image_properties->GetString(kImagePathNodeName, &image_path);
        linked_ptr<Job>& job = jobs_[user_id];
        job.reset(new Job(this, user_id));
        if (!image_path.empty()) {
          VLOG(0) << "Loading old user image, then migrating it.";
          job->SetToPath(base::FilePath(image_path),
                         user->image_index(),
                         user->image_url(),
                         false);
        } else {
          job->SetToDefaultImage(user->image_index());
        }
      }
    }
  }

  // Reset the downloaded profile image as a new user logged in.
  downloaded_profile_image_ = gfx::ImageSkia();
  profile_image_url_ = GURL();
  profile_image_requested_ = false;

  if (user_manager_->IsLoggedInAsRegularUser()) {
    TryToInitDownloadedProfileImage();

    // Schedule an initial download of the profile data (full name and
    // optionally image).
    profile_download_one_shot_timer_.Start(
        FROM_HERE,
        g_ignore_profile_data_download_delay_ ?
            base::TimeDelta() :
            base::TimeDelta::FromSeconds(kProfileDataDownloadDelaySec),
        base::Bind(&UserImageManagerImpl::DownloadProfileData,
                   base::Unretained(this),
                   kProfileDownloadReasonLoggedIn));
    // Schedule periodic refreshes of the profile data.
    profile_download_periodic_timer_.Start(
        FROM_HERE,
        base::TimeDelta::FromSeconds(kProfileRefreshIntervalSec),
        base::Bind(&UserImageManagerImpl::DownloadProfileData,
                   base::Unretained(this),
                   kProfileDownloadReasonScheduled));
  } else {
    profile_download_one_shot_timer_.Stop();
    profile_download_periodic_timer_.Stop();
  }

  user_image_sync_observer_.reset();
  TryToCreateImageSyncObserver();
}

void UserImageManagerImpl::SaveUserDefaultImageIndex(const std::string& user_id,
                                                     int default_image_index) {
  if (IsUserImageManaged(user_id))
    return;
  linked_ptr<Job>& job = jobs_[user_id];
  job.reset(new Job(this, user_id));
  job->SetToDefaultImage(default_image_index);
}

void UserImageManagerImpl::SaveUserImage(const std::string& user_id,
                                         const UserImage& user_image) {
  if (IsUserImageManaged(user_id))
    return;
  linked_ptr<Job>& job = jobs_[user_id];
  job.reset(new Job(this, user_id));
  job->SetToImage(User::kExternalImageIndex, user_image);
}

void UserImageManagerImpl::SaveUserImageFromFile(const std::string& user_id,
                                                 const base::FilePath& path) {
  if (IsUserImageManaged(user_id))
    return;
  linked_ptr<Job>& job = jobs_[user_id];
  job.reset(new Job(this, user_id));
  job->SetToPath(path, User::kExternalImageIndex, GURL(), true);
}

void UserImageManagerImpl::SaveUserImageFromProfileImage(
    const std::string& user_id) {
  if (IsUserImageManaged(user_id))
    return;
  // Use the profile image if it has been downloaded already. Otherwise, use a
  // stub image (gray avatar).
  linked_ptr<Job>& job = jobs_[user_id];
  job.reset(new Job(this, user_id));
  job->SetToImage(User::kProfileImageIndex,
                  downloaded_profile_image_.isNull() ?
                      UserImage() :
                      UserImage::CreateAndEncode(downloaded_profile_image_));
  // If no profile image has been downloaded yet, ensure that a download is
  // started.
  if (downloaded_profile_image_.isNull())
    DownloadProfileData(kProfileDownloadReasonProfileImageChosen);
}

void UserImageManagerImpl::DeleteUserImage(const std::string& user_id) {
  jobs_.erase(user_id);
  DeleteUserImageAndLocalStateEntry(user_id, kUserImages);
  DeleteUserImageAndLocalStateEntry(user_id, kUserImageProperties);
}

void UserImageManagerImpl::DownloadProfileImage(const std::string& reason) {
  profile_image_requested_ = true;
  DownloadProfileData(reason);
}

const gfx::ImageSkia& UserImageManagerImpl::DownloadedProfileImage() const {
  return downloaded_profile_image_;
}

UserImageSyncObserver* UserImageManagerImpl::GetSyncObserver() const {
  return user_image_sync_observer_.get();
}

void UserImageManagerImpl::Shutdown() {
  profile_downloader_.reset();
  user_image_sync_observer_.reset();
  policy_observer_.reset();
}

void UserImageManagerImpl::OnExternalDataSet(const std::string& policy,
                                             const std::string& user_id) {
  DCHECK_EQ(policy::key::kUserAvatarImage, policy);
  if (IsUserImageManaged(user_id))
    return;
  users_with_managed_images_.insert(user_id);

  jobs_.erase(user_id);

  const User* logged_in_user = user_manager_->GetLoggedInUser();
  // If the user image for the currently logged-in user became managed, stop the
  // sync observer so that the policy-set image does not get synced out.
  if (logged_in_user && logged_in_user->email() == user_id)
    user_image_sync_observer_.reset();
}

void UserImageManagerImpl::OnExternalDataCleared(const std::string& policy,
                                                 const std::string& user_id) {
  DCHECK_EQ(policy::key::kUserAvatarImage, policy);
  users_with_managed_images_.erase(user_id);
  TryToCreateImageSyncObserver();
}

void UserImageManagerImpl::OnExternalDataFetched(const std::string& policy,
                                                 const std::string& user_id,
                                                 scoped_ptr<std::string> data) {
  DCHECK_EQ(policy::key::kUserAvatarImage, policy);
  DCHECK(IsUserImageManaged(user_id));
  if (data) {
    linked_ptr<Job>& job = jobs_[user_id];
    job.reset(new Job(this, user_id));
    job->SetToImageData(data.Pass());
  }
}

// static
void UserImageManagerImpl::IgnoreProfileDataDownloadDelayForTesting() {
  g_ignore_profile_data_download_delay_ = true;
}

void UserImageManagerImpl::StopPolicyObserverForTesting() {
  policy_observer_.reset();
}

bool UserImageManagerImpl::NeedsProfilePicture() const {
  return downloading_profile_image_;
}

int UserImageManagerImpl::GetDesiredImageSideLength() const {
  return GetCurrentUserImageSize();
}

Profile* UserImageManagerImpl::GetBrowserProfile() {
  return ProfileManager::GetDefaultProfile();
}

std::string UserImageManagerImpl::GetCachedPictureURL() const {
  return profile_image_url_.spec();
}

void UserImageManagerImpl::OnProfileDownloadSuccess(
    ProfileDownloader* downloader) {
  // Ensure that the |profile_downloader_| is deleted when this method returns.
  scoped_ptr<ProfileDownloader> profile_downloader(
      profile_downloader_.release());
  DCHECK_EQ(downloader, profile_downloader.get());

  const User* user = user_manager_->GetLoggedInUser();
  const std::string& user_id = user->email();

  user_manager_->UpdateUserAccountData(
      user_id,
      UserManager::UserAccountData(downloader->GetProfileFullName(),
                                   downloader->GetProfileGivenName(),
                                   downloader->GetProfileLocale()));
  if (!downloading_profile_image_)
    return;

  ProfileDownloadResult result = kDownloadFailure;
  switch (downloader->GetProfilePictureStatus()) {
    case ProfileDownloader::PICTURE_SUCCESS:
      result = kDownloadSuccess;
      break;
    case ProfileDownloader::PICTURE_CACHED:
      result = kDownloadCached;
      break;
    case ProfileDownloader::PICTURE_DEFAULT:
      result = kDownloadDefault;
      break;
    default:
      NOTREACHED();
  }

  UMA_HISTOGRAM_ENUMERATION("UserImage.ProfileDownloadResult",
                            result,
                            kDownloadResultsCount);
  DCHECK(!profile_image_load_start_time_.is_null());
  AddProfileImageTimeHistogram(
      result,
      profile_image_download_reason_,
      base::TimeTicks::Now() - profile_image_load_start_time_);

  // Ignore the image if it is no longer needed.
  if (!NeedProfileImage())
    return;

  if (result == kDownloadDefault) {
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_PROFILE_IMAGE_UPDATE_FAILED,
        content::Source<UserImageManager>(this),
        content::NotificationService::NoDetails());
  } else {
    profile_image_requested_ = false;
  }

  // Nothing to do if the picture is cached or is the default avatar.
  if (result != kDownloadSuccess)
    return;

  downloaded_profile_image_ = gfx::ImageSkia::CreateFrom1xBitmap(
      downloader->GetProfilePicture());
  profile_image_url_ = GURL(downloader->GetProfilePictureURL());

  if (user->image_index() == User::kProfileImageIndex) {
    VLOG(1) << "Updating profile image for logged-in user.";
    UMA_HISTOGRAM_ENUMERATION("UserImage.ProfileDownloadResult",
                              kDownloadSuccessChanged,
                              kDownloadResultsCount);
    // This will persist |downloaded_profile_image_| to disk.
    SaveUserImageFromProfileImage(user_id);
  }

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PROFILE_IMAGE_UPDATED,
      content::Source<UserImageManager>(this),
      content::Details<const gfx::ImageSkia>(&downloaded_profile_image_));
}

void UserImageManagerImpl::OnProfileDownloadFailure(
    ProfileDownloader* downloader,
    ProfileDownloaderDelegate::FailureReason reason) {
  DCHECK_EQ(downloader, profile_downloader_.get());
  profile_downloader_.reset();

  if (downloading_profile_image_) {
    UMA_HISTOGRAM_ENUMERATION("UserImage.ProfileDownloadResult",
                              kDownloadFailure,
                              kDownloadResultsCount);
    DCHECK(!profile_image_load_start_time_.is_null());
    AddProfileImageTimeHistogram(
        kDownloadFailure,
        profile_image_download_reason_,
        base::TimeTicks::Now() - profile_image_load_start_time_);
  }

  if (reason == ProfileDownloaderDelegate::NETWORK_ERROR) {
    // Retry download after a delay if a network error occurred.
    profile_download_one_shot_timer_.Start(
        FROM_HERE,
        base::TimeDelta::FromSeconds(kProfileDataDownloadRetryIntervalSec),
        base::Bind(&UserImageManagerImpl::DownloadProfileData,
                   base::Unretained(this),
                   kProfileDownloadReasonRetry));
  }

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PROFILE_IMAGE_UPDATE_FAILED,
      content::Source<UserImageManager>(this),
      content::NotificationService::NoDetails());
}

bool UserImageManagerImpl::IsUserImageManaged(
    const std::string& user_id) const {
  return ContainsKey(users_with_managed_images_, user_id);
}

void UserImageManagerImpl::SetInitialUserImage(const std::string& user_id) {
  // Choose a random default image.
  SaveUserDefaultImageIndex(user_id,
                            base::RandInt(kFirstDefaultImageIndex,
                                          kDefaultImagesCount - 1));
}

void UserImageManagerImpl::TryToInitDownloadedProfileImage() {
  const User* user = user_manager_->GetLoggedInUser();
  if (user->image_index() == User::kProfileImageIndex &&
      downloaded_profile_image_.isNull() &&
      !user->image_is_stub()) {
    // Initialize the |downloaded_profile_image_| for the currently logged-in
    // user if it has not been initialized already, the user image is the
    // profile image and the user image has been loaded successfully.
    VLOG(1) << "Profile image initialized from disk.";
    downloaded_profile_image_ = user->image();
    profile_image_url_ = user->image_url();
  }
}

bool UserImageManagerImpl::NeedProfileImage() const {
  return user_manager_->IsLoggedInAsRegularUser() &&
         (user_manager_->GetLoggedInUser()->image_index() ==
              User::kProfileImageIndex ||
          profile_image_requested_);
}

void UserImageManagerImpl::DownloadProfileData(const std::string& reason) {
  // GAIA profiles exist for regular users only.
  if (!user_manager_->IsLoggedInAsRegularUser())
    return;

  // If a download is already in progress, allow it to continue, with one
  // exception: If the current download does not include the profile image but
  // the image has since become necessary, start a new download that includes
  // the profile image.
  if (profile_downloader_ &&
      (downloading_profile_image_ || !NeedProfileImage())) {
    return;
  }

  downloading_profile_image_ = NeedProfileImage();
  profile_image_download_reason_ = reason;
  profile_image_load_start_time_ = base::TimeTicks::Now();
  profile_downloader_.reset(new ProfileDownloader(this));
  profile_downloader_->Start();
}

void UserImageManagerImpl::DeleteUserImageAndLocalStateEntry(
    const std::string& user_id,
    const char* prefs_dict_root) {
  DictionaryPrefUpdate update(g_browser_process->local_state(),
                              prefs_dict_root);
  const base::DictionaryValue* image_properties;
  if (!update->GetDictionaryWithoutPathExpansion(user_id, &image_properties))
    return;

  std::string image_path;
  image_properties->GetString(kImagePathNodeName, &image_path);
  if (!image_path.empty()) {
    background_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(base::IgnoreResult(&base::DeleteFile),
                   base::FilePath(image_path),
                   false));
  }
  update->RemoveWithoutPathExpansion(user_id, NULL);
}

void UserImageManagerImpl::OnJobChangedUserImage(const User* user) {
  if (user == user_manager_->GetLoggedInUser())
    TryToInitDownloadedProfileImage();

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED,
      content::Source<UserImageManagerImpl>(this),
      content::Details<const User>(user));
}

void UserImageManagerImpl::OnJobDone(const std::string& user_id) {
  std::map<std::string, linked_ptr<Job> >::iterator it =
      jobs_.find(user_id);
  if (it != jobs_.end()) {
    base::MessageLoopProxy::current()->DeleteSoon(FROM_HERE,
                                                  it->second.release());
    jobs_.erase(it);
  } else {
    NOTREACHED();
  }

  if (!ContainsKey(users_to_migrate_, user_id))
    return;
  // Migration completed for |user_id|.
  users_to_migrate_.erase(user_id);

  const DictionaryValue* prefs_images_unsafe =
      g_browser_process->local_state()->GetDictionary(kUserImages);
  const base::DictionaryValue* image_properties = NULL;
  if (!prefs_images_unsafe->GetDictionaryWithoutPathExpansion(
          user_id, &image_properties)) {
    NOTREACHED();
    return;
  }

  int image_index = User::kInvalidImageIndex;
  image_properties->GetInteger(kImageIndexNodeName, &image_index);
  UMA_HISTOGRAM_ENUMERATION("UserImage.Migration",
                            ImageIndexToHistogramIndex(image_index),
                            kHistogramImagesCount);

  std::string image_path;
  image_properties->GetString(kImagePathNodeName, &image_path);
  if (!image_path.empty()) {
    // If an old image exists, delete it and remove |user_id| from the old prefs
    // dictionary only after the deletion has completed. This ensures that no
    // orphaned image is left behind if the browser crashes before the deletion
    // has been performed: In that case, local state will be unchanged and the
    // migration will be run again on the user's next login.
    background_task_runner_->PostTaskAndReply(
        FROM_HERE,
        base::Bind(base::IgnoreResult(&base::DeleteFile),
                   base::FilePath(image_path),
                   false),
        base::Bind(&UserImageManagerImpl::UpdateLocalStateAfterMigration,
                   weak_factory_.GetWeakPtr(),
                   user_id));
  } else {
    // If no old image exists, remove |user_id| from the old prefs dictionary.
    UpdateLocalStateAfterMigration(user_id);
  }
}

void UserImageManagerImpl::UpdateLocalStateAfterMigration(
    const std::string& user_id) {
  DictionaryPrefUpdate update(g_browser_process->local_state(),
                              kUserImages);
  update->RemoveWithoutPathExpansion(user_id, NULL);
}

void UserImageManagerImpl::TryToCreateImageSyncObserver() {
  const User* user = user_manager_->GetLoggedInUser();
  // If the currently logged-in user's user image is managed, the sync observer
  // must not be started so that the policy-set image does not get synced out.
  if (!user_image_sync_observer_ &&
      user && user->CanSyncImage() &&
      !IsUserImageManaged(user->email()) &&
      !CommandLine::ForCurrentProcess()->HasSwitch(
          chromeos::switches::kDisableUserImageSync)) {
    user_image_sync_observer_.reset(new UserImageSyncObserver(user));
  }
}

}  // namespace chromeos


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 109: 119 (1994)

#### Original name
Tricholoma singaporense Corner

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<component name="ArtifactManager">
  <artifact type="exploded-war" name="coffee-mate:war exploded">
    <output-path>$PROJECT_DIR$/target/coffee-mate</output-path>
    <root id="root">
      <element id="directory" name="WEB-INF">
        <element id="directory" name="classes">
          <element id="module-output" name="coffee-mate" />
        </element>
        <element id="directory" name="lib">
          <element id="library" level="project" name="Maven: org.springframework.boot:spring-boot-starter-web:1.3.0.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework.boot:spring-boot-starter:1.3.0.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework.boot:spring-boot:1.3.0.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework.boot:spring-boot-autoconfigure:1.3.0.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework.boot:spring-boot-starter-logging:1.3.0.RELEASE" />
          <element id="library" level="project" name="Maven: ch.qos.logback:logback-classic:1.1.3" />
          <element id="library" level="project" name="Maven: ch.qos.logback:logback-core:1.1.3" />
          <element id="library" level="project" name="Maven: org.slf4j:slf4j-api:1.7.13" />
          <element id="library" level="project" name="Maven: org.slf4j:jcl-over-slf4j:1.7.13" />
          <element id="library" level="project" name="Maven: org.slf4j:jul-to-slf4j:1.7.13" />
          <element id="library" level="project" name="Maven: org.slf4j:log4j-over-slf4j:1.7.13" />
          <element id="library" level="project" name="Maven: org.springframework:spring-core:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: org.yaml:snakeyaml:1.16" />
          <element id="library" level="project" name="Maven: org.springframework.boot:spring-boot-starter-validation:1.3.0.RELEASE" />
          <element id="library" level="project" name="Maven: org.hibernate:hibernate-validator:5.2.2.Final" />
          <element id="library" level="project" name="Maven: javax.validation:validation-api:1.1.0.Final" />
          <element id="library" level="project" name="Maven: org.jboss.logging:jboss-logging:3.3.0.Final" />
          <element id="library" level="project" name="Maven: com.fasterxml:classmate:1.1.0" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.6.3" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.6.3" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-core:2.6.3" />
          <element id="library" level="project" name="Maven: org.springframework:spring-web:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-aop:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: aopalliance:aopalliance:1.0" />
          <element id="library" level="project" name="Maven: org.springframework:spring-beans:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-context:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-webmvc:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-expression:4.2.3.RELEASE" />
          <element id="library" level="project" name="Maven: com.happylifeplat:message-code:1.0.1.RELEASE" />
          <element id="library" level="project" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:8.0.28" />
        </element>
      </element>
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/target/coffee-mate/META-INF/MANIFEST.MF" />
      </element>
      <element id="javaee-facet-resources" facet="coffee-mate/web/Web" />
    </root>
  </artifact>
</component>


text:
#ifndef Rice__Enum__hpp_
#define Rice__Enum__hpp_

#include "to_from_ruby_defn.hpp"
#include "Address_Registration_Guard.hpp"
#include "Array.hpp"
#include "Hash.hpp"
#include "String.hpp"
#include "Module.hpp"
#include "Data_Type.hpp"

namespace Rice
{

//! Default traits for the Enum class template.
template<typename Enum_T>
struct Default_Enum_Traits
{
  //! Converts the enum value to a long.
  static long as_long(Enum_T value);
};

/*!
 *  \example enum/sample_enum.cpp
 */

//! A wrapper for enumerated types.
/*! Provides a simple type-safe wrapper for enumerated types.  At the
 *  ruby level, the class will have convenience methods for iterating
 *  over all the defined enum values, converting the values to strings,
 *  and more.
 *
 *  \param Enum_T the enumerated type
 *  \param Enum_Traits specifies the traits of the enumerated type.
 *
 *  Example:
 *  \code
 *    enum Color { Red, Green, Blue };
 *    Enum<Color> rb_cColor = define_enum<Color>("Color")
 *      .define_value("Red", Red)
 *      .define_value("Green", Green)
 *      .define_value("Blue", Blue);
 *  \endcode
 */
template<typename Enum_T, typename Enum_Traits = Default_Enum_Traits<Enum_T> >
class Enum
  : public Module_impl<Data_Type<Enum_T>, Enum<Enum_T, Enum_Traits> >
{
public:
  //! Default constructor.
  Enum();

  //! Construct and initialize.
  Enum(
      char const * name,
      Module module = rb_cObject);

  //! Copy constructor.
  Enum(Enum const & other);

  //! Assignment operator.
  Enum & operator=(Enum const & other);

  //! Destructor.
  virtual ~Enum();

  //! Define a new enum value.
  /*! \param name the name of the enum value.
   *  \param value the value to associate with name.
   *  \return *this
   */
  Enum<Enum_T, Enum_Traits> & define_value(
      char const * name,
      Enum_T value);

  void swap(Enum & other);

private:
  //! Initialize the enum type.
  /*! Must be called only once.
   *  \param name the name of the class to define
   *  \param module the module in which to place the enum class.
   *  \return *this
   */
  Enum<Enum_T, Enum_Traits> & initialize(
      char const * name,
      Module module = rb_cObject);

private:
  static Object each(Object self);
  static Object to_s(Object self);
  static Object to_i(Object self);
  static Object inspect(Object self);
  static Object compare(Object lhs, Object rhs);
  static Object eql(Object lhs, Object rhs);
  static Object hash(Object self);
  static Object from_int(Class klass, Object i);

private:
  Array enums_;
  Address_Registration_Guard enums_guard_;

  Hash names_;
  Address_Registration_Guard names_guard_;
};

template<typename T>
Enum<T> define_enum(
    char const * name,
    Module module = rb_cObject);

} // namespace Rice

#include "Enum.ipp"

#endif // Rice__Enum__hpp_


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ionic-select</title>
</head>
<body>
  <script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="/bower_components/xin-ionic/ionic-demo.html">
  <link rel="import" href="/bower_components/xin-ionic/ionic-header.html">
  <link rel="import" href="/bower_components/xin-ionic/ionic-content.html">
  <link rel="import" href="/bower_components/xin-ionic/ionic-list.html">
  <link rel="import" href="/bower_components/xin-ionic/ionic-item.html">
  <link rel="import" href="/bower_components/xin-ionic/ionic-select.html">

  <ionic-demo>
    <template>
      <ionic-header title="Select"></ionic-header>
      <ionic-content>
        <ionic-list>
          <ionic-select value="{{selected}}">
            <option value="">Please select</option>
            <option>Foo</option>
            <option>Bar</option>
            <option>Baz</option>
          </ionic-select>
          <ionic-item>Selected value is: <span>[[selected]]</span></ionic-item>
        </ionic-list>
      </ionic-content>
    </template>
  </ionic-demo>
</body>
</html>


text:
package com.joshcough.minecraft

/**
 * This plugin and this code is not intended for use.
 * It is just an empty plugin that is required for turning this library
 * into a plugin, so that the API and Ermine can be on the classpath for
 * plugins that want to use this API.
 */
class NetLogoLibPlugin extends org.bukkit.plugin.java.JavaPlugin {
  override def onEnable  : Unit = {}
  override def onDisable : Unit = {}
}


text:
.content img{
	display:block;
	margin:auto;
}


text:
.bg-colour{
    background-color: darkorchid;
    height: 100vh;
}
.login-padding{
    padding-top: 100px;
}


text:
// Copyright (c) 2015 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Palaso.WritingSystems;
using Palaso.Text;
using Palaso.UI.WindowsForms;

namespace Palaso.UI.WindowsForms.GeckoBasedControls
{
	public partial class GeckoBox : GeckoBase, ITextInputBox, IControlThatKnowsWritingSystem
	{
		private string _pendingHtmlLoad;
		protected bool _keyPressed;
		private EventHandler _textChangedHandler;
		private string _previousText;

		public GeckoBox()
		{
			InitializeComponent();

			_keyPressed = false;

			var designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
			if (designMode)
				return;

			Debug.WriteLine("New GeckoBox");
			ReadOnly = false;
			Multiline = false;

			_textChangedHandler = new EventHandler(OnTextChanged);
			this.TextChanged += _textChangedHandler;

			_browser.DomMouseDown += (object sender, EventArgs ea) =>
			{
				//DomMouseEventArgs e = new DomMouseEventArgs(e);
				if (!_browserDocumentLoaded)
				{
					return;
				}

				EnsureFocusedGeckoControlHasInputFocus();

				if (ContainsFocus)
				{
					return;
				}

				_browser.Focus();
			};
		}

		public GeckoBox(IWritingSystemDefinition ws, string nameForLogging)
			: this()
		{
			_nameForLogging = nameForLogging;
			if (_nameForLogging == null)
			{
				_nameForLogging = "??";
			}
			Name = _nameForLogging;
			WritingSystem = ws;
		}

		protected override void Closing()
		{
			this.TextChanged -= _textChangedHandler;
			_textChangedHandler = null;
			base.Closing();
		}

		///
		/// called when the client changes our Control.Text... we need to them move that into the html
		///
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected virtual void OnTextChanged(object sender, EventArgs e)
		{
			SetText(Text);
			AdjustHeight();
			LanguageForm.AdjustSpansForTextChange(_previousText, Text, Spans);
			_previousText = Text;
		}

		public Control TheControl { get { return this; } }

		public void Select(int start, int length)
		{
			base.Select();
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			if (Parent is TextInputBox)
				(Parent as TextInputBox).OnChildKeyDown (e);
			else
				base.OnKeyDown(e);
		}

		protected override void OnDomKeyUp(object sender, EventArgs ea)
		{
			DomKeyEventArgs e = new DomKeyEventArgs(ea);
			var content = _browser.Document.GetElementById("main");
			if (!(e.KeyCode == (uint)Keys.Enter)) // carriage return
			{
				_keyPressed = true;
				Text = content.TextContent;
			}
		}

		protected override void OnGeckoBox_Load(object sender, EventArgs e)
		{
			_browserIsReadyToNavigate = true;
			if (_pendingHtmlLoad != null)
			{
				_browser.LoadHtml(_pendingHtmlLoad);
				_pendingHtmlLoad = null;
			}
			else
			{
				SetText(""); //make an empty, editable box
			}
			this.Focus();
		}

		protected override void OnResize(EventArgs e)
		{
			_browser.Width = Width;
			base.OnResize(e);
		}

		protected void RefreshDisplay()
		{
			if (_writingSystem != null)
			{
				_keyPressed = false;
				SetText(Text);
			}
		}

		private void SetText(string s)
		{
			s = System.Security.SecurityElement.Escape(s);
			String justification = "left";
			String multiLineStyle = "";
			String background = "#FFFFFF";

			if (_writingSystem != null && WritingSystem.RightToLeftScript)
			{
				justification = "right";
			}

			String editable = "true";
			if (ReadOnly)
			{
				editable = "false";
				background = System.Drawing.ColorTranslator.ToHtml(BackColor);
			}

			if (Multiline)
			{
				multiLineStyle = "word-wrap:break-word; ";
			}
			else
			{
				multiLineStyle = "white-space:nowrap; ";
			}
			Font font;
			if (_writingSystem != null)
				font = WritingSystemDefinition.CreateFont(_writingSystem);
			else
				font = this.Parent.Font;
			var html = new StringBuilder("");
			html.AppendLine("");
			html.AppendLine("<meta charset=\"UTF-8\">");
			html.AppendLine("");
			html.AppendLine("");
			html.AppendFormat("", GetLanguageHtml(_writingSystem), background);
			html.AppendFormat("
{2}
",
					font.Name, font.Size.ToString(), s, justification, editable, System.Drawing.ColorTranslator.ToHtml(BackColor), System.Drawing.ColorTranslator.ToHtml(ForeColor), multiLineStyle);
			html.AppendLine("");
			html.AppendLine("");
			if (!_browserIsReadyToNavigate)
			{
				_pendingHtmlLoad = html.ToString();
			}
			else
			{
				if (!_keyPressed)
				{
					_browser.LoadHtml(html.ToString());
				}
				_keyPressed = false;
			}
		}

		public void SetHtml(string html)
		{
			if (!_browserIsReadyToNavigate)
			{
				_pendingHtmlLoad = html;
			}
			else
			{
				_browser.LoadHtml(html);
			}

		}

		public bool IsSpellCheckingEnabled { get; set; }

		protected override void OnLeave(EventArgs e)
		{
			base.OnLeave(e);

			ClearKeyboard();
		}
		protected override void OnEnter(EventArgs e)
		{
			base.OnEnter(e);

			AssignKeyboardFromWritingSystem();
		}

		public List<LanguageForm.FormatSpan> Spans { get; set; }

		public override string Text
		{
			set
			{
				_previousText = value;
				base.Text = value;
			}
			get { return base.Text; }
		}
	}

}


text:
//
//  TPMessageListModelTest.m
//  TP
//
//  Created by moxin on 2015-06-01 19:41:08 +0800.
//  Copyright (c) 2015年 VizLab. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "VizzleConfig.h"
#import "TPMessageListModel.h"

@interface TPMessageListModelTest : XCTestCase

@property(nonatomic,strong)TPMessageListModel* tPMessageListModel;

@end

@implementation TPMessageListModelTest

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
    self.tPMessageListModel = [TPMessageListModel new];
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];

    [self.tPMessageListModel cancel];
    self.tPMessageListModel = nil;
}

- (void)testConnection {

    __block BOOL waitingForBlock = YES;
    [self.tPMessageListModel loadWithCompletion:^(VZHTTPListModel *model, NSError *error) {

        TPMessageListModel* tPMessageListModel = (TPMessageListModel* )model;
        if (!error)
        {

        }
        else
        {
            XCTFail(@"Connection Failed:%@",error);
        }

        waitingForBlock = NO;

    }];

    while (waitingForBlock) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
    }
}

@end


text:
<configuration debug="false">

  <root level="off"/>

  <appender name="TEST" class="com.kdgregory.logback.testhelpers.sns.TestableSNSAppender">
    <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%msg</pattern>
    </layout>
    <topicName>Irrelevant</topicName>
    <synchronous>true</synchronous>
    <batchDelay>9876</batchDelay> <!-- note: overridden -->
  </appender>

  <logger name="com.kdgregory.logback.aws.TestSNSAppender" level="debug">
    <appender-ref ref="TEST" />
  </logger>

</configuration>


text:
package io.druid.segment.data;

import io.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import io.druid.segment.DoubleColumnSelector;
import io.druid.segment.FloatColumnSelector;
import io.druid.segment.LongColumnSelector;
import io.druid.segment.historical.HistoricalColumnSelector;

import java.io.Closeable;

public interface IndexedDoubles extends Closeable
{
  public int size();
  public double get(int index);
  public void fill(int index, double[] toFill);

  @Override
  void close();

  default DoubleColumnSelector makeDoubleColumnSelector(ReadableOffset offset)
  {
    class HistoricalDoubleColumnSelector implements DoubleColumnSelector, HistoricalColumnSelector<Double>
    {
      @Override
      public double getDouble()
      {
        return IndexedDoubles.this.get(offset.getOffset());
      }

      @Override
      public double getDouble(int offset)
      {
        return IndexedDoubles.this.get(offset);
      }

      @Override
      public void inspectRuntimeShape(RuntimeShapeInspector inspector)
      {
        inspector.visit("indexed", IndexedDoubles.this);
        inspector.visit("offset", offset);
      }
    }
    return new HistoricalDoubleColumnSelector();
  }

  default FloatColumnSelector makeFloatColumnSelector(ReadableOffset offset)
  {
    class HistoricalFloatColumnSelector implements FloatColumnSelector, HistoricalColumnSelector<Float>
    {
      @Override
      public float getFloat()
      {
        return (float) IndexedDoubles.this.get(offset.getOffset());
      }

      @Override
      public double getDouble(int offset)
      {
        return IndexedDoubles.this.get(offset);
      }

      @Override
      public void inspectRuntimeShape(RuntimeShapeInspector inspector)
      {
        inspector.visit("indexed", IndexedDoubles.this);
        inspector.visit("offset", offset);
      }
    }
    return new HistoricalFloatColumnSelector();
  }

  default LongColumnSelector makeLongColumnSelector(ReadableOffset offset)
  {
    class HistoricalLongColumnSelector implements LongColumnSelector, HistoricalColumnSelector<Long>
    {
      @Override
      public long getLong()
      {
        return (long) IndexedDoubles.this.get(offset.getOffset());
      }

      @Override
      public double getDouble(int offset)
      {
        return IndexedDoubles.this.get(offset);
      }

      @Override
      public void inspectRuntimeShape(RuntimeShapeInspector inspector)
      {
        inspector.visit("indexed", IndexedDoubles.this);
        inspector.visit("offset", offset);
      }
    }
    return new HistoricalLongColumnSelector();
  }
}


text:
<?php
/**
 * The interface of registry
 *
 * @category   Registry
 * @package    EnliteFiles
 * @author     Vladimir Struc <Sysaninster@gmail.com>
 * @license    LICENSE.txt
 * @date       30.10.13
 */

namespace EnliteFiles\Registry;

use EnliteFiles\File\FileInterface;
use EnliteFiles\Storage\StorageInterface;

interface RegistryInterface {

    /**
     * Save info about file
     *
     * @param FileInterface $file
     * @return void
     */
    public function save(FileInterface $file);

    /**
     * Load file by id
     *
     * @param int $id
     * @return FileInterface
     */
    public function loadById($id);

    /**
     * Remove info about file
     *
     * @param FileInterface $file
     * @return void
     */
    public function remove(FileInterface $file);

    /**
     * Factory model of file
     *
     * @return FileInterface
     */
    public function factory();

    /**
     * Set storage
     *
     * @param StorageInterface $storage
     * @return void
     */
    public function setStorage(StorageInterface $storage);

}


text:
class ExtensionFunction;
class UIThreadExtensionFunction;
class IOThreadExtensionFunction;

namespace base {
class ListValue;
class Value;
}

namespace content {
class BrowserContext;
class RenderFrameHost;
class RenderViewHost;
class WebContents;
}

namespace extensions {
class ExtensionFunctionDispatcher;
class IOThreadExtensionMessageFilter;
class QuotaLimitHeuristic;
}

namespace IPC {
class Sender;
}

#ifdef NDEBUG
#define EXTENSION_FUNCTION_VALIDATE(test) \
  do {                                    \
    if (!(test)) {                        \
      this->bad_message_ = true;          \
      return ValidationFailure(this);     \
    }                                     \
  } while (0)
#else   // NDEBUG
#define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
#endif  // NDEBUG

#define EXTENSION_FUNCTION_ERROR(error) \
  do {                                  \
    error_ = error;                     \
    this->bad_message_ = true;          \
    return ValidationFailure(this);     \
  } while (0)

// Declares a callable extension function with the given |name|. You must also
// supply a unique |histogramvalue| used for histograms of extension function
// invocation (add new ones at the end of the enum in
// extension_function_histogram_value.h).
#define DECLARE_EXTENSION_FUNCTION(name, histogramvalue) \
  public: static const char* function_name() { return name; } \
  public: static extensions::functions::HistogramValue histogram_value() \
    { return extensions::functions::histogramvalue; }

// Traits that describe how ExtensionFunction should be deleted. This just calls
// the virtual "Destruct" method on ExtensionFunction, allowing derived classes
// to override the behavior.
struct ExtensionFunctionDeleteTraits {
 public:
  static void Destruct(const ExtensionFunction* x);
};

// Abstract base class for extension functions the ExtensionFunctionDispatcher
// knows how to dispatch to.
class ExtensionFunction
    : public base::RefCountedThreadSafe<ExtensionFunction,
                                        ExtensionFunctionDeleteTraits> {
 public:
  enum ResponseType {
    // The function has succeeded.
    SUCCEEDED,
    // The function has failed.
    FAILED,
    // The input message is malformed.
    BAD_MESSAGE
  };

  using ResponseCallback = base::Callback<void(
      ResponseType type,
      const base::ListValue& results,
      const std::string& error,
      extensions::functions::HistogramValue histogram_value)>;

  ExtensionFunction();

  virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction();
  virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction();

  // Returns true if the function has permission to run.
  //
  // The default implementation is to check the Extension's permissions against
  // what this function requires to run, but some APIs may require finer
  // grained control, such as tabs.executeScript being allowed for active tabs.
  //
  // This will be run after the function has been set up but before Run().
  virtual bool HasPermission();

  // The result of a function call.
  //
  // Use NoArguments(), OneArgument(), ArgumentList(), or Error()
  // rather than this class directly.
  class ResponseValueObject {
   public:
    virtual ~ResponseValueObject() {}

    // Returns true for success, false for failure.
    virtual bool Apply() = 0;
  };
  typedef scoped_ptr<ResponseValueObject> ResponseValue;

  // The action to use when returning from RunAsync.
  //
  // Use RespondNow() or RespondLater() rather than this class directly.
  class ResponseActionObject {
   public:
    virtual ~ResponseActionObject() {}

    virtual void Execute() = 0;
  };
  typedef scoped_ptr<ResponseActionObject> ResponseAction;

  // Helper class for tests to force all ExtensionFunction::user_gesture()
  // calls to return true as long as at least one instance of this class
  // exists.
  class ScopedUserGestureForTests {
   public:
    ScopedUserGestureForTests();
    ~ScopedUserGestureForTests();
  };

  // Runs the function and returns the action to take when the caller is ready
  // to respond.
  //
  // Typical return values might be:
  //   * RespondNow(NoArguments())
  //   * RespondNow(OneArgument(42))
  //   * RespondNow(ArgumentList(my_result.ToValue()))
  //   * RespondNow(Error("Warp core breach"))
  //   * RespondNow(Error("Warp core breach on *", GetURL()))
  //   * RespondLater(), then later,
  //     * Respond(NoArguments())
  //     * ... etc.
  //
  //
  // Callers must call Execute() on the return ResponseAction at some point,
  // exactly once.
  //
  // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
  // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
  // but this is deprecated. ExtensionFunction implementations are encouraged
  // to just implement Run.
  virtual ResponseAction Run() WARN_UNUSED_RESULT = 0;

  // Gets whether quota should be applied to this individual function
  // invocation. This is different to GetQuotaLimitHeuristics which is only
  // invoked once and then cached.
  //
  // Returns false by default.
  virtual bool ShouldSkipQuotaLimiting() const;

  // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
  // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
  // instances is passed to the owner of |heuristics|.
  // No quota limiting by default.
  //
  // Only called once per lifetime of the QuotaService.
  virtual void GetQuotaLimitHeuristics(
      extensions::QuotaLimitHeuristics* heuristics) const {}

  // Called when the quota limit has been exceeded. The default implementation
  // returns an error.
  virtual void OnQuotaExceeded(const std::string& violation_error);

  // Specifies the raw arguments to the function, as a JSON value.
  virtual void SetArgs(const base::ListValue* args);

  // Sets a single Value as the results of the function.
  void SetResult(scoped_ptr<base::Value> result);
  // As above, but deprecated. TODO(estade): remove.
  void SetResult(base::Value* result);

  // Sets multiple Values as the results of the function.
  void SetResultList(scoped_ptr<base::ListValue> results);

  // Retrieves the results of the function as a ListValue.
  const base::ListValue* GetResultList() const;

  // Retrieves any error string from the function.
  virtual std::string GetError() const;

  // Sets the function's error string.
  virtual void SetError(const std::string& error);

  // Sets the function's bad message state.
  void set_bad_message(bool bad_message) { bad_message_ = bad_message; }

  // Specifies the name of the function. A long-lived string (such as a string
  // literal) must be provided.
  void set_name(const char* name) { name_ = name; }
  const char* name() const { return name_; }

  void set_profile_id(void* profile_id) { profile_id_ = profile_id; }
  void* profile_id() const { return profile_id_; }

  void set_extension(
      const scoped_refptr<const extensions::Extension>& extension) {
    extension_ = extension;
  }
  const extensions::Extension* extension() const { return extension_.get(); }
  const std::string& extension_id() const {
    DCHECK(extension())
        << "extension_id() called without an Extension. If " << name()
        << " is allowed to be called without any Extension then you should "
        << "check extension() first. If not, there is a bug in the Extension "
        << "platform, so page somebody in extensions/OWNERS";
    return extension_->id();
  }

  void set_request_id(int request_id) { request_id_ = request_id; }
  int request_id() { return request_id_; }

  void set_source_url(const GURL& source_url) { source_url_ = source_url; }
  const GURL& source_url() { return source_url_; }

  void set_has_callback(bool has_callback) { has_callback_ = has_callback; }
  bool has_callback() { return has_callback_; }

  void set_include_incognito(bool include) { include_incognito_ = include; }
  bool include_incognito() const { return include_incognito_; }

  // Note: consider using ScopedUserGestureForTests instead of calling
  // set_user_gesture directly.
  void set_user_gesture(bool user_gesture) { user_gesture_ = user_gesture; }
  bool user_gesture() const;

  void set_histogram_value(
      extensions::functions::HistogramValue histogram_value) {
    histogram_value_ = histogram_value; }
  extensions::functions::HistogramValue histogram_value() const {
    return histogram_value_; }

  void set_response_callback(const ResponseCallback& callback) {
    response_callback_ = callback;
  }

  void set_source_tab_id(int source_tab_id) { source_tab_id_ = source_tab_id; }
  int source_tab_id() const { return source_tab_id_; }

  void set_source_context_type(extensions::Feature::Context type) {
    source_context_type_ = type;
  }
  extensions::Feature::Context source_context_type() const {
    return source_context_type_;
  }

 protected:
  friend struct ExtensionFunctionDeleteTraits;

  // ResponseValues.
  //
  // Success, no arguments to pass to caller.
  ResponseValue NoArguments();
  // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP - a
  // raw pointer for convenience, since callers usually construct the argument
  // to this by hand.
  ResponseValue OneArgument(base::Value* arg);
  // Success, a single argument |arg| to pass to caller.
  ResponseValue OneArgument(scoped_ptr<base::Value> arg);
  // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
  // OWNERSHIP - raw pointers for convenience, since callers usually construct
  // the argument to this by hand. Note that use of this function may imply you
  // should be using the generated Result struct and ArgumentList.
  ResponseValue TwoArguments(base::Value* arg1, base::Value* arg2);
  // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
  // - a scoped_ptr<> for convenience, since callers usually get this from the
  // result of a Create(...) call on the generated Results struct, for example,
  // alarms::Get::Results::Create(alarm).
  ResponseValue ArgumentList(scoped_ptr<base::ListValue> results);
  // Error. chrome.runtime.lastError.message will be set to |error|.
  ResponseValue Error(const std::string& error);
  // Error with formatting. Args are processed using
  // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
  // by the corresponding |s*|:
  // Error("Error in *: *", "foo", "bar") <--> Error("Error in foo: bar").
  ResponseValue Error(const std::string& format, const std::string& s1);
  ResponseValue Error(const std::string& format,
                      const std::string& s1,
                      const std::string& s2);
  ResponseValue Error(const std::string& format,
                      const std::string& s1,
                      const std::string& s2,
                      const std::string& s3);
  // Error with a list of arguments |args| to pass to caller. TAKES OWNERSHIP.
  // Using this ResponseValue indicates something is wrong with the API.
  // It shouldn't be possible to have both an error *and* some arguments.
  // Some legacy APIs do rely on it though, like webstorePrivate.
  ResponseValue ErrorWithArguments(scoped_ptr<base::ListValue> args,
                                   const std::string& error);
  // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE(),
  // so this will actually kill the renderer and not respond at all.
  ResponseValue BadMessage();

  // ResponseActions.
  //
  // These are exclusively used as return values from Run(). Call Respond(...)
  // to respond at any other time - but as described below, only after Run()
  // has already executed, and only if it returned RespondLater().
  //
  // Respond to the extension immediately with |result|.
  ResponseAction RespondNow(ResponseValue result) WARN_UNUSED_RESULT;
  // Don't respond now, but promise to call Respond(...) later.
  ResponseAction RespondLater() WARN_UNUSED_RESULT;

  // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
  // needs to work from Run(), RunAsync(), and RunSync(). The former of those
  // has a different return type (ResponseAction) than the latter two (bool).
  static ResponseAction ValidationFailure(ExtensionFunction* function)
      WARN_UNUSED_RESULT;

  // If RespondLater() was returned from Run(), functions must at some point
  // call Respond() with |result| as their result.
  //
  // More specifically: call this iff Run() has already executed, it returned
  // RespondLater(), and Respond(...) hasn't already been called.
  void Respond(ResponseValue result);

  virtual ~ExtensionFunction();

  // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
  virtual void Destruct() const = 0;

  // Do not call this function directly, return the appropriate ResponseAction
  // from Run() instead. If using RespondLater then call Respond().
  //
  // Call with true to indicate success, false to indicate failure, in which
  // case please set |error_|.
  virtual void SendResponse(bool success) = 0;

  // Common implementation for SendResponse.
  void SendResponseImpl(bool success);

  // Return true if the argument to this function at |index| was provided and
  // is non-null.
  bool HasOptionalArgument(size_t index);

  // Id of this request, used to map the response back to the caller.
  int request_id_;

  // The id of the profile of this function's extension.
  void* profile_id_;

  // The extension that called this function.
  scoped_refptr<const extensions::Extension> extension_;

  // The name of this function.
  const char* name_;

  // The URL of the frame which is making this request
  GURL source_url_;

  // True if the js caller provides a callback function to receive the response
  // of this call.
  bool has_callback_;

  // True if this callback should include information from incognito contexts
  // even if our profile_ is non-incognito. Note that in the case of a "split"
  // mode extension, this will always be false, and we will limit access to
  // data from within the same profile_ (either incognito or not).
  bool include_incognito_;

  // True if the call was made in response of user gesture.
  bool user_gesture_;

  // The arguments to the API. Only non-null if argument were specified.
  scoped_ptr<base::ListValue> args_;

  // The results of the API. This should be populated by the derived class
  // before SendResponse() is called.
  scoped_ptr<base::ListValue> results_;

  // Any detailed error from the API. This should be populated by the derived
  // class before Run() returns.
  std::string error_;

  // Any class that gets a malformed message should set this to true before
  // returning.  Usually we want to kill the message sending process.
  bool bad_message_;

  // The sample value to record with the histogram API when the function
  // is invoked.
  extensions::functions::HistogramValue histogram_value_;

  // The callback to run once the function has done execution.
  ResponseCallback response_callback_;

  // The ID of the tab triggered this function call, or -1 if there is no tab.
  int source_tab_id_;

  // The type of the JavaScript context where this call originated.
  extensions::Feature::Context source_context_type_;

 private:
  void OnRespondingLater(ResponseValue response);

  DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
};

// Extension functions that run on the UI thread. Most functions fall into
// this category.
class UIThreadExtensionFunction : public ExtensionFunction {
 public:
  // TODO(yzshen): We should be able to remove this interface now that we
  // support overriding the response callback.
  // A delegate for use in testing, to intercept the call to SendResponse.
  class DelegateForTests {
   public:
    virtual void OnSendResponse(UIThreadExtensionFunction* function,
                                bool success,
                                bool bad_message) = 0;
  };

  UIThreadExtensionFunction();

  UIThreadExtensionFunction* AsUIThreadExtensionFunction() override;

  void set_test_delegate(DelegateForTests* delegate) {
    delegate_ = delegate;
  }

  // Called when a message was received.
  // Should return true if it processed the message.
  virtual bool OnMessageReceived(const IPC::Message& message);

  // Set the browser context which contains the extension that has originated
  // this function call.
  void set_browser_context(content::BrowserContext* context) {
    context_ = context;
  }
  content::BrowserContext* browser_context() const { return context_; }

  void SetRenderViewHost(content::RenderViewHost* render_view_host);
  content::RenderViewHost* render_view_host() const {
    return render_view_host_;
  }
  void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
  content::RenderFrameHost* render_frame_host() const {
    return render_frame_host_;
  }

  void set_dispatcher(const base::WeakPtr<
      extensions::ExtensionFunctionDispatcher>& dispatcher) {
    dispatcher_ = dispatcher;
  }
  extensions::ExtensionFunctionDispatcher* dispatcher() const {
    return dispatcher_.get();
  }

  // Gets the "current" web contents if any. If there is no associated web
  // contents then defaults to the foremost one.
  // NOTE: "current" can mean different things in different contexts. You
  // probably want to use GetSenderWebContents().
  virtual content::WebContents* GetAssociatedWebContents();

  // Returns the web contents associated with the sending |render_view_host_|.
  // This can be null.
  content::WebContents* GetSenderWebContents();

 protected:
  // Emits a message to the extension's devtools console.
  void WriteToConsole(content::ConsoleMessageLevel level,
                      const std::string& message);

  friend struct content::BrowserThread::DeleteOnThread<
      content::BrowserThread::UI>;
  friend class base::DeleteHelper<UIThreadExtensionFunction>;

  ~UIThreadExtensionFunction() override;

  void SendResponse(bool success) override;

  // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
  void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids);

  // The dispatcher that will service this extension function call.
  base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;

  // The RenderViewHost we will send responses to.
  content::RenderViewHost* render_view_host_;

  // The RenderFrameHost we will send responses to.
  // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
  // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
  content::RenderFrameHost* render_frame_host_;

  // The content::BrowserContext of this function's extension.
  content::BrowserContext* context_;

 private:
  class RenderHostTracker;

  void Destruct() const override;

  // TODO(tommycli): Remove once RenderViewHost is gone.
  IPC::Sender* GetIPCSender();
  int GetRoutingID();

  scoped_ptr<RenderHostTracker> tracker_;

  DelegateForTests* delegate_;

  // The blobs transferred to the renderer process.
  std::vector<std::string> transferred_blob_uuids_;
};

// Extension functions that run on the IO thread. This type of function avoids
// a roundtrip to and from the UI thread (because communication with the
// extension process happens on the IO thread). It's intended to be used when
// performance is critical (e.g. the webRequest API which can block network
// requests). Generally, UIThreadExtensionFunction is more appropriate and will
// be easier to use and interface with the rest of the browser.
class IOThreadExtensionFunction : public ExtensionFunction {
 public:
  IOThreadExtensionFunction();

  IOThreadExtensionFunction* AsIOThreadExtensionFunction() override;

  void set_ipc_sender(
      base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender,
      int routing_id) {
    ipc_sender_ = ipc_sender;
    routing_id_ = routing_id;
  }

  base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_weak()
      const {
    return ipc_sender_;
  }

  int routing_id() const { return routing_id_; }

  void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
    extension_info_map_ = extension_info_map;
  }
  const extensions::InfoMap* extension_info_map() const {
    return extension_info_map_.get();
  }

 protected:
  friend struct content::BrowserThread::DeleteOnThread<
      content::BrowserThread::IO>;
  friend class base::DeleteHelper<IOThreadExtensionFunction>;

  ~IOThreadExtensionFunction() override;

  void Destruct() const override;

  void SendResponse(bool success) override;

 private:
  base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_;
  int routing_id_;

  scoped_refptr<const extensions::InfoMap> extension_info_map_;
};

// Base class for an extension function that runs asynchronously *relative to
// the browser's UI thread*.
class AsyncExtensionFunction : public UIThreadExtensionFunction {
 public:
  AsyncExtensionFunction();

 protected:
  ~AsyncExtensionFunction() override;

  // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
  //
  // AsyncExtensionFunctions implement this method. Return true to indicate that
  // nothing has gone wrong yet; SendResponse must be called later. Return false
  // to respond immediately with an error.
  virtual bool RunAsync() = 0;

  // ValidationFailure override to match RunAsync().
  static bool ValidationFailure(AsyncExtensionFunction* function);

 private:
  // If you're hitting a compile error here due to "final" - great! You're
  // doing the right thing, you just need to extend UIThreadExtensionFunction
  // instead of AsyncExtensionFunction.
  ResponseAction Run() final;
};

// A SyncExtensionFunction is an ExtensionFunction that runs synchronously
// *relative to the browser's UI thread*. Note that this has nothing to do with
// running synchronously relative to the extension process. From the extension
// process's point of view, the function is still asynchronous.
//
// This kind of function is convenient for implementing simple APIs that just
// need to interact with things on the browser UI thread.
class SyncExtensionFunction : public UIThreadExtensionFunction {
 public:
  SyncExtensionFunction();

 protected:
  ~SyncExtensionFunction() override;

  // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
  //
  // SyncExtensionFunctions implement this method. Return true to respond
  // immediately with success, false to respond immediately with an error.
  virtual bool RunSync() = 0;

  // ValidationFailure override to match RunSync().
  static bool ValidationFailure(SyncExtensionFunction* function);

 private:
  // If you're hitting a compile error here due to "final" - great! You're
  // doing the right thing, you just need to extend UIThreadExtensionFunction
  // instead of SyncExtensionFunction.
  ResponseAction Run() final;
};

class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
 public:
  SyncIOThreadExtensionFunction();

 protected:
  ~SyncIOThreadExtensionFunction() override;

  // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
  //
  // SyncIOThreadExtensionFunctions implement this method. Return true to
  // respond immediately with success, false to respond immediately with an
  // error.
  virtual bool RunSync() = 0;

  // ValidationFailure override to match RunSync().
  static bool ValidationFailure(SyncIOThreadExtensionFunction* function);

 private:
  // If you're hitting a compile error here due to "final" - great! You're
  // doing the right thing, you just need to extend IOThreadExtensionFunction
  // instead of SyncIOExtensionFunction.
  ResponseAction Run() final;
};

#endif  // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Game" table="game">
    <change-tracking-policy>DEFERRED_IMPLICIT</change-tracking-policy>
    <id name="gameId" type="integer" column="game_id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="club" type="string" column="club" length="255"/>
    <field name="result" type="string" column="result" length="255"/>
    <field name="localGame1" type="string" column="local_game1" length="255"/>
    <field name="localGame2" type="string" column="local_game2" length="255"/>
    <field name="localGame3" type="string" column="local_game3" length="255"/>
    <field name="visitorGame1" type="string" column="visitor_game1" length="255"/>
    <field name="visitorGame2" type="string" column="visitor_game2" length="255"/>
    <field name="visitorGame3" type="string" column="visitor_game3" length="255"/>
    <field name="tieBreak1" type="string" column="tie_break1" length="255"/>
    <field name="tieBreak2" type="string" column="tie_break2" length="255"/>
    <field name="tieBreak3" type="string" column="tie_break3" length="255"/>
    <field name="superTieBreak" type="string" column="super_tie_break" length="255"/>
    <many-to-one field="teamLocal" target-entity="Team" orphan-removal="">
      <join-columns>
        <join-column name="team_local_id" referenced-column-name="team_id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="teamVisitor" target-entity="Team" orphan-removal="">
      <join-columns>
        <join-column name="team_visitor_id" referenced-column-name="team_id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="teamWinner" target-entity="Team" orphan-removal="">
      <join-columns>
        <join-column name="team_winner_id" referenced-column-name="team_id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="teamLooser" target-entity="Team" orphan-removal="">
      <join-columns>
        <join-column name="team_looser_id" referenced-column-name="team_id"/>
      </join-columns>
    </many-to-one>
    <lifecycle-callbacks/>
  </entity>
</doctrine-mapping>


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0023_auto_20161021_1626'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='user',
            options={'ordering': ['username', 'last_name', 'first_name']},
        ),
        migrations.RemoveField(
            model_name='user',
            name='name',
        ),
    ]


text:
{{ obj.name }}
{% if obj.description %}
  : {{obj.description}}
{% endif %}


text:
package org.runningdinner.mail.mailserversettings;

/**
 * Exception that is thrown on mail connection check when user wants to use a custom mail server
 *
 * @author Clemens Stich
 *
 */
public class MailServerConnectionFailedException extends Exception {

	private static final long serialVersionUID = -5070710969462849916L;

	public enum MAIL_CONNECTION_ERROR {
		AUTHENTICATION, SEND, UNKNOWN
	}

	protected MAIL_CONNECTION_ERROR mailConnectionError = MAIL_CONNECTION_ERROR.UNKNOWN;

	public MailServerConnectionFailedException() {
		super();
	}

	public MailServerConnectionFailedException(String message, Throwable cause) {
		super(message, cause);
	}

	public MailServerConnectionFailedException(String message) {
		super(message);
	}

	public MailServerConnectionFailedException(Throwable cause) {
		super(cause);
	}

	public MAIL_CONNECTION_ERROR getMailConnectionError() {
		return mailConnectionError;
	}

	public MailServerConnectionFailedException setMailConnectionError(MAIL_CONNECTION_ERROR mailConnectionError) {
		this.mailConnectionError = mailConnectionError;
		return this;
	}

}


text:
"""
Firewall manager iptables plugin.
"""

import gettext
_ = lambda m: gettext.dgettext(message=m, domain='ovirt-engine-setup')

from otopi import util
from otopi import plugin
from otopi import constants as otopicons
from otopi import filetransaction

from ovirt_engine import util as outil

from ovirt_engine_setup import constants as osetupcons
from ovirt_engine_setup import firewall_manager_base

from . import process_firewalld_services

@util.export
class Plugin(plugin.PluginBase):
    """
    Firewall manager iptables plugin.
    """

    class _IpTablesManager(firewall_manager_base.FirewallManagerBase):

        _SERVICE = 'iptables'

        def _get_rules(self):
            if self._rules is None:
                self._rules = outil.processTemplate(
                    osetupcons.FileLocations.OVIRT_IPTABLES_DEFAULT,
                    subst={
                        '@CUSTOM_RULES@': (
                            process_firewalld_services.Process.getInstance(
                                environment=self.environment,
                            ).parseFirewalld(
                                format=(
                                    '-A INPUT -p {protocol} -m state '
                                    '--state NEW -m {protocol} '
                                    '--dport {port} -j ACCEPT\n'
                                ),
                                portSeparator=':',
                            )
                        ),
                    }
                )
            return self._rules

        def __init__(self, plugin):
            super(Plugin._IpTablesManager, self).__init__(plugin)
            self._rules = None

        @property
        def name(self):
            return osetupcons.Const.FIREWALL_MANAGER_IPTABLES

        def detect(self):
            return self.plugin.services.exists(self._SERVICE)

        def active(self):
            return self.plugin.services.status(self._SERVICE)

        def prepare_examples(self):
            content = self._get_rules()
            self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
                filetransaction.FileTransaction(
                    name=osetupcons.FileLocations.OVIRT_IPTABLES_EXAMPLE,
                    content=content,
                    modifiedList=self.environment[
                        otopicons.CoreEnv.MODIFIED_FILES
                    ],
                )
            )

        def enable(self):
            self.environment[otopicons.NetEnv.IPTABLES_ENABLE] = True
            self.environment[
                otopicons.NetEnv.IPTABLES_RULES
            ] = self._get_rules()
            # This file is updated by otopi. Here we just prevent it from
            # being deleted on cleanup.
            # TODO: copy/move some uninstall code from the engine to otopi
            # to allow just adding lines to iptables instead of replacing
            # the file and also remove these lines on cleanup.
            self.environment[
                osetupcons.CoreEnv.UNINSTALL_UNREMOVABLE_FILES
            ].append(
                osetupcons.FileLocations.SYSCONFIG_IPTABLES,
            )

        def print_manual_configuration_instructions(self):
            self.plugin.dialog.note(
                text=_(
                    'An example of the required configuration for iptables '
                    'can be found at:\n'
                    '    {example}'
                ).format(
                    example=osetupcons.FileLocations.OVIRT_IPTABLES_EXAMPLE
                )
            )

    @plugin.event(
        stage=plugin.Stages.STAGE_SETUP,
        before=(
            osetupcons.Stages.KEEP_ONLY_VALID_FIREWALL_MANAGERS,
        ),
    )
    def _setup(self):
        self.environment[
            osetupcons.ConfigEnv.FIREWALL_MANAGERS
        ].append(Plugin._IpTablesManager(self))

# vim: expandtab tabstop=4 shiftwidth=4


text:
<?php

namespace Orchestra\Story\Http\Controllers;

use Orchestra\Story\Model\Content;
use Illuminate\Support\Facades\View;
use Orchestra\Support\Facades\Facile;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class PageController extends ContentController
{
    /**
     * {@inheritdoc}
     */
    protected function getResponse($page, $id, $slug)
    {
        $slug = preg_replace('/^_page_\//', '', $slug);

        if (! View::exists($view = "orchestra/story::pages.{$slug}")) {
            $view = 'orchestra/story::page';
        }

        $data = [
            'id'   => $id,
            'page' => $page,
            'slug' => $slug,
        ];

        return Facile::view($view)->with($data)->render();
    }

    /**
     * {@inheritdoc}
     */
    protected function getRequestedContent($id, $slug)
    {
        if (isset($id) and ! is_null($id)) {
            return Content::page()->publish()->where('id', $id)->firstOrFail();
        } elseif (isset($slug) and ! is_null($slug)) {
            return Content::page()->publish()->where('slug', "_page_/{$slug}")->firstOrFail();
        }

        throw new NotFoundHttpException();
    }
}


text:
package ca.friendlyguacamole.server.models

/**
  * Created by panagiotis on 07/08/17.
  */
case class LoginResponse(token: String, session: String)


text:
package mg.fishchicken.core.conditions;

import groovy.lang.Binding;
import mg.fishchicken.gamelogic.quests.Quest;

import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.XmlReader.Element;

/**
 * Returns true if the supplied variable is not defined
 * on the supplied Quest.
 *
 *

 * Example:
 *

 *	<questVariableUndefined name="variableName" quest="questId" />
 *

 *
 * @author ANNUN
 *
 */
public class QuestVariableUndefined extends VariableUndefined {

	public static final String XML_QUEST = "quest";

	@Override
	protected boolean evaluate(Object object, Binding parameters) {
		return super.evaluate(Quest.getQuest(getParameter(XML_QUEST)), parameters);
	}

	@Override
	public void validateAndLoadFromXML(Element conditionElement) {
		super.validateAndLoadFromXML(conditionElement);
		if (conditionElement.get(XML_QUEST, null) == null) {
			throw new GdxRuntimeException(XML_QUEST+" must be set for condition QuestVariableUndefined in element: \n\n"+conditionElement);
		}
	}

	@Override
	protected String getStringTableNameKey() {
		return "isUndefinedInQuest";
	}

	@Override
	protected Object[] getStringNameParams() {
		return new Object[]{getParameter(XML_VARIABLE_NAME), getParameter(XML_QUEST)};
	}
}