text:
namespace omaha {

namespace {

// Returns the number of days haven been passed since the given time.
// The parameter time is in the same format as C time() returns.
int GetNumberOfDaysSince(int time) {
  ASSERT1(time >= 0);
  const int now = Time64ToInt32(GetCurrent100NSTime());
  ASSERT1(now >= time);

  if (now < time) {
    // In case the client computer clock is adjusted in between.
    return 0;
  }
  return (now - time) / kSecondsPerDay;
}

// Determines if an application is registered with Google Update.
class IsAppRegisteredFunc
    : public std::unary_function<const CString&, HRESULT> {
 public:
  explicit IsAppRegisteredFunc(const CString& guid)
      : is_registered_(false),
        guid_(guid) {}

  bool is_registered() const { return is_registered_; }

  HRESULT operator() (const CString& guid) {
    if (guid.CompareNoCase(guid_) == 0) {
      is_registered_ = true;
    }
    return S_OK;
  }
 private:
  CString guid_;
  bool is_registered_;
};

// Accumulates ProductData.
class CollectProductsFunc
    : public std::unary_function<const CString&, HRESULT> {
 public:
  CollectProductsFunc(ProductDataVector* products,
                      bool is_machine,
                      bool collect_registered_products)
      : products_(products),
        is_machine_(is_machine),
        collect_registered_products_(collect_registered_products) {
    ASSERT1(products);
  }

  // Ignores errors and accumulates as many applications as possible.
  HRESULT operator() (const CString& guid) {
    AppManager app_manager(is_machine_);
    ProductData product_data;
    if (SUCCEEDED(app_manager.ReadProductDataFromStore(StringToGuid(guid),
                                                       &product_data))) {
      ASSERT(!collect_registered_products_ ||
             !product_data.app_data().is_uninstalled(),
             (_T("Should not be finding uninstalled apps while looking for ")
              _T("registered apps; may be enumerating the wrong key.")));
      if (collect_registered_products_ ||
          product_data.app_data().is_uninstalled()) {
        CORE_LOG(L3, (_T("[Found %s product][%s]"),
                      collect_registered_products_ ? _T("registered") :
                                                      _T("uninstalled"),
                      guid));
        products_->push_back(product_data);
      }
    }
    return S_OK;
  }

 private:
  bool collect_registered_products_;
  bool is_machine_;
  ProductDataVector* products_;
};

// Accumulates AppData for components of a product.
class CollectComponentsFunc
    : public std::unary_function<const CString&, HRESULT> {
 public:
  CollectComponentsFunc(ProductData* product_data,
                        bool is_machine)
      : product_data_(product_data),
        is_machine_(is_machine) {
    ASSERT1(product_data);
  }

  // Ignores errors and accumulates as many components as possible.
  HRESULT operator() (const CString& guid) {
    AppManager app_manager(is_machine_);
    AppData component_data;
    if (SUCCEEDED(app_manager.ReadAppDataFromStore(
        product_data_->app_data().app_guid(),
        StringToGuid(guid),
        &component_data))) {
      product_data_->AddComponent(component_data);
    }
    return S_OK;
  }

 private:
  ProductData* product_data_;
  bool is_machine_;
};

// Enumerates all sub keys of the key and calls the functor for each of them.
template <typename T>
HRESULT EnumerateSubKeys(const TCHAR* key_name, T* functor) {
  RegKey client_key;
  HRESULT hr = client_key.Open(key_name, KEY_READ);
  if (FAILED(hr)) {
    return hr;
  }

  int num_sub_keys = client_key.GetSubkeyCount();
  for (int i = 0; i < num_sub_keys; ++i) {
    CString sub_key_name;
    hr = client_key.GetSubkeyNameAt(i, &sub_key_name);
    if (SUCCEEDED(hr)) {
      (*functor)(sub_key_name);
    }
  }

  return S_OK;
}

}  // namespace

AppManager::AppManager(bool is_machine)
    : is_machine_(is_machine) {
  CORE_LOG(L3, (_T("[AppManager::AppManager][is_machine=%d]"), is_machine));
}

bool AppManager::IsProductRegistered(const GUID& app_guid) const {
  IsAppRegisteredFunc func(GuidToString(app_guid));
  HRESULT hr = EnumerateSubKeys(
      ConfigManager::Instance()->registry_clients(is_machine_),
      &func);
  if (FAILED(hr)) {
    return false;
  }

  return func.is_registered();
}

// TODO(omaha): Consider making AppManager a namespace.
void AppManager::ConvertCommandLineToProductData(const CommandLineArgs& args,
                                                 ProductDataVector* products) {
  ASSERT1(products);

  // TODO(omaha):  Need to update this to read the bundle info to build up
  // multiple AppData objects (and also to read components) and add unit test.
  for (size_t i = 0; i < args.extra.apps.size(); ++i) {
    const CommandLineAppArgs& extra_arg = args.extra.apps[i];
    const GUID& app_guid = extra_arg.app_guid;
    AppData app_data(app_guid, is_machine_);
    app_data.set_language(args.extra.language);
    app_data.set_ap(extra_arg.ap);
    app_data.set_tt_token(extra_arg.tt_token);
    app_data.set_iid(args.extra.installation_id);
    app_data.set_brand_code(args.extra.brand_code);
    app_data.set_client_id(args.extra.client_id);
    app_data.set_referral_id(args.extra.referral_id);

    // install_time_diff_sec is set based on the current state of the system.
    if (IsProductRegistered(app_guid)) {
      app_data.set_install_time_diff_sec(GetInstallTimeDiffSec(app_guid));
    } else {
      // The product is not already installed. We differentiate this from no
      // install time being present (i.e. the app was installed before
      // installtime was implemented) by setting the diff to -1 days.
      // This makes an assumption about the XML parser but works for now.
      const int kNewInstallValue = -1 * kSecondsPerDay;
      app_data.set_install_time_diff_sec(kNewInstallValue);
    }

    // Do not set is_oem_install because it is not based on the command line.
    app_data.set_is_eula_accepted(!args.is_eula_required_set);
    app_data.set_display_name(extra_arg.app_name);
    app_data.set_browser_type(args.extra.browser_type);
    app_data.set_install_source(args.install_source);
    app_data.set_usage_stats_enable(args.extra.usage_stats_enable);
    app_data.set_encoded_installer_data(extra_arg.encoded_installer_data);
    app_data.set_install_data_index(extra_arg.install_data_index);

    ProductData product_data(app_data);
    products->push_back(product_data);
  }

  ASSERT1(products->size() == args.extra.apps.size());
}

HRESULT AppManager::GetRegisteredProducts(ProductDataVector* products) const {
  ASSERT1(products);

  CollectProductsFunc func(products, is_machine_, true);
  return EnumerateSubKeys(
      ConfigManager::Instance()->registry_clients(is_machine_),
      &func);
}

HRESULT AppManager::GetUnRegisteredProducts(ProductDataVector* products) const {
  ASSERT1(products);

  CollectProductsFunc func(products, is_machine_, false);
  return EnumerateSubKeys(
      ConfigManager::Instance()->registry_client_state(is_machine_),
      &func);
}

CString AppManager::GetProductClientKeyName(const GUID& app_guid) {
  return goopdate_utils::GetAppClientsKey(is_machine_, GuidToString(app_guid));
}

CString AppManager::GetProductClientComponentsKeyName(const GUID& app_guid) {
  return AppendRegKeyPath(GetProductClientKeyName(app_guid),
                          kComponentsRegKeyName);
}

CString AppManager::GetProductClientStateComponentsKeyName(
    const GUID& app_guid) {
  return AppendRegKeyPath(GetProductClientStateKeyName(app_guid),
                          kComponentsRegKeyName);
}

CString AppManager::GetComponentClientKeyName(const GUID& parent_app_guid,
                                              const GUID& app_guid) {
  return AppendRegKeyPath(GetProductClientComponentsKeyName(parent_app_guid),
                          GuidToString(app_guid));
}

CString AppManager::GetProductClientStateKeyName(const GUID& app_guid) {
  return goopdate_utils::GetAppClientStateKey(is_machine_,
                                              GuidToString(app_guid));
}

CString AppManager::GetComponentClientStateKeyName(const GUID& parent_app_guid,
                                                   const GUID& app_guid) {
  return AppendRegKeyPath(
      GetProductClientStateComponentsKeyName(parent_app_guid),
      GuidToString(app_guid));
}

CString AppManager::GetProductClientStateMediumKeyName(const GUID& app_guid) {
  ASSERT1(is_machine_);
  return goopdate_utils::GetAppClientStateMediumKey(is_machine_,
                                                    GuidToString(app_guid));
}

CString AppManager::GetClientKeyName(const GUID& parent_app_guid,
                                     const GUID& app_guid) {
  if (::IsEqualGUID(parent_app_guid, GUID_NULL)) {
    return GetProductClientKeyName(app_guid);
  } else {
    return GetComponentClientKeyName(parent_app_guid, app_guid);
  }
}

CString AppManager::GetClientStateKeyName(const GUID& parent_app_guid,
                                          const GUID& app_guid) {
  if (::IsEqualGUID(parent_app_guid, GUID_NULL)) {
    return GetProductClientStateKeyName(app_guid);
  } else {
    return GetComponentClientStateKeyName(parent_app_guid, app_guid);
  }
}

HRESULT AppManager::OpenClientKey(const GUID& parent_app_guid,
                                  const GUID& app_guid,
                                  RegKey* client_key) {
  ASSERT1(client_key);
  return client_key->Open(GetClientKeyName(parent_app_guid, app_guid),
                          KEY_READ);
}

HRESULT AppManager::OpenClientStateKey(const GUID& parent_app_guid,
                                       const GUID& app_guid,
                                       REGSAM sam_desired,
                                       RegKey* client_state_key) {
  ASSERT1(client_state_key);
  CString key_name = GetClientStateKeyName(parent_app_guid, app_guid);
  return client_state_key->Open(key_name, sam_desired);
}

// Also creates the ClientStateMedium key for machine apps, ensuring it exists
// whenever ClientState exists.  Does not create ClientStateMedium for Omaha.
// This method is called for self-updates, so it must explicitly avoid this.
HRESULT AppManager::CreateClientStateKey(const GUID& parent_app_guid,
                                         const GUID& app_guid,
                                         RegKey* client_state_key) {
  ASSERT(::IsEqualGUID(parent_app_guid, GUID_NULL),
         (_T("Legacy components not supported; ClientStateMedium ignores.")));

  ASSERT1(client_state_key);
  const CString key_name = GetClientStateKeyName(parent_app_guid, app_guid);
  HRESULT hr = client_state_key->Create(key_name);
  if (FAILED(hr)) {
    CORE_LOG(L3, (_T("[RegKey::Create failed][0x%08x]"), hr));
    return hr;
  }

  if (!is_machine_) {
    return S_OK;
  }

  if (::IsEqualGUID(kGoopdateGuid, app_guid)) {
    return S_OK;
  }

  const CString medium_key_name = GetProductClientStateMediumKeyName(app_guid);
  hr = RegKey::CreateKey(medium_key_name);
  if (FAILED(hr)) {
    CORE_LOG(L3, (_T("[RegKey::Create ClientStateMedium failed][0x%08x]"), hr));
    return hr;
  }

  return S_OK;
}

// Reads the following values from the registry:
// Clients Key
//   product version
//   language
// Client State Key
//   previous product version.
//   last checked
//   ap
//   client id
//   iid
// Clients key in HKCU/HKLM/Low integrity
//   did run
// Note: If the application is uninstalled, the clients key may not exist.
HRESULT AppManager::ReadProductDataFromStore(const GUID& app_guid,
                                             ProductData* product_data) {
  ASSERT1(product_data);

  AppData app_data;
  HRESULT hr = ReadAppDataFromStore(GUID_NULL, app_guid, &app_data);
  if (FAILED(hr)) {
    CORE_LOG(LE, (_T("[AppManager::ReadAppDataFromStore failed][0x%08x]"), hr));
    return hr;
  }

  ProductData product(app_data);

  // Read components for this product from the registry.
  CollectComponentsFunc func(&product, is_machine_);
  EnumerateSubKeys(GetProductClientComponentsKeyName(app_data.app_guid()),
                   &func);

  *product_data = product;
  return S_OK;
}

HRESULT AppManager::ReadAppDataFromStore(const GUID& parent_app_guid,
                                         const GUID& app_guid,
                                         AppData* app_data) {
  ASSERT1(app_data);
  AppData temp_data(app_guid, is_machine_);
  temp_data.set_parent_app_guid(parent_app_guid);

  bool client_key_exists = false;
  RegKey client_key;
  HRESULT hr = OpenClientKey(parent_app_guid, app_guid, &client_key);
  if (SUCCEEDED(hr)) {
    CString version;
    hr = client_key.GetValue(kRegValueProductVersion, &version);
    temp_data.set_version(version);
    CORE_LOG(L3, (_T("[AppManager::ReadAppDataFromStore]")
                  _T("[parent_app_guid=%s]")
                  _T("[app_guid=%s]")
                  _T("[version=%s]"),
                  GuidToString(parent_app_guid),
                  GuidToString(app_guid),
                  version));
    if (FAILED(hr)) {
      return hr;
    }

    // Language might not be written by an installer, so ignore failures.
    CString language;
    client_key.GetValue(kRegValueLanguage, &language);
    temp_data.set_language(language);
    client_key_exists = true;
  }

  // If ClientState registry key doesn't exist, the function could return.
  // Before opening the key, set days_since_last* to -1, which is the
  // default value if reg key doesn't exist. If later we find that the values
  // are readable, new values will overwrite current ones.
  temp_data.set_days_since_last_active_ping(-1);
  temp_data.set_days_since_last_roll_call(-1);

  RegKey client_state_key;
  hr = OpenClientStateKey(parent_app_guid,
                          app_guid,
                          KEY_READ,
                          &client_state_key);
  if (FAILED(hr)) {
    // It is possible that the client state key has not yet been populated.
    // In this case just return the information that we have gathered thus far.
    // However if both keys dont exist, then we are doing something wrong.
    CORE_LOG(LW, (_T("[AppManager::ReadAppDataFromStore - No ClientState]")));
    if (client_key_exists) {
      *app_data = temp_data;
      return S_OK;
    } else {
      return hr;
    }
  }

  // The value is not essential for Omaha's operation, so ignore errors.
  CString previous_version;
  HRESULT previous_version_hr =
      client_state_key.GetValue(kRegValueProductVersion, &previous_version);
  temp_data.set_previous_version(previous_version);

  // An app is considered uninstalled if:
  //  * The app's Clients key does not exist AND
  //  * The app's ClientState key exists and contains the pv value.
  // Omaha may create the app's ClientState key and write values from the
  // metainstaller tag before running the installer, which creates the Client
  // key. Requiring pv in ClientState avoids mistakenly determining that the
  // Omaha-created key indicates an uninstall.
  bool app_is_uninstalled =
      !client_key_exists &&
      HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) != previous_version_hr;
  temp_data.set_is_uninstalled(app_is_uninstalled);

  CString ap;
  client_state_key.GetValue(kRegValueAdditionalParams, &ap);
  temp_data.set_ap(ap);

  CString tt_token;
  client_state_key.GetValue(kRegValueTTToken, &tt_token);
  temp_data.set_tt_token(tt_token);

  CString iid;
  client_state_key.GetValue(kRegValueInstallationId, &iid);
  temp_data.set_iid(StringToGuid(iid));

  CString brand_code;
  client_state_key.GetValue(kRegValueBrandCode, &brand_code);
  ASSERT1(brand_code.GetLength() <= kBrandIdLength);
  temp_data.set_brand_code(brand_code);

  CString client_id;
  client_state_key.GetValue(kRegValueClientId, &client_id);
  temp_data.set_client_id(client_id);

  DWORD last_active_ping_sec(0);
  if (SUCCEEDED(client_state_key.GetValue(kRegValueActivePingDayStartSec,
                                          &last_active_ping_sec))) {
    int days_since_last_active_ping =
        GetNumberOfDaysSince(static_cast<int32>(last_active_ping_sec));
    temp_data.set_days_since_last_active_ping(days_since_last_active_ping);
  }

  DWORD last_roll_call_sec(0);
  if (SUCCEEDED(client_state_key.GetValue(kRegValueRollCallDayStartSec,
                                          &last_roll_call_sec))) {
    int days_since_last_roll_call =
        GetNumberOfDaysSince(static_cast<int32>(last_roll_call_sec));
    temp_data.set_days_since_last_roll_call(days_since_last_roll_call);
  }

  // We do not need the referral_id.

  ASSERT(::IsEqualGUID(parent_app_guid, GUID_NULL),
         (_T("Legacy components not supported.")));
  temp_data.set_install_time_diff_sec(GetInstallTimeDiffSec(app_guid));

  temp_data.set_is_oem_install(client_state_key.HasValue(kRegValueOemInstall));

  bool is_eula_accepted = true;
  DWORD eula_accepted = 0;

  ASSERT(::IsEqualGUID(parent_app_guid, GUID_NULL),
         (_T("Legacy components not supported; IsAppEulaAccepted ignores.")));
  temp_data.set_is_eula_accepted(
      goopdate_utils::IsAppEulaAccepted(is_machine_,
                                        GuidToString(app_guid),
                                        false));

  if (temp_data.language().IsEmpty()) {
    // Read the language from the client state key if we did not find
    // it in the client key.
    CString language;
    client_state_key.GetValue(kRegValueLanguage, &language);
    temp_data.set_language(language);
  }

  // Read the did run value.
  // TODO(omaha): Try to move this logic into the application_usage_data class.
  ApplicationUsageData app_usage(is_machine_, vista_util::IsVistaOrLater());
  hr = app_usage.ReadDidRun(GuidToString(app_guid));
  if (FAILED(hr)) {
    CORE_LOG(LEVEL_WARNING, (_T("[ReadDidRun failed][0x%08x]"), hr));
  }
  AppData::ActiveStates active = AppData::ACTIVE_NOTRUN;
  if (app_usage.exists()) {
    active = app_usage.did_run() ? AppData::ACTIVE_RUN :
                                   AppData::ACTIVE_NOTRUN;
  } else {
    active = AppData::ACTIVE_UNKNOWN;
  }
  temp_data.set_did_run(active);

  *app_data = temp_data;
  return S_OK;
}

// Sets brand code, client ID, usage stats, browser, ap, and Omaha language in
// the app's ClientState. Also, sets the installed by OEM flag if appropriate.
// Sets eulaaccepted=0 if the app is not already registered and the app's EULA
// has not been accepted. Deletes eulaaccepted if the EULA has been accepted.
// Only call for initial or over-installs. Do not call for updates to avoid
// mistakenly replacing data, such as the application's language, and causing
// unexpected changes to the app during a silent update.
HRESULT AppManager::WritePreInstallData(const AppData& app_data) {
  CORE_LOG(L3, (_T("[AppManager::WritePreInstallData]")));

  RegKey client_state_key;
  HRESULT hr = CreateClientStateKey(app_data.parent_app_guid(),
                                    app_data.app_guid(),
                                    &client_state_key);
  if (FAILED(hr)) {
    return hr;
  }

  if (app_data.is_eula_accepted()) {
    hr = goopdate_utils::ClearAppEulaNotAccepted(
             is_machine_,
             GuidToString(app_data.app_guid()));
  } else {
    if (!IsProductRegistered(app_data.app_guid())) {
      hr = goopdate_utils::SetAppEulaNotAccepted(
               is_machine_,
               GuidToString(app_data.app_guid()));
    }
  }
  if (FAILED(hr)) {
    return hr;
  }

  CString state_key_path = GetClientStateKeyName(app_data.parent_app_guid(),
                                                 app_data.app_guid());
  VERIFY1(SUCCEEDED(goopdate_utils::SetAppBranding(state_key_path,
                                                   app_data.brand_code(),
                                                   app_data.client_id(),
                                                   app_data.referral_id())));

  ASSERT(::IsEqualGUID(app_data.parent_app_guid(), GUID_NULL),
         (_T("Legacy components not supported; SetUsageStatsEnable ignores.")));
  if (TRISTATE_NONE != app_data.usage_stats_enable()) {
    VERIFY1(SUCCEEDED(goopdate_utils::SetUsageStatsEnable(
                          is_machine_,
                          GuidToString(app_data.app_guid()),
                          app_data.usage_stats_enable())));
  }

  if (BROWSER_UNKNOWN == app_data.browser_type()) {
    VERIFY1(SUCCEEDED(client_state_key.DeleteValue(kRegValueBrowser)));
  } else {
    DWORD browser_type = app_data.browser_type();
    VERIFY1(SUCCEEDED(client_state_key.SetValue(kRegValueBrowser,
                                                browser_type)));
  }

  if (app_data.ap().IsEmpty()) {
    VERIFY1(SUCCEEDED(
        client_state_key.DeleteValue(kRegValueAdditionalParams)));
  } else {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(kRegValueAdditionalParams,
                                                app_data.ap())));
  }

  if (!app_data.language().IsEmpty()) {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(kRegValueLanguage,
                                                app_data.language())));
  }

  if (ConfigManager::Instance()->IsOemInstalling(is_machine_)) {
    ASSERT1(is_machine_);
    VERIFY1(SUCCEEDED(client_state_key.SetValue(kRegValueOemInstall, _T("1"))));
  }

  return S_OK;
}

// Sets installation ID in the app's ClientState.
// Copies version and language from clients to client state reg key.
HRESULT AppManager::InitializeApplicationState(AppData* app_data) {
  CORE_LOG(L3, (_T("[AppManager::InitializeApplicationState]")));
  ASSERT1(app_data);
  RegKey client_state_key;
  HRESULT hr = CreateClientStateKey(app_data->parent_app_guid(),
                                    app_data->app_guid(),
                                    &client_state_key);
  if (FAILED(hr)) {
    return hr;
  }

  RegKey client_key;
  hr = OpenClientKey(app_data->parent_app_guid(),
                     app_data->app_guid(),
                     &client_key);
  if (FAILED(hr)) {
    return hr;
  }

  if (!::IsEqualGUID(app_data->iid(), GUID_NULL)) {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(
                          kRegValueInstallationId,
                          GuidToString(app_data->iid()))));
  }

  return CopyVersionAndLanguageToClientState(app_data,
                                             client_state_key,
                                             client_key);
}

// Copies language and version from clients into client state reg key.
HRESULT AppManager::UpdateApplicationState(AppData* app_data) {
  ASSERT1(app_data);
  RegKey client_state_key;
  HRESULT hr = CreateClientStateKey(app_data->parent_app_guid(),
                                    app_data->app_guid(),
                                    &client_state_key);
  if (FAILED(hr)) {
    return hr;
  }

  RegKey client_key;
  hr = OpenClientKey(app_data->parent_app_guid(),
                     app_data->app_guid(),
                     &client_key);
  if (FAILED(hr)) {
    return hr;
  }

  hr = CopyVersionAndLanguageToClientState(app_data,
                                           client_state_key,
                                           client_key);
  if (FAILED(hr)) {
    return hr;
  }

  return S_OK;
}

HRESULT AppManager::WriteTTToken(const AppData& app_data,
                                 const UpdateResponseData& response_data) {
  CORE_LOG(L3, (_T("[WriteTTToken][app_data token=%s][response_data token=%s]"),
                app_data.tt_token(), response_data.tt_token()));
  RegKey client_state_key;
  HRESULT hr = CreateClientStateKey(app_data.parent_app_guid(),
                                    app_data.app_guid(),
                                    &client_state_key);
  if (FAILED(hr)) {
    return hr;
  }

  if (response_data.tt_token().IsEmpty()) {
    VERIFY1(SUCCEEDED(client_state_key.DeleteValue(kRegValueTTToken)));
  } else {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(kRegValueTTToken,
                                                response_data.tt_token())));
  }

  return S_OK;
}

// The registry reads and writes are not thread safe, but there should not be
// other threads or processes calling this at the same time.
void AppManager::UpdateUpdateAvailableStats(const GUID& parent_app_guid,
                                            const GUID& app_guid) {
  RegKey state_key;
  HRESULT hr = CreateClientStateKey(parent_app_guid, app_guid, &state_key);
  if (FAILED(hr)) {
    ASSERT1(false);
    return;
  }

  DWORD update_available_count(0);
  hr = state_key.GetValue(kRegValueUpdateAvailableCount,
                          &update_available_count);
  if (FAILED(hr)) {
    update_available_count = 0;
  }
  ++update_available_count;
  VERIFY1(SUCCEEDED(state_key.SetValue(kRegValueUpdateAvailableCount,
                                       update_available_count)));

  DWORD64 update_available_since_time(0);
  hr = state_key.GetValue(kRegValueUpdateAvailableSince,
                          &update_available_since_time);
  if (FAILED(hr)) {
    // There is no existing value, so this must be the first update notice.
    VERIFY1(SUCCEEDED(state_key.SetValue(kRegValueUpdateAvailableSince,
                                         GetCurrent100NSTime())));

    // TODO(omaha): It would be nice to report the version that we were first
    // told to update to. This is available in UpdateResponse but we do not
    // currently send it down in update responses. If we start using it, add
    // kRegValueFirstUpdateResponseVersion.
  }
}

void AppManager::ClearUpdateAvailableStats(const GUID& parent_app_guid,
                                           const GUID& app_guid) {
  RegKey state_key;
  HRESULT hr =
      OpenClientStateKey(parent_app_guid, app_guid, KEY_ALL_ACCESS, &state_key);
  if (FAILED(hr)) {
    return;
  }

  VERIFY1(SUCCEEDED(state_key.DeleteValue(kRegValueUpdateAvailableCount)));
  VERIFY1(SUCCEEDED(state_key.DeleteValue(kRegValueUpdateAvailableSince)));
}

void AppManager::ClearOemInstalled(const GUID& parent_app_guid,
                                   const GUID& app_guid) {
  RegKey state_key;
  HRESULT hr =
      OpenClientStateKey(parent_app_guid, app_guid, KEY_ALL_ACCESS, &state_key);
  ASSERT1(SUCCEEDED(hr));
  if (FAILED(hr)) {
    return;
  }

  VERIFY1(SUCCEEDED(state_key.DeleteValue(kRegValueOemInstall)));
}

// Returns 0 for any values that are not found.
void AppManager::ReadUpdateAvailableStats(
    const GUID& parent_app_guid,
    const GUID& app_guid,
    DWORD* update_responses,
    DWORD64* time_since_first_response_ms) {
  ASSERT1(update_responses);
  ASSERT1(time_since_first_response_ms);
  *update_responses = 0;
  *time_since_first_response_ms = 0;

  RegKey state_key;
  HRESULT hr = OpenClientStateKey(parent_app_guid,
                                  app_guid,
                                  KEY_READ,
                                  &state_key);
  if (FAILED(hr)) {
    CORE_LOG(LW, (_T("[App ClientState key does not exist][%s]"),
                  GuidToString(app_guid)));
    return;
  }

  DWORD update_responses_in_reg(0);
  hr = state_key.GetValue(kRegValueUpdateAvailableCount,
                          &update_responses_in_reg);
  if (SUCCEEDED(hr)) {
    *update_responses = update_responses_in_reg;
  }

  DWORD64 update_available_since_time(0);
  hr = state_key.GetValue(kRegValueUpdateAvailableSince,
                          &update_available_since_time);
  if (SUCCEEDED(hr)) {
    const DWORD64 current_time = GetCurrent100NSTime();
    ASSERT1(update_available_since_time <= current_time);
    const DWORD64 time_since_first_response_in_100ns =
        current_time - update_available_since_time;
    *time_since_first_response_ms =
        time_since_first_response_in_100ns / kMillisecsTo100ns;
  }
}

// The update success and update check success times are not updated for
// installs even if it is an over-install. At this point, we do not know for
// sure that it was an online update.
void AppManager::RecordSuccessfulInstall(const GUID& parent_app_guid,
                                         const GUID& app_guid,
                                         bool is_update,
                                         bool is_offline) {
  ASSERT1(!is_update || !is_offline);

  ClearUpdateAvailableStats(parent_app_guid, app_guid);

  if (!is_offline) {
    // Assumes that all updates are online.
    RecordSuccessfulUpdateCheck(parent_app_guid, app_guid);
  }

  if (is_update) {
    RegKey state_key;
    HRESULT hr = CreateClientStateKey(parent_app_guid, app_guid, &state_key);
    if (FAILED(hr)) {
      ASSERT1(false);
      return;
    }

    const DWORD now = Time64ToInt32(GetCurrent100NSTime());
    VERIFY1(SUCCEEDED(state_key.SetValue(kRegValueLastUpdateTimeSec, now)));
  }
}

void AppManager::RecordSuccessfulUpdateCheck(const GUID& parent_app_guid,
                                             const GUID& app_guid) {
  RegKey state_key;
  HRESULT hr = CreateClientStateKey(parent_app_guid, app_guid, &state_key);
  if (FAILED(hr)) {
    ASSERT1(false);
    return;
  }

  const DWORD now = Time64ToInt32(GetCurrent100NSTime());
  VERIFY1(SUCCEEDED(state_key.SetValue(kRegValueLastSuccessfulCheckSec, now)));
}

// Assumes the app is registered and has a ClientState. The new install case
// should be handled differently.
uint32 AppManager::GetInstallTimeDiffSec(const GUID& app_guid) {
  RegKey client_state_key;
  HRESULT hr = OpenClientStateKey(GUID_NULL,
                                  app_guid,
                                  KEY_READ,
                                  &client_state_key);
  ASSERT(SUCCEEDED(hr), (_T("Assumes app is registered.")));
  if (FAILED(hr)) {
    return 0;
  }

  DWORD install_time(0);
  DWORD install_time_diff_sec(0);
  if (SUCCEEDED(client_state_key.GetValue(kRegValueInstallTimeSec,
                                          &install_time))) {
    const uint32 now = Time64ToInt32(GetCurrent100NSTime());
    if (0 != install_time && now >= install_time) {
      install_time_diff_sec = now - install_time;
      // TODO(omaha3): Restore this assert. In Omaha 2, this method gets called
      // as part of installation verification and Job::UpdateJob(), so the value
      // can be 0. This will not be the case in Omaha 3.
      // ASSERT1(install_time_diff_sec != 0);
    }
  }

  return install_time_diff_sec;
}

// Clear the Installation ID if at least one of the conditions is true:
// 1) DidRun==yes. First run is the last time we want to use the Installation
//    ID. So delete Installation ID if it is present.
// 2) kMaxLifeOfInstallationIDSec has passed since the app was installed. This
//    is to ensure that Installation ID is cleared even if DidRun is never set.
// 3) The app is Omaha. Always delete Installation ID if it is present
//    because DidRun does not apply.
HRESULT AppManager::ClearInstallationId(AppData* app_data,
                                        const RegKey& client_state_key) {
  ASSERT1(app_data);
  if (::IsEqualGUID(app_data->iid(), GUID_NULL)) {
    return S_OK;
  }

  if ((AppData::ACTIVE_RUN == app_data->did_run()) ||
      (kMaxLifeOfInstallationIDSec <= app_data->install_time_diff_sec()) ||
      (::IsEqualGUID(kGoopdateGuid, app_data->app_guid()))) {
    CORE_LOG(L1, (_T("[Deleting iid for app][%s]"),
                  GuidToString(app_data->app_guid())));
    // Relies on installation_id not empty to indicate state_key is valid.
    VERIFY1(S_OK == client_state_key.DeleteValue(kRegValueInstallationId));
    app_data->set_iid(GUID_NULL);
  }

  return S_OK;
}

void AppManager::ResetDidRun(AppData* app_data) {
  ApplicationUsageData app_usage(app_data->is_machine_app(),
                                 vista_util::IsVistaOrLater());
  VERIFY1(SUCCEEDED(app_usage.ResetDidRun(GuidToString(app_data->app_guid()))));
  app_data->set_did_run(app_usage.exists() ? AppData::ACTIVE_NOTRUN :
                                             AppData::ACTIVE_UNKNOWN);
}

void AppManager::SetLastPingDayStartTime(int time_since_midnight_sec,
                                         AppData* app_data,
                                         const RegKey& client_state_key) {
  ASSERT1(time_since_midnight_sec >= 0);
  ASSERT1(time_since_midnight_sec < kMaxTimeSinceMidnightSec);
  ASSERT1(app_data);

  int now = Time64ToInt32(GetCurrent100NSTime());

  bool did_send_active_ping = (app_data->did_run() == AppData::ACTIVE_RUN &&
                               app_data->days_since_last_active_ping() != 0);
  if (did_send_active_ping) {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(
                          kRegValueActivePingDayStartSec,
                          static_cast<DWORD>(now - time_since_midnight_sec))));
    app_data->set_days_since_last_active_ping(0);
  }

  bool did_send_roll_call = (app_data->days_since_last_roll_call() != 0);
  if (did_send_roll_call) {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(
                          kRegValueRollCallDayStartSec,
                          static_cast<DWORD>(now - time_since_midnight_sec))));
    app_data->set_days_since_last_roll_call(0);
  }
}

// Writes the day start time when last active ping/roll call happened to
// registry if the corresponding ping has been sent.
// Removes installation id, if did run = true or if goopdate.
// Clears did run.
HRESULT AppManager::HandleSuccessfulUpdateCheckRequestSend(
    int time_since_midnight_sec,
    AppData* app_data) {
  RegKey client_state_key;
  HRESULT hr = CreateClientStateKey(app_data->parent_app_guid(),
                                    app_data->app_guid(),
                                    &client_state_key);
  if (FAILED(hr)) {
    return hr;
  }

  // Handle the installation id.
  hr = ClearInstallationId(app_data, client_state_key);
  if (FAILED(hr)) {
    CORE_LOG(LE, (_T("[ClearInstallationId failed][hr=0x%08x]"), hr));
  }

  SetLastPingDayStartTime(time_since_midnight_sec, app_data, client_state_key);

  // Reset did_run after updating the days_since_last_active_ping and the
  // installation ID since these updates need previous did_run status to
  // determine the right actions.
  ResetDidRun(app_data);

  return hr;
}

// Only replaces the language in ClientState and app_data if the language in
// Clients is not empty.
HRESULT AppManager::CopyVersionAndLanguageToClientState(
    AppData* app_data,
    const RegKey& client_state_key,
    const RegKey& client_key) {
  // TODO(omaha):  need to handle components too.
  ASSERT1(app_data);
  // Read the version and language from the client key.
  CString version;
  HRESULT hr = client_key.GetValue(kRegValueProductVersion, &version);
  if (FAILED(hr)) {
    return hr;
  }

  CString language;
  client_key.GetValue(kRegValueLanguage, &language);

  // Write the version and language in the client state key.
  hr = client_state_key.SetValue(kRegValueProductVersion, version);
  if (FAILED(hr)) {
    return hr;
  }

  app_data->set_version(version);
  app_data->set_previous_version(version);

  if (!language.IsEmpty()) {
    VERIFY1(SUCCEEDED(client_state_key.SetValue(kRegValueLanguage, language)));
    app_data->set_language(language);
  }

  return S_OK;
}

HRESULT AppManager::RemoveClientState(const AppData& app_data) {
  ASSERT(::IsEqualGUID(app_data.parent_app_guid(), GUID_NULL),
         (_T("Legacy components not supported; ClientStateMedium ignores.")));

  ASSERT1(app_data.is_uninstalled());
  const CString state_key = GetClientStateKeyName(app_data.parent_app_guid(),
                                                  app_data.app_guid());
  HRESULT state_hr = RegKey::DeleteKey(state_key, true);

  if (!is_machine_) {
    return state_hr;
  }

  const CString state_medium_key =
      GetProductClientStateMediumKeyName(app_data.app_guid());
  HRESULT state_medium_hr = RegKey::DeleteKey(state_medium_key, true);

  return FAILED(state_hr) ? state_hr : state_medium_hr;
}

// Returns true if the absolute difference between time moments is greater than
// the interval between update checks.
// Deals with clocks rolling backwards, in scenarios where the clock indicates
// some time in the future, for example next year, last_checked_ is updated to
// reflect that time, and then the clock is adjusted back to present.
bool AppManager::ShouldCheckForUpdates() const {
  ConfigManager* cm = ConfigManager::Instance();
  bool is_period_overridden = false;
  const int update_interval = cm->GetLastCheckPeriodSec(&is_period_overridden);
  if (0 == update_interval) {
    ASSERT1(is_period_overridden);
    OPT_LOG(L1, (_T("[ShouldCheckForUpdates returned 0][checks disabled]")));
    return false;
  }

  const int time_difference = cm->GetTimeSinceLastCheckedSec(is_machine_);

  const bool result = time_difference >= update_interval ? true : false;
  CORE_LOG(L3, (_T("[ShouldCheckForUpdates returned %d][%u]"),
                result, is_period_overridden));
  return result;
}

HRESULT AppManager::UpdateLastChecked() {
  // Set the last check value to the current value.
  DWORD now = Time64ToInt32(GetCurrent100NSTime());
  HRESULT hr = ConfigManager::Instance()->SetLastCheckedTime(is_machine_, now);
  CORE_LOG(L3, (_T("[AppManager::UpdateLastChecked][now %d]"), now));
  if (FAILED(hr)) {
    CORE_LOG(LW, (_T("[UpdateLastChecked returned 0x%08x]"), hr));
    return hr;
  }
  return S_OK;
}

HRESULT AppManager::ReadProductDataFromUserOrMachineStore(
    const GUID& guid,
    ProductData* product_data) {
  ASSERT1(product_data);
  AppManager app_manager_user(false);
  HRESULT hr = app_manager_user.ReadProductDataFromStore(guid, product_data);
  if (SUCCEEDED(hr)) {
    return hr;
  }

  AppManager app_manager_machine(true);
  return app_manager_machine.ReadProductDataFromStore(guid, product_data);
}

// Writes 0.0.0.1 to pv. This value avoids any special cases, such as initial
// install rules, for 0.0.0.0, while being unlikely to be higher than the
// product's actual current version.
HRESULT AppManager::RegisterProduct(const GUID& product_guid,
                                    const CString& product_name) {
  const TCHAR* const kRegisterProductVersion = _T("0.0.0.1");

  RegKey client_key;
  HRESULT hr = client_key.Create(GetClientKeyName(GUID_NULL, product_guid));
  if (FAILED(hr)) {
    return hr;
  }

  hr = client_key.SetValue(kRegValueProductVersion, kRegisterProductVersion);
  if (FAILED(hr)) {
    return hr;
  }

  // AppName is not a required parameter since it's only used for being able to
  // easily tell what application is there when reading the registry.
  VERIFY1(SUCCEEDED(client_key.SetValue(kRegValueAppName, product_name)));

  return S_OK;
}

HRESULT AppManager::UnregisterProduct(const GUID& product_guid) {
  return RegKey::DeleteKey(GetClientKeyName(GUID_NULL, product_guid), true);
}

}  // namespace omaha.


text:
package io.github.netvl.picopickle

import scala.annotation.implicitNotFound
import scala.{collection => coll}
import scala.collection.{mutable => mut, immutable => imm}

trait ObjectKeyTypesComponent {
  @implicitNotFound("Don't know how to write ${T} as a map key; make sure that an implicit `ObjectKeyWriter[${T}]` is in scope")
  trait ObjectKeyWriter[T] {
    def write(value: T): String
  }

  object ObjectKeyWriter {
    def apply[T](conv: T => String): ObjectKeyWriter[T] = new ObjectKeyWriter[T] {
      override def write(value: T): String = conv(value)
    }
  }

  @implicitNotFound("Don't know how to read ${T} as a map key; make sure that an implicit `ObjectKeyReader[${T}]` is in scope")
  trait ObjectKeyReader[T] {
    def read(value: String): T
  }

  object ObjectKeyReader {
    def apply[T](conv: String => T): ObjectKeyReader[T] = new ObjectKeyReader[T] {
      override def read(value: String): T = conv(value)
    }
  }

  type ObjectKeyReadWriter[T] = ObjectKeyReader[T] with ObjectKeyWriter[T]

  object ObjectKeyReadWriter {
    def apply[T](from: String => T): ObjectKeyReadWriter[T] = apply((t: T) => t.toString, from)

    def apply[T](to: T => String, from: String => T): ObjectKeyReadWriter[T] = new ObjectKeyReader[T] with ObjectKeyWriter[T] {
      override def write(value: T): String = to(value)
      override def read(value: String): T = from(value)
    }

    def apply[T](implicit r: ObjectKeyReader[T], w: ObjectKeyWriter[T]) = new ObjectKeyReader[T] with ObjectKeyWriter[T] {
      override def write(value: T): String = w.write(value)
      override def read(value: String): T = r.read(value)
    }
  }

}

trait ObjectKeyWritersComponent {
  this: ObjectKeyTypesComponent =>

  implicit val stringObjectKeyWriter: ObjectKeyWriter[String] = ObjectKeyWriter(identity)
}

trait ObjectKeyReadersComponent {
  this: ObjectKeyTypesComponent =>

  implicit val stringObjectKeyReader: ObjectKeyReader[String] = ObjectKeyReader(identity)
}

trait ObjectKeyReaderWritersComponent extends ObjectKeyReadersComponent with ObjectKeyWritersComponent {
  this: ObjectKeyTypesComponent =>
}

redpajama_set_name: RedPajamaGithub


text:
using namespace ::testing;

namespace nonstd
{
namespace predicate
{

TEST(cpp11_composed_predicate_and,
	returns_false_when_one_of_different_type_predicates_is_not_satisfied)
{
	unsigned int drinking_age = 21;
	auto is_male_allowed_to_drink = make_composed_predicate<person>(
		std::bind2nd(std::mem_fun_ref(&person::is_older_than),
			drinking_age),
		std::mem_fun_ref(&person::is_male));

	person some_boy("male", 12);

	ASSERT_THAT(is_male_allowed_to_drink(some_boy), Eq(false));
}

} // namespace predicate.
} // namespace nonstd.


text:
@protocol IO2GMessageRow <IO2GRow>
    - (NSString*) getMsgID;
    - (DATE) getTime;
    - (NSString*) getFrom;
    - (NSString*) getType;
    - (NSString*) getFeature;
    - (NSString*) getText;
    - (NSString*) getSubject;
    - (BOOL) getHTMLFragmentFlag;
    //

@end

@protocol IO2GMessageTableRow <IO2GMessageRow>
@end


text:
package com.davidbracewell.function;

import java.io.Serializable;
import java.util.function.ToLongBiFunction;

/**
 * Version of ToLongBiFunction that is serializable
 *
 * @param <T> Functional parameter
 * @param <U> Functional parameter
 */
@FunctionalInterface
public interface SerializableToLongBiFunction<T, U> extends ToLongBiFunction<T, U>, Serializable {

}//END OF SerializableToLongBiFunction


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**secret_name** | **str** | SecretName represents the name of the secret in the VMI's namespace |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
namespace BackgroundJobAndNotificationsDemo.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class Added_CreatorUserId_To_BackgroundJobInfo : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(Added_CreatorUserId_To_BackgroundJobInfo));

        string IMigrationMetadata.Id
        {
            get { return "201601221608456_Added_CreatorUserId_To_BackgroundJobInfo"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
package com.originalsbytoto.bukkit.packsshop;

import java.util.List;
import java.util.regex.Pattern;

import javax.persistence.GeneratedValue;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

import net.milkbowl.vault.economy.Economy;

public class MainClass extends JavaPlugin implements Listener{

	public static Economy econ = null;

	@Override
	public void onEnable() {

		getLogger().info("PackShops initialization ...");

			PluginManager pm = getServer().getPluginManager();
			pm.registerEvents(this, this);

			setupEconomy();

			saveDefaultConfig();

		getLogger().info("PackShops is enabled");

	}

	@Override
	public void onDisable() {

		getLogger().info("PackShops disabling ...");

		getLogger().info("PackShops is disabled");

	}

	@EventHandler
	public void onPlayerJoin(PlayerJoinEvent e) {

		int pId = 96517;
		ApiUpdate updater = new ApiUpdate(pId);
		updater.query();
		String n = updater.getLatestName();

		if(!compare(getDescription().getVersion(), n)) {
			return;
		}

		if(getConfig().getBoolean("update.active", true)) {

			String message = "A new update for PacksShop is available. Find it on http://http://dev.bukkit.org/bukkit-plugins/packsshop/ !";

			if(getConfig().getBoolean("update.onlyOPs", true)) {

				if(e.getPlayer().isOp()) e.getPlayer().sendMessage(message);

			} else {

				e.getPlayer().sendMessage(message);

			}

		}

	}

	private boolean setupEconomy() {

        RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);

        if (economyProvider != null) {

            econ = economyProvider.getProvider();

        }

        return (econ != null);

    }

	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

		if(cmd.getName().equalsIgnoreCase("packsshop")) {

			if(sender.isOp() == false) {

				if(sender.hasPermission("packsshop.use") == false) {

					sender.sendMessage(getConfig().getString("messages.nopermission", "§4You can't do that!"));
					return true;

				}

			}

			if(args.length >= 2) {

				if(getConfig().contains("packs." + args[0].toString())) {

					if(getConfig().contains("packs." + args[0].toString() + ".items")) {

						List<String> items = getConfig().getStringList("packs." + args[0].toString() + ".items");

						for(int i = 0; i < items.size(); i++) {

							String item = items.get(i);
							String[] values = item.split("/");

							String name = values[0];
							int q = Integer.valueOf(values[1]);

							String subid = "";

							if(values.length >= 3) subid = values[2];

							Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "give " + args[1].toString() + " " + name + " " + q + " " + subid);

						}

					}

					if(getConfig().contains("packs." + args[0].toString() + ".money")) {

						econ.depositPlayer(args[1].toString(), getConfig().getDouble("packs." + args[0] + ".money"));

					}

				} else {

					sender.sendMessage(getConfig().getString("messages.noexist", "§4This pack doesn't exist!"));

				}

			} else {

				sender.sendMessage(getConfig().getString("messages.arguments", "§4Please provide a minimum of 2 arguments in the command !"));

			}

		} else if(cmd.getName().equalsIgnoreCase("packsreload")) {

			if(sender.isOp() == false) {

				if(sender.hasPermission("packsshop.reload") == false) {

					sender.sendMessage(getConfig().getString("messages.nopermission", "§4You can't do that!"));
					return true;

				}

				this.reloadConfig();

				sender.sendMessage(getConfig().getString("messages.reload", "§2Configuration reloaded!"));

			}

		}

		return true;

	}

    private static boolean compare(String v1, String v2) {
        String s1 = normalisedVersion(v1);
        String s2 = normalisedVersion(v2);
        int cmp = s1.compareTo(s2);
        boolean cmpStr = cmp < 0 ? false : cmp > 0 ? true : true;
        return cmpStr;
    }

    public static String normalisedVersion(String version) {
        return normalisedVersion(version, ".", 4);
    }

    public static String normalisedVersion(String version, String sep, int maxWidth) {
        String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            sb.append(String.format("%" + maxWidth + 's', s));
        }
        return sb.toString();
    }

}


text:
/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tstring.h>
#include <tdebug.h>
#include <bitset>

#include "mpcproperties.h"
#include "mpcfile.h"

using namespace TagLib;

class MPC::Properties::PropertiesPrivate
{
public:
  PropertiesPrivate(const ByteVector &d, long length, ReadStyle s) :
    data(d),
    streamLength(length),
    style(s),
    version(0),
    length(0),
    bitrate(0),
    sampleRate(0),
    channels(0) {}

  ByteVector data;
  long streamLength;
  ReadStyle style;
  int version;
  int length;
  int bitrate;
  int sampleRate;
  int channels;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

MPC::Properties::Properties(const ByteVector &data, long streamLength, ReadStyle style) : AudioProperties(style)
{
  d = new PropertiesPrivate(data, streamLength, style);
  read();
}

MPC::Properties::~Properties()
{
  delete d;
}

int MPC::Properties::length() const
{
  return d->length;
}

int MPC::Properties::bitrate() const
{
  return d->bitrate;
}

int MPC::Properties::sampleRate() const
{
  return d->sampleRate;
}

int MPC::Properties::channels() const
{
  return d->channels;
}

int MPC::Properties::mpcVersion() const
{
  return d->version;
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

static const unsigned short sftable [4] = { 44100, 48000, 37800, 32000 };

void MPC::Properties::read()
{
  if(!d->data.startsWith("MP+"))
    return;

  d->version = d->data[3] & 15;

  unsigned int frames;

  if(d->version >= 7) {
    frames = d->data.mid(4, 4).toUInt(false);

    std::bitset<32> flags(TAGLIB_CONSTRUCT_BITSET(d->data.mid(8, 4).toUInt(false)));
    d->sampleRate = sftable[flags[17] * 2 + flags[16]];
    d->channels = 2;
  }
  else {
    uint headerData = d->data.mid(0, 4).toUInt(false);

    d->bitrate = (headerData >> 23) & 0x01ff;
    d->version = (headerData >> 11) & 0x03ff;
    d->sampleRate = 44100;
    d->channels = 2;

    if(d->version >= 5)
      frames = d->data.mid(4, 4).toUInt(false);
    else
      frames = d->data.mid(6, 2).toUInt(false);
  }

  uint samples = frames * 1152 - 576;

  d->length = d->sampleRate > 0 ? (samples + (d->sampleRate / 2)) / d->sampleRate : 0;

  if(!d->bitrate)
    d->bitrate = d->length > 0 ? ((d->streamLength * 8L) / d->length) / 1000 : 0;
}


text:
module Hackbot
  module SlackInteraction
    extend ActiveSupport::Concern

    def send_msg(channel, msg)
      opts = HashWithIndifferentAccess.new(as_user: true)

      if msg.is_a? String
        opts[:text] = msg
      else
        opts = opts.merge(msg)
      end

      if opts[:attachments]
        opts[:attachments] = insert_attachment_defaults(opts[:attachments])
      end

      resp = ::SlackClient::Chat.send_msg(channel, nil, access_token, opts)

      sleep 1 # space out calls to slack's api to prevent rate limiting

      resp
    end

    def attach(channel, *attachments)
      send_msg(channel, attachments: attachments)
    end

    # Commenting because this method's name is somewhat confusing. Please rename
    # if you can think of something better.
    #
    # This method updates the message that triggered action with the passed in
    # message contents. It uses action's special response_url attribute to
    # update the source message without leaving a note in the user's Slack
    # client saying that the source message was edited, making the UX of the
    # edit much nicer.
    #
    # The whole behavior of response_url can be quite confusing and difficult to
    # understand -- the first thing to understand is that the request format is
    # different from regular Web API calls and, therefore, can't be used with
    # our current SlackClient implementation.
    #
    # Docs: https://api.slack.com/docs/message-buttons#overview
    def update_action_source(msg, action_event = event)
      if msg[:attachments]
        msg[:attachments] = insert_attachment_defaults(msg[:attachments])
      end

      payload = { token: access_token, **msg }

      RestClient::Request.execute(
        method: :post,
        url: action_event[:response_url],
        payload: payload.to_json
      )
    end

    # Warning: this currently only works for action sources that have a single
    # attachment with actions, you will likely need to modify this method for
    # more complex cases.
    #
    # This updates the action source to remove its actions and set adds a new
    # attachment with a field set to the given result_str. You should be using
    # this to give the user the results of the action they invoked.
    def send_action_result(result_str)
      attachments = [**event[:msg][:attachments].first, actions: []]
      attachments << { fields: [title: result_str] }
      update_action_source(
        **event[:msg],
        attachments: attachments
      )
    end

    def send_file(channel, filename, file)
      SlackClient::Files.upload(
        channel,
        filename,
        file,
        access_token
      )
    end

    private

    def insert_attachment_defaults(attachments)
      mutated = attachments.deep_dup

      mutated.each do |a|
        # Enable text formatting for all possible values by default
        #
        # Docs: https://api.slack.com/docs/message-formatting#message_formatting
        a[:mrkdwn_in] ||= %w[pretext text fields]

        # Set a default, somewhat useful fallback
        a[:fallback] ||= 'You must use a Slack client that supports '\
                         'attachments to view this'

        insert_action_defaults!(a) if a[:actions]
      end

      mutated
    end

    def insert_action_defaults!(attachment)
      # Set callback_id to the current interaction id for attachments that
      # include actions. We don't actually use this anywhere, opting to use
      # our should_handle? method instead to figure out how to handle actions
      # (as of 2017-03-22, at least), but this is a required field for actions
      # to work so we must set it.
      attachment[:callback_id] ||= id

      attachment[:actions].each do |action|
        # Set actions to buttons by default to simplify action usage. As of
        # 2017-03-22, there aren't any other action types, but they may be
        # added in the future.
        action[:type] ||= 'button'

        # Simplify usage by setting a default name.
        action[:name] ||= 'default_name'

        # Set the action's value to its text by default (if you create a button
        # that shows "Yes", it'll send "Yes" back unless you set another value)
        action[:value] ||= action[:text]
      end
    end
  end
end


text:
namespace detail {
static pcstr const s_anti_aim_timeout_string = "anti_aim_timeout";
static pcstr const s_anti_aim_effectors_string = "anti_aim_effectors";
static pcstr const s_anti_aim_freeze_time_string = "anti_aim_freeze_time";
static pcstr const s_anti_aim_max_angle_string = "anti_aim_max_angle";
static pcstr const s_anti_aim_detection_gain_speed_string = "anti_aim_detection_gain_speed";
static pcstr const s_anti_aim_detection_loose_speed_string = "anti_aim_detection_loose_speed";

} // namespace detail

anti_aim_ability::anti_aim_ability(CBaseMonster* const object) : m_object(object) {
    m_effector_id = 0;
    m_max_angle = 0.5f;
    m_last_activated_tick = 0;
    m_last_detection_tick = 0;
    m_last_angle = M_PI;
    m_callback.clear();
}

anti_aim_ability::~anti_aim_ability() { do_deactivate(); }

void anti_aim_ability::load_from_ini(CInifile const* ini, pcstr const section) {
    using namespace detail;

    m_timeout = READ_IF_EXISTS(ini, r_float, section, s_anti_aim_timeout_string, 5.f);
    m_freeze_time = READ_IF_EXISTS(ini, r_float, section, s_anti_aim_freeze_time_string, 1.f);
    m_max_angle = READ_IF_EXISTS(ini, r_float, section, s_anti_aim_max_angle_string, 0.5f);
    m_detection_gain_speed =
        READ_IF_EXISTS(ini, r_float, section, s_anti_aim_detection_gain_speed_string, 1.f);
    m_detection_loose_speed =
        READ_IF_EXISTS(ini, r_float, section, s_anti_aim_detection_loose_speed_string, 0.1f);
    pcstr effectors = READ_IF_EXISTS(ini, r_string, section, s_anti_aim_effectors_string, NULL);

    if (effectors) {
        u32 const num_effectors = _GetItemCount(effectors, ',');
        m_effectors.resize(num_effectors);
        for (u32 i = 0; i < num_effectors; ++i) {
            char effector_name[1024];
            _GetItem(effectors, i, effector_name, ',');
            m_effectors[i] = effector_name;
        }
    }
}

void anti_aim_ability::on_monster_death() { do_deactivate(); }

bool anti_aim_ability::can_detect() {
    CEntityAlive const* enemy = m_object->EnemyMan.get_enemy();
    Fvector const self2enemy = enemy->Position() - m_object->Position();
    Fvector const self_dir = m_object->Direction();
    float angle = angle_between_vectors(self2enemy, self_dir);

    return angle < deg2rad(70.f);
}

bool anti_aim_ability::check_start_condition() {
    if (is_active()) {
        return false;
    }

    if (m_object->GetScriptControl() && !m_object->get_force_anti_aim()) {
        return false;
    }

    if (!m_object->check_start_conditions(ControlCom::eAntiAim)) {
        return false;
    }

    if (m_man->is_captured(ControlCom::eControlAnimation)) {
        return false;
    }

    if (m_man->is_captured(ControlCom::eControlPath)) {
        return false;
    }

    if (m_man->is_captured(ControlCom::eControlMovement)) {
        return false;
    }

    if (is_active()) {
        return false;
    }

    if (!check_update_condition()) {
        return false;
    }

    if (m_object->anim().has_override_animation()) {
        return false;
    }

    if (m_detection_level < 1.f && !m_object->get_force_anti_aim()) {
        return false;
    }

    if (!can_detect()) {
        return false;
    }

    return true;
}

void anti_aim_ability::activate() {
    m_man->capture(this, ControlCom::eControlAnimation);
    m_man->capture(this, ControlCom::eControlPath);
    m_man->capture(this, ControlCom::eControlMovement);
    m_man->subscribe(this, ControlCom::eventAnimationEnd);

    m_man->path_stop(this);
    m_man->move_stop(this);

    m_last_activated_tick = Device.dwTimeGlobal;

    m_animation_hit_tick =
        Device.dwTimeGlobal +
        (TTime)(m_object->anim().get_animation_hit_time(eAnimAntiAimAbility, 0) * 1000);

    MotionID motion;
    float anim_length;
    m_object->anim().get_animation_info(eAnimAntiAimAbility, 0, motion, anim_length);

    SControlAnimationData* ctrl_data =
        (SControlAnimationData*)m_man->data(this, ControlCom::eControlAnimation);
    VERIFY(ctrl_data);

    ctrl_data->global.set_motion(motion);
    ctrl_data->global.actual = false;

    m_animation_end_tick = Device.dwTimeGlobal + (TTime)(anim_length * 1000);

    m_object->set_force_anti_aim(false);
}

void anti_aim_ability::start_camera_effector() {
    VERIFY(!m_effector_id);
    VERIFY(m_effectors.size());
    pcstr const effector_name = m_effectors[rand() % m_effectors.size()].c_str();

    m_effector_id = Actor()->Cameras().RequestCamEffectorId();

    CAnimatorCamEffector* cam_eff = xr_new<CAnimatorCamEffector>();
    cam_eff->SetType((ECamEffectorType)m_effector_id);
    cam_eff->SetCyclic(false);

    if (pSettings->line_exist(effector_name, "cam_eff_hud_affect")) {
        cam_eff->SetHudAffect(!!pSettings->r_bool(effector_name, "cam_eff_hud_affect"));
    }

    LPCSTR fn = pSettings->r_string(effector_name, "cam_eff_name");
    cam_eff->Start(fn);

    m_camera_effector_end_tick = Device.dwTimeGlobal + (TTime)(cam_eff->GetAnimatorLength() * 1000);
    m_camera_effector_end_tick = std::max(m_camera_effector_end_tick, m_animation_end_tick);

    Actor()->Cameras().AddCamEffector(cam_eff);

    if (m_callback) {
        m_callback();
    }
}

void anti_aim_ability::do_deactivate() {
    if (is_active()) {
        if (m_object->Visual()) // when m_object is destroying, visual might be dead already
        {
            m_man->deactivate(this);
        }

        m_object->set_force_anti_aim(false);
    }
}

void anti_aim_ability::deactivate() {
    if (is_active()) {
        return;
    }

    m_man->release(this, ControlCom::eControlAnimation);
    m_man->release(this, ControlCom::eControlPath);
    m_man->release(this, ControlCom::eControlMovement);

    m_man->unsubscribe(this, ControlCom::eventAnimationEnd);

    if (Actor()) {
        Actor()->Cameras().RemoveCamEffector((ECamEffectorType)m_effector_id);
    }

    m_effector_id = 0;
    m_last_detection_tick = Device.dwTimeGlobal;
    m_last_angle = M_PI;
    m_detection_level = 0.f;
}

float anti_aim_ability::calculate_angle() const {
    float const opposite_angle_return_value = M_PI;

    if (!m_object->EnemyMan.see_enemy_now(Actor())) {
        return opposite_angle_return_value;
    }

    Fvector const self_dir = Actor()->Cameras().Direction();

    Fvector monster_center;
    m_object->Center(monster_center);
    Fvector monster_head = get_head_position(m_object);

    Fvector const actor_head = get_head_position(Actor());
    Fvector const to_monster_center = monster_center - actor_head;
    Fvector const to_monster_head = monster_head - actor_head;
    float const max_deviation = angle_between_vectors(to_monster_center, to_monster_head);
    float const deviation = angle_between_vectors(to_monster_center, self_dir);

    return std::max(0.f, deviation - max_deviation);
}

#include "../../level_debug.h"
#include "../../debug_text_tree.h"

extern CActor* g_actor;

bool anti_aim_ability::check_update_condition() const {
    if (!m_object->g_Alive() || !g_actor || !Actor()->g_Alive())
        return false;

    CEntityAlive const* enemy = m_object->EnemyMan.get_enemy();
    if (enemy != Actor())
        return false;

    if (!smart_cast<CWeapon*>(Actor()->inventory().ActiveItem()))
        return false;

    return true;
}

void anti_aim_ability::update_schedule() {
#ifdef DEBUG_STATE
    DBG().get_text_tree().clear();
    debug::text_tree& text_tree = DBG().get_text_tree().find_or_add("ActorView");
    text_tree.add_line("detection_level", m_detection_level);
#endif // #ifdef DEBUG_STATE

    if (!check_update_condition()) {
        do_deactivate();
        return;
    }

    if (check_start_condition()) {
        m_man->activate(ControlCom::eAntiAim);
    }

    if (is_active()) {
#ifdef DEBUG_STATE
        text_tree.add_line("state", "activated");
#endif // #ifdef DEBUG_STATE

        if (Device.dwTimeGlobal < m_animation_hit_tick) {
            return;
        }
        if (m_effector_id == 0) {
            start_camera_effector();
        }
        if (Device.dwTimeGlobal < m_camera_effector_end_tick) {
            return;
        }
        do_deactivate();
    }

    if (Device.dwTimeGlobal < m_last_activated_tick + (TTime)(m_timeout * 1000)) {
#ifdef DEBUG_STATE
        text_tree.add_line("state", "colddown");
#endif // #ifdef DEBUG_STATE
        return;
    }

#ifdef DEBUG_STATE
    text_tree.add_line("state", "deactivated");
#endif // #ifdef DEBUG_STATE

    if (m_last_detection_tick == 0) {
        m_last_detection_tick = Device.dwTimeGlobal;
    }

    float const detect_delta = (Device.dwTimeGlobal - m_last_detection_tick) / 1000.f;
    m_last_detection_tick = Device.dwTimeGlobal;

    float const angle = calculate_angle();
    float const average_angle = std::min(m_max_angle, (angle + m_last_angle) / 2);
    float const relative_angle = (m_max_angle - average_angle) / m_max_angle;
    float const detect_speed = can_detect() ? xr::sqr(relative_angle) * m_detection_gain_speed : 0;

    m_detection_level += (detect_speed - m_detection_loose_speed) * detect_delta;
    clamp(m_detection_level, 0.f, 1.f);
    m_last_angle = angle;
}


text:
title       : "Inferential Statistics:"
subtitle    : "Dependent Samples t-Tests"
author      : "William R. Buchanan, Ph.D."
job         : "Strategic Data Fellow at MDE/Adjunct Prof at JSU"
framework   : io2012        # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      #
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
knit        : slidify::knit2slides

---

## Overview
* Review
* R stuff
* Model Assumptions
	+ Same subjects
	+ Distribution of the Outcome
* Dependent Samples t-Tests
     + Choosing between dependent and independent samples t-tests
     + Examples
* Next Class

---

## Review
* How many groups of subjects (students) can you compare when using an independent samples t-test?
* What does the p-value from a t-test indicate?
* Explain the 95% Confidence Interval in your own words.
* Are statistically significant differences __always__ practically significant?  Give an example to support your answer
* Give an example of a hypothesis that you could test using a t-test.

---

```r
# Load the foreign data package and the ggplot2 package
library("foreign"); library("ggplot2")

# Store the URL where the data can be accessed
url <- "http://www.paces-consulting.org/stata/JSU/Fall2014/"

# Load either your data or the example data (Substitute your name to get your data)
example <- as.data.frame(read.dta(paste0(url, "JohnDoe-task3.dta")))
```

---

## R Stuff
* As you'll see soon enough, dependent samples t-tests do things a bit differently than
independent samples t-tests, and in order to fully appreciate the assumptions, we need to
be able to do a bit of data manipulation
* You've done basic arithmetic in R during the DataCamp assignment, and now we're going to
compare that with a little bit of data management to help you look at/assess the assumptions
of the model you'll end up fitting to your data
* Remember that you can refer to a variable in a dataframe using these types of references
     + `example$mthscore2`
     + `example["rlascore1"]`
     + `example[, 14]`
* In the first example `example` is the name of your data object, `$` is a symbol used to reference a column within that data object, and `mthscore2` is the name of the variable you're interested in
* In the second example `example` is still the name of your data object and `["rlascore1"]` is the name of the variable you're interested in
* In the last example, `example` is still the name of your data object and `[, 14]` is the position - or column number - for the variable you are interested in

---

* You should remember that you can use objects for basic arithmetic:
     + `x <- 5; y <- 3; x - y` (you should see `[1] 2` if you do that in R)
* You should also remember from the graph examples that you can _recursively_ create objects
     + In this context, remember the cases in the examples/class where we assigned a result to an
     object that included itself like `x <- 5; x <- x - 3`
* We can combine those ideas to create new variables that contain results like this as well

---

```r
# Create a new variable containing the difference between math scores
example$mthdiff <- example$mthscore2 - example$mthscore1

# Create a new variable containing the difference between reading scores
example$rladiff <- example$rlascore2 - example$rlascore1

# Look at summaries of these variables
summary(example[c("rladiff", "mthdiff")])
```

```
##     rladiff         mthdiff
##  Min.   :-35     Min.   :-3
##  1st Qu.:  0     1st Qu.: 6
##  Median :  6     Median : 8
##  Mean   :  7     Mean   : 8
##  3rd Qu.: 13     3rd Qu.:11
##  Max.   : 50     Max.   :22
##  NA's   :20743   NA's   :12808
```

---

# Distribution of the outcome
* The data must still be measured on the intervallic/ratio scale
* The difference between __independent__ and __dependent__ t-tests assumptions is :
     + Independent samples t-tests assume the distribution of the _outcome variable_ is approximately
     Gaussian (normal; looks like a bell curve)
     + Dependent samples t-tests assume that the __difference__ between the two measures being
     compared are approximately Gaussian (normal; looks like a bell curve)
* The way that you can assess this, is by doing what we did above (e.g., creating a new variable with
the difference between the two meausres) and graphing that distribution

---

```r
# Create a graph of the distribution of the difference in the scores
ggplot(data = example, aes(x = mthdiff)) + geom_density() + #
ggtitle("Distribution of the Difference in Math Scores: \nPrior vs Current Year") + #
xlab("Difference Score") + ylab("Density of Observations")
```

---

```r
# Create a graph of the distribution of the difference in the scores
ggplot(data = example, aes(x = rladiff)) + geom_density() + #
ggtitle("Distribution of the Difference in Reading Scores: \nPrior vs Current Year") + #
xlab("Difference Score") + ylab("Density of Observations")
```

---

# Same Subjects
* For __independent__ samples t-tests the students can only appear in one group or the other
* For __dependent__ samples t-tests you are comparing the students to themselves across two measures
* So for a __dependent__ or __paired__ samples t-test, there is no grouping variable because you are
comparing the difference in the means of the same students (e.g., comparing how students in your
class did on test 1 with how they did on test 2)

---

## Dependent Samples t-Tests
* Last week, when we discussed independent samples t-tests, the discussion focused on two distinct
groups of subjects (students in our example data) that did not overlap (e.g., a student could only
belong to a single group)
     + _independent samples_ is actually telling us that the two groups should be mutually exclusive
     (e.g., cannot belong to both groups) and should be independent of one another (e.g., you
     wouldn't compare a subset of a group with the group as a whole [e.g., you wouldn't compare the
     mean of Hispanic/Latino males to the mean of all Hispanics/Latinos])
* __Dependent samples__ or __paired samples__ t-tests have a very different assumption about the
subjects, which is that you are comparing the same subjects across two measures (e.g., comparing
the students' scores from last year with the current year)
     + _dependent_ or _paired_ samples implies that the measures are paired by subjected (e.g., the
     outcome variables are each paired with the same student) and/or that the measures are dependent
     on time (e.g., the same measurement is used at time 1 and time2)
     + This may sound like there isn't a difference, but _paired_ implied that you can test the
     difference in the means of reading and math tests for the same students (e.g., see if there is
     a difference in the means of the two scores)
* Give an example of when you may want to use a dependent/paired samples t-test

---

## Choosing between dependent and independent samples t-tests?
* If you are interested in comparing two distinct groups of observations use the __independent__
samples t-test
     + You want to compare the scores of students getting free lunch vs students not getting free
     lucn on the same test
     + You want to compare the heights of boys vs girls
* If you are interested in comparing the same students over time, or the same students on two
different measures, use a __dependent__ samples t-test
     + You want to compare whether there is a difference in reading and math scores for the students
     in your classroom
     + You want to compare whether or not the difference between student scores on the first 9-week
     exam is different from their scores on the second 9-week exam (e.g., did the scores go up down
     or stay the same on average)
* Remember that although it is possible to do some of these things, it may not make practical or
theorical sense to do so
* When deciding if you should/shouldn't do something for a t-test ask yourself if it is something
that you think would be helpful to you and/or your colleagues to know about the student outcomes

---

## Examples

```r
# Test first hypothesis example
t.test(example$mthscore2, example$mthscore1, paired = TRUE)
```

```
##
## 	Paired t-test
##
## data:  example$mthscore2 and example$mthscore1
## t = 774, df = 120533, p-value < 2.2e-16
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  8.119 8.160
## sample estimates:
## mean of the differences
##                   8.139
```

---

## Next Class
* Simple correlations
* Use the task3 dataset for the task4 assignment
* There may be a new data set for the final so be sure that you are comfortable finding out how to
label your graphs using information from the dataset (in previous weeks' slides) and are comfortable
substituting different variables into the examples


text:
using namespace Engine;

Level::Level() {
}

Level::~Level() {
}


text:
My collections

There are no collection. <router-link to="/create-collection">Create</router-link>

        Add a category


text:
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Unit tests for goog.dom.safe.
 */

goog.provide('goog.dom.safeTest');
goog.setTestOnly('goog.dom.safeTest');

goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.safe');
goog.require('goog.dom.safe.InsertAdjacentHtmlPosition');
goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeScript');
goog.require('goog.html.SafeStyle');
goog.require('goog.html.SafeUrl');
goog.require('goog.html.TrustedResourceUrl');
goog.require('goog.html.testing');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('goog.testing');
goog.require('goog.testing.jsunit');
goog.require('goog.userAgent');

var mockWindowOpen;

function tearDown() {
  if (mockWindowOpen) {
    mockWindowOpen.$tearDown();
  }
}

function testInsertAdjacentHtml() {
  var writtenHtml;
  var writtenPosition;
  var mockNode = /** @type {!Node} */ ({
    'insertAdjacentHTML': function(position, html) {
      writtenPosition = position;
      writtenHtml = html;
    }
  });

  goog.dom.safe.insertAdjacentHtml(
      mockNode, goog.dom.safe.InsertAdjacentHtmlPosition.BEFOREBEGIN,
      goog.html.SafeHtml.create('div', {}, 'foobar'));
  assertEquals('
foobar
', writtenHtml);
  assertEquals('beforebegin', writtenPosition);
}

function testSetInnerHtml() {
  var mockElement =
      /** @type {!Element} */ ({'tagName': 'DIV', 'innerHTML': 'blarg'});
  var html = '


text:
<?php

include(__DIR__.'/config.php');
include(__DIR__.'/dynamicMenu.php');

$menu = array(
	'home' => array('text' =>'Home', 'url' =>'?p=home'),
	'away' => array('text' =>'Away', 'url' =>'?p=away'),
	'about' => array('text' =>'About', 'url' =>'?p=about'));

$shire['navMenu'] = CNavigation::GenerateMenu($menu);
$shire['title'] = "Hello World!";
$shire['header'] = <<<EOD

Shire webbtemplate
Återanvändbara moduler för webbutveckling med PHP
EOD;

$shire['main'] = <<<EOD

Hej världen!

Detta är en exempelsida som visar hur shire ser ut och fungerar.

EOD;

$shire['footer'] = <<<EOD
Copyright (c) Patrik Eliasson (pael10@student.bth.se) | Shire på GitHub | Unicorn
EOD;

include(SHIRE_THEME_PATH);


text:
"use strict";
var $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__,
    $__TempVarTransformer_46_js__,
    $__ParseTreeFactory_46_js__,
    $__PlaceholderParser_46_js__,
    $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__;
var $__0 = ($___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__ = require("../syntax/trees/ParseTreeType.js"), $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__ && $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__.__esModule && $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__ || {default: $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__}),
    FOR_OF_STATEMENT = $__0.FOR_OF_STATEMENT,
    VARIABLE_DECLARATION_LIST = $__0.VARIABLE_DECLARATION_LIST,
    LABELLED_STATEMENT = $__0.LABELLED_STATEMENT;
var TempVarTransformer = ($__TempVarTransformer_46_js__ = require("./TempVarTransformer.js"), $__TempVarTransformer_46_js__ && $__TempVarTransformer_46_js__.__esModule && $__TempVarTransformer_46_js__ || {default: $__TempVarTransformer_46_js__}).TempVarTransformer;
var $__2 = ($__ParseTreeFactory_46_js__ = require("./ParseTreeFactory.js"), $__ParseTreeFactory_46_js__ && $__ParseTreeFactory_46_js__.__esModule && $__ParseTreeFactory_46_js__ || {default: $__ParseTreeFactory_46_js__}),
    id = $__2.createIdentifierExpression,
    createMemberExpression = $__2.createMemberExpression,
    createVariableStatement = $__2.createVariableStatement;
var $__3 = ($__PlaceholderParser_46_js__ = require("./PlaceholderParser.js"), $__PlaceholderParser_46_js__ && $__PlaceholderParser_46_js__.__esModule && $__PlaceholderParser_46_js__ || {default: $__PlaceholderParser_46_js__}),
    parseStatement = $__3.parseStatement,
    parseStatements = $__3.parseStatements;
var $__4 = ($___46__46__47_syntax_47_trees_47_ParseTrees_46_js__ = require("../syntax/trees/ParseTrees.js"), $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__ && $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__.__esModule && $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__ || {default: $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__}),
    AnonBlock = $__4.AnonBlock,
    LabelledStatement = $__4.LabelledStatement;
var ForOfTransformer = function($__super) {
  function ForOfTransformer() {
    $traceurRuntime.superConstructor(ForOfTransformer).apply(this, arguments);
  }
  return ($traceurRuntime.createClass)(ForOfTransformer, {
    transformForOfStatement: function(original) {
      return this.transformForOfStatement_(original, []);
    },
    transformForOfStatement_: function(original, labelSet) {
      var tree = $traceurRuntime.superGet(this, ForOfTransformer.prototype, "transformForOfStatement").call(this, original);
      var iter = id(this.getTempIdentifier());
      var result = id(this.getTempIdentifier());
      var label = id(this.getTempIdentifier());
      var normalCompletion = id(this.getTempIdentifier());
      var throwCompletion = id(this.getTempIdentifier());
      var exception = id(this.getTempIdentifier());
      var ex = id(this.getTempIdentifier());
      var labelledStatement;
      var innerStatement;
      var assignment;
      if (tree.initializer.type === VARIABLE_DECLARATION_LIST) {
        assignment = createVariableStatement(tree.initializer.declarationType, tree.initializer.declarations[0].lvalue, createMemberExpression(result, 'value'));
      } else {
        assignment = parseStatement($traceurRuntime.getTemplateObject(["", " = ", ".value;"]), tree.initializer, result);
      }
      innerStatement = parseStatement($traceurRuntime.getTemplateObject(["\n        for (var ", ",\n                 ", " = (", ")[Symbol.iterator]();\n             !(", " = (", " = ", ".next()).done);\n             ", " = true) {\n          ", "\n          ", "\n        }"]), result, iter, tree.collection, normalCompletion, result, iter, normalCompletion, assignment, tree.body);
      while (labelledStatement = labelSet.pop()) {
        innerStatement = new LabelledStatement(labelledStatement.location, labelledStatement.name, innerStatement);
      }
      return new AnonBlock(null, parseStatements($traceurRuntime.getTemplateObject(["\n        var ", " = true;\n        var ", " = false;\n        var ", " = undefined;\n        try {\n          ", "\n        } catch (", ") {\n          ", " = true;\n          ", " = ", ";\n        } finally {\n          try {\n            if (!", " && ", ".return != null) {\n              ", ".return();\n            }\n          } finally {\n            if (", ") {\n              throw ", ";\n            }\n          }\n        }"]), normalCompletion, throwCompletion, exception, innerStatement, ex, throwCompletion, exception, ex, normalCompletion, iter, iter, throwCompletion, exception));
    },
    transformLabelledStatement: function(tree) {
      var labelSet = [tree];
      var statement = tree.statement;
      while (statement.type === LABELLED_STATEMENT) {
        labelSet.push(statement);
        statement = statement.statement;
      }
      if (statement.type !== FOR_OF_STATEMENT) {
        return $traceurRuntime.superGet(this, ForOfTransformer.prototype, "transformLabelledStatement").call(this, tree);
      }
      return this.transformForOfStatement_(statement, labelSet);
    }
  }, {}, $__super);
}(TempVarTransformer);
Object.defineProperties(module.exports, {
  ForOfTransformer: {get: function() {
      return ForOfTransformer;
    }},
  __esModule: {value: true}
});


text:
from __future__ import unicode_literals

class API(object):
    """Configuration object containing the URLs for the Box API."""
    BASE_API_URL = 'https://api.box.com/2.0'
    UPLOAD_URL = 'https://upload.box.com/api/2.0'
    OAUTH2_API_URL = 'https://api.box.com/oauth2'  # <https://developers.box.com/docs/#oauth-2>
    OAUTH2_AUTHORIZE_URL = 'https://app.box.com/api/oauth2/authorize'  # <https://developers.box.com/docs/#oauth-2-authorize>


text:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "SURF2017";
$db = "molecules";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// sql to create table
$sql = "CREATE TABLE st (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

echo "YAYY";

$handle = @fopen("data.txt", "r");

while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 4096);
 // Read a line.
list($a,$b,$c)=explode("|",$buffer);
//Separate string by the means of |
echo $a."-".$b."-".$c."<br>";
$sql = "INSERT INTO data_table (iddata, name, age) VALUES('".$a."','".$b."',".$c.")";
mysql_query($sql,$conn) or die(mysql_error());
}

$conn->close();

?>


text:
I wasn't able to reach typerighter.com or the pieces that help it run without an internet connection.

Perhaps, a pen and paper instead?


text:
template <class T>
class MemoryPool
{
public:
    MemoryPool(size_t nSize = EXPANSION_SIZE);
    ~MemoryPool();

    inline void* Alloc(size_t nSize);
    inline void Free(void* pElement);

private:
    MemoryPool<T>* m_pNext;
    enum {EXPANSION_SIZE = 32};

    void ExpandFreeList(int nSize = EXPANSION_SIZE);
};

template <class T>
void MemoryPool<T>::ExpandFreeList(int nSize)
{

}


text:
/**
 * Created by ZhiyuanSun on 16/8/18.
 */
import React, { Component } from 'react';

export default class SliderArrows extends Component {
  constructor(props) {
    super(props);
  }

  handleArrowClick(option) {
    this.props.turn(option);
  }

  render() {
    return (
      <div className="slider-arrows-wrap">
        <span
          className="slider-arrow slider-arrow-left"
          onClick={this.handleArrowClick.bind(this, -1)}>
          <
        </span>
        <span
          className="slider-arrow slider-arrow-right"
          onClick={this.handleArrowClick.bind(this, 1)}>
          >
        </span>
      </div>
    );
  }
}


text:
/**
 * @module bot-chooser-sk
 * @description
bot-chooser-sk

 *
 *

 * This element pops up a dialog with OK and Cancel buttons. Its open method
 * returns a Promise which will resolve when the user clicks OK after selecting
 * a bot or reject when the user clicks Cancel.
 *

 *
 */
import { define } from 'elements-sk/define';
import { html, render, TemplateResult } from 'lit-html';
import { $$ } from 'common-sk/modules/dom';

import 'elements-sk/styles/buttons';
import 'elements-sk/styles/select';
import { Incident } from '../json';

export class BotChooserSk extends HTMLElement {
  private dialog: HTMLDialogElement | null = null;

  private resolve: ((value: string | undefined)=> void) | null = null;

  private bots_to_incidents: Record<string, Incident[]> = {};

  private selected: string = '';

  private static template = (ele: BotChooserSk) => html`<dialog>${ele.displayDialogContents()}</dialog>`;

  connectedCallback(): void {
    this._render();
    this.dialog = $$('dialog', this);
  }

  /**
   * Display the dialog.
   *
   * @param bots_to_incidents Map of bots to their incidents.
   * @param bots_to_ignore Which bots should be ignored.
   * @returns Returns a Promise that resolves on OK, and rejects on Cancel.
   *
   */
  public open(bots_to_incidents: Record<string, Incident[]>, bots_to_ignore: string[]): Promise<string | undefined> {
    this.bots_to_incidents = {};
    Object.keys(bots_to_incidents).forEach((bot) => {
      if (bots_to_ignore.includes(bot)) {
        return;
      }
      this.bots_to_incidents[bot] = bots_to_incidents[bot];
    });
    this._render();
    this.dialog!.showModal();

    const selectElem = $$('select', this) as HTMLSelectElement;
    if (selectElem) {
      selectElem.focus();
      if (selectElem.length > 0) {
        // Select the first option.
        this.selected = selectElem.options[0].value;
        selectElem.selectedIndex = 0;
      }
    }
    return new Promise((resolve) => {
      this.resolve = resolve;
    });
  }

  private displayBotOptions(): TemplateResult[] {
    const botsHTML: TemplateResult[] = [];
    Object.keys(this.bots_to_incidents).forEach((bot) => {
      botsHTML.push(html`
        <option value=${bot}>${bot} [${this.bots_to_incidents[bot].map((i) => i.params.alertname).join(',')}]</option>
      `);
    });
    return botsHTML;
  }

  private displayDialogContents(): TemplateResult {
    if (Object.keys(this.bots_to_incidents).length === 0) {
      return html`

No active bot alerts found

          <button @click=${this.dismiss}>OK</button>

      `;
    }
    return html`

Bots with active alerts

        <select size=10 @input=${this.input} @keyup=${this.keyup}>
          ${this.displayBotOptions()}
        </select>

          <button @click=${this.dismiss}>Cancel</button>
          <button @click=${this.confirm}>OK</button>

      `;
  }

  private input(e: Event): void {
    this.selected = (e.target as HTMLInputElement).value;
  }

  private dismiss(): void {
    this.dialog!.close();
    this.resolve!(undefined);
  }

  private confirm(): void {
    this.dialog!.close();
    this.resolve!(this.selected);
  }

  private keyup(e: KeyboardEvent): void {
    if (e.key === 'Enter') {
      this.confirm();
    }
  }

  private _render(): void {
    render(BotChooserSk.template(this), this, { eventContext: this });
  }
}

define('bot-chooser-sk', BotChooserSk);


text:
package abstractinnerclass;

import static com.google.j2cl.integration.testing.Asserts.assertTrue;

public class Main {
  interface A {
    int foo();
  }

  abstract static class B implements A {
    int bar() {
      return foo();
    }
  }

  abstract class C implements A {
    int bar() {
      return foo();
    }
  }

  static class BB extends B {
    @Override
    public int foo() {
      return 10;
    }
  }

  class CC extends C {
    @Override
    public int foo() {
      return 20;
    }
  }

  public static void main(String... args) {
    assertTrue(10 == new BB().bar());
    assertTrue(20 == new Main().new CC().bar());
  }
}