text:
namespace {

ChromeAuthenticatorRequestDelegate::TestObserver* g_observer = nullptr;

// Returns true iff |relying_party_id| is listed in the
// SecurityKeyPermitAttestation policy.
bool IsWebauthnRPIDListedInEnterprisePolicy(
    content::BrowserContext* browser_context,
    const std::string& relying_party_id) {
  const Profile* profile = Profile::FromBrowserContext(browser_context);
  const PrefService* prefs = profile->GetPrefs();
  const base::ListValue* permit_attestation =
      prefs->GetList(prefs::kSecurityKeyPermitAttestation);
  return std::any_of(permit_attestation->GetList().begin(),
                     permit_attestation->GetList().end(),
                     [&relying_party_id](const base::Value& v) {
                       return v.GetString() == relying_party_id;
                     });
}

std::string Base64(base::span<const uint8_t> in) {
  std::string ret;
  base::Base64Encode(
      base::StringPiece(reinterpret_cast<const char*>(in.data()), in.size()),
      &ret);
  return ret;
}

absl::optional<std::string> GetString(const base::Value& dict,
                                      const char* key) {
  const base::Value* v = dict.FindKey(key);
  if (!v || !v->is_string()) {
    return absl::nullopt;
  }
  return v->GetString();
}

template <size_t N>
bool CopyBytestring(std::array<uint8_t, N>* out,
                    absl::optional<std::string> value) {
  if (!value) {
    return false;
  }

  std::string bytes;
  if (!base::Base64Decode(*value, &bytes) || bytes.size() != N) {
    return false;
  }

  std::copy(bytes.begin(), bytes.end(), out->begin());
  return true;
}

bool CopyBytestring(std::vector<uint8_t>* out,
                    absl::optional<std::string> value) {
  if (!value) {
    return false;
  }

  std::string bytes;
  if (!base::Base64Decode(*value, &bytes)) {
    return false;
  }

  out->clear();
  out->insert(out->begin(), bytes.begin(), bytes.end());
  return true;
}

bool CopyString(std::string* out, absl::optional<std::string> value) {
  if (!value) {
    return false;
  }
  *out = *value;
  return true;
}

#if defined(OS_MAC)
const char kWebAuthnTouchIdMetadataSecretPrefName[] =
    "webauthn.touchid.metadata_secret";
#endif

const char kWebAuthnCablePairingsPrefName[] = "webauthn.cablev2_pairings";

// The |kWebAuthnCablePairingsPrefName| preference contains a list of dicts,
// where each dict has these keys:
const char kPairingPrefName[] = "name";
const char kPairingPrefContactId[] = "contact_id";
const char kPairingPrefTunnelServer[] = "tunnel_server";
const char kPairingPrefId[] = "id";
const char kPairingPrefSecret[] = "secret";
const char kPairingPrefPublicKey[] = "pub_key";
const char kPairingPrefTime[] = "time";

// DeleteCablePairingByPublicKey erases any pairing with the given public key
// from |list|.
void DeleteCablePairingByPublicKey(base::ListValue* list,
                                   const std::string& public_key_base64) {
  list->EraseListValueIf([&public_key_base64](const auto& value) {
    if (!value.is_dict()) {
      return false;
    }
    const base::Value* pref_public_key = value.FindKey(kPairingPrefPublicKey);
    return pref_public_key && pref_public_key->is_string() &&
           pref_public_key->GetString() == public_key_base64;
  });
}

}  // namespace

// ---------------------------------------------------------------------
// ChromeWebAuthenticationDelegate
// ---------------------------------------------------------------------

ChromeWebAuthenticationDelegate::~ChromeWebAuthenticationDelegate() = default;

absl::optional<std::string>
ChromeWebAuthenticationDelegate::MaybeGetRelyingPartyIdOverride(
    const std::string& claimed_relying_party_id,
    const url::Origin& caller_origin) {
  // Don't override cryptotoken processing.
  constexpr char kCryptotokenOrigin[] =
      "chrome-extension://kmendfapggjehodndflmmgagdbamhnfd";
  if (caller_origin == url::Origin::Create(GURL(kCryptotokenOrigin))) {
    return absl::nullopt;
  }

  // Otherwise, allow extensions to use WebAuthn and map their origins
  // directly to RP IDs.
  if (caller_origin.scheme() == "chrome-extension") {
    // The requested RP ID for an extension must simply be the extension
    // identifier because no flexibility is permitted. If a caller doesn't
    // specify an RP ID then Blink defaults the value to the origin's host.
    if (claimed_relying_party_id != caller_origin.host()) {
      return absl::nullopt;
    }
    return caller_origin.Serialize();
  }

  return absl::nullopt;
}

bool ChromeWebAuthenticationDelegate::ShouldPermitIndividualAttestation(
    content::BrowserContext* browser_context,
    const std::string& relying_party_id) {
  constexpr char kGoogleCorpAppId[] =
      "https://www.gstatic.com/securitykey/a/google.com/origins.json";

  // If the RP ID is actually the Google corp App ID (because the request is
  // actually a U2F request originating from cryptotoken), or is listed in the
  // enterprise policy, signal that individual attestation is permitted.
  return relying_party_id == kGoogleCorpAppId ||
         IsWebauthnRPIDListedInEnterprisePolicy(browser_context,
                                                relying_party_id);
}

bool ChromeWebAuthenticationDelegate::SupportsResidentKeys(
    content::RenderFrameHost* render_frame_host) {
  return true;
}

bool ChromeWebAuthenticationDelegate::IsFocused(
    content::WebContents* web_contents) {
  return web_contents->GetVisibility() == content::Visibility::VISIBLE;
}

#if defined(OS_MAC)
// static
ChromeWebAuthenticationDelegate::TouchIdAuthenticatorConfig
ChromeWebAuthenticationDelegate::TouchIdAuthenticatorConfigForProfile(
    Profile* profile) {
  constexpr char kKeychainAccessGroup[] =
      MAC_TEAM_IDENTIFIER_STRING "." MAC_BUNDLE_IDENTIFIER_STRING ".webauthn";

  std::string metadata_secret =
      profile->GetPrefs()->GetString(kWebAuthnTouchIdMetadataSecretPrefName);
  if (metadata_secret.empty() ||
      !base::Base64Decode(metadata_secret, &metadata_secret)) {
    metadata_secret = device::fido::mac::GenerateCredentialMetadataSecret();
    profile->GetPrefs()->SetString(
        kWebAuthnTouchIdMetadataSecretPrefName,
        base::Base64Encode(base::as_bytes(base::make_span(metadata_secret))));
  }

  return TouchIdAuthenticatorConfig{
      .keychain_access_group = kKeychainAccessGroup,
      .metadata_secret = std::move(metadata_secret)};
}

absl::optional<ChromeWebAuthenticationDelegate::TouchIdAuthenticatorConfig>
ChromeWebAuthenticationDelegate::GetTouchIdAuthenticatorConfig(
    content::BrowserContext* browser_context) {
  return TouchIdAuthenticatorConfigForProfile(
      Profile::FromBrowserContext(browser_context));
}
#endif  // defined(OS_MAC)

#if BUILDFLAG(IS_CHROMEOS_ASH)
content::WebAuthenticationDelegate::ChromeOSGenerateRequestIdCallback
ChromeWebAuthenticationDelegate::GetGenerateRequestIdCallback(
    content::RenderFrameHost* render_frame_host) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  aura::Window* window =
      render_frame_host->GetNativeView()->GetToplevelWindow();
  return ash::WebAuthnRequestRegistrar::Get()->GetRegisterCallback(window);
}
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

absl::optional<bool> ChromeWebAuthenticationDelegate::
    IsUserVerifyingPlatformAuthenticatorAvailableOverride(
        content::RenderFrameHost* render_frame_host) {
  // If the testing API is active, its override takes precedence.
  absl::optional<bool> testing_api_override =
      content::WebAuthenticationDelegate::
          IsUserVerifyingPlatformAuthenticatorAvailableOverride(
              render_frame_host);
  if (testing_api_override) {
    return *testing_api_override;
  }

#if defined(OS_WIN)
  // TODO(crbug.com/908622): Enable platform authenticators in Incognito on
  // Windows once the API allows triggering an adequate warning dialog.
  if (render_frame_host->GetBrowserContext()->IsOffTheRecord()) {
    return false;
  }
#endif

  // Chrome disables platform authenticators is Guest sessions. They may be
  // available (behind an additional interstitial) in Incognito mode.
  Profile* profile =
      Profile::FromBrowserContext(render_frame_host->GetBrowserContext());
  if (profile->IsGuestSession()) {
    return false;
  }

  return absl::nullopt;
}

content::WebAuthenticationRequestProxy*
ChromeWebAuthenticationDelegate::MaybeGetRequestProxy(
    content::BrowserContext* browser_context) {
  return extensions::WebAuthenticationProxyServiceFactory::GetForBrowserContext(
      browser_context);
}

// ---------------------------------------------------------------------
// ChromeAuthenticatorRequestDelegate
// ---------------------------------------------------------------------

// static
void ChromeAuthenticatorRequestDelegate::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
#if defined(OS_MAC)
  registry->RegisterStringPref(kWebAuthnTouchIdMetadataSecretPrefName,
                               std::string());
#endif

  registry->RegisterListPref(kWebAuthnCablePairingsPrefName);
}

ChromeAuthenticatorRequestDelegate::ChromeAuthenticatorRequestDelegate(
    content::RenderFrameHost* render_frame_host)
    : render_frame_host_id_(render_frame_host->GetGlobalId()) {
  if (g_observer) {
    g_observer->Created(this);
  }
}

ChromeAuthenticatorRequestDelegate::~ChromeAuthenticatorRequestDelegate() {
  // Currently, completion of the request is indicated by //content destroying
  // this delegate.
  if (weak_dialog_model_) {
    weak_dialog_model_->OnRequestComplete();
  }

  // The dialog model may be destroyed after the OnRequestComplete call.
  if (weak_dialog_model_) {
    weak_dialog_model_->RemoveObserver(this);
    weak_dialog_model_ = nullptr;
  }
}

// static
void ChromeAuthenticatorRequestDelegate::SetGlobalObserverForTesting(
    TestObserver* observer) {
  CHECK(!observer || !g_observer);
  g_observer = observer;
}

base::WeakPtr<ChromeAuthenticatorRequestDelegate>
ChromeAuthenticatorRequestDelegate::AsWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

void ChromeAuthenticatorRequestDelegate::SetRelyingPartyId(
    const std::string& rp_id) {
  transient_dialog_model_holder_ =
      std::make_unique<AuthenticatorRequestDialogModel>(rp_id);
  weak_dialog_model_ = transient_dialog_model_holder_.get();
}

bool ChromeAuthenticatorRequestDelegate::DoesBlockRequestOnFailure(
    InterestingFailureReason reason) {
  if (!IsWebAuthnUIEnabled())
    return false;
  if (!weak_dialog_model_)
    return false;

  switch (reason) {
    case InterestingFailureReason::kTimeout:
      weak_dialog_model_->OnRequestTimeout();
      break;
    case InterestingFailureReason::kKeyNotRegistered:
      weak_dialog_model_->OnActivatedKeyNotRegistered();
      break;
    case InterestingFailureReason::kKeyAlreadyRegistered:
      weak_dialog_model_->OnActivatedKeyAlreadyRegistered();
      break;
    case InterestingFailureReason::kSoftPINBlock:
      weak_dialog_model_->OnSoftPINBlock();
      break;
    case InterestingFailureReason::kHardPINBlock:
      weak_dialog_model_->OnHardPINBlock();
      break;
    case InterestingFailureReason::kAuthenticatorRemovedDuringPINEntry:
      weak_dialog_model_->OnAuthenticatorRemovedDuringPINEntry();
      break;
    case InterestingFailureReason::kAuthenticatorMissingResidentKeys:
      weak_dialog_model_->OnAuthenticatorMissingResidentKeys();
      break;
    case InterestingFailureReason::kAuthenticatorMissingUserVerification:
      weak_dialog_model_->OnAuthenticatorMissingUserVerification();
      break;
    case InterestingFailureReason::kAuthenticatorMissingLargeBlob:
      weak_dialog_model_->OnAuthenticatorMissingLargeBlob();
      break;
    case InterestingFailureReason::kNoCommonAlgorithms:
      weak_dialog_model_->OnNoCommonAlgorithms();
      break;
    case InterestingFailureReason::kStorageFull:
      weak_dialog_model_->OnAuthenticatorStorageFull();
      break;
    case InterestingFailureReason::kUserConsentDenied:
      weak_dialog_model_->OnUserConsentDenied();
      break;
    case InterestingFailureReason::kWinUserCancelled:
      return weak_dialog_model_->OnWinUserCancelled();
  }
  return true;
}

void ChromeAuthenticatorRequestDelegate::RegisterActionCallbacks(
    base::OnceClosure cancel_callback,
    base::RepeatingClosure start_over_callback,
    device::FidoRequestHandlerBase::RequestCallback request_callback,
    base::RepeatingClosure bluetooth_adapter_power_on_callback) {
  request_callback_ = request_callback;
  cancel_callback_ = std::move(cancel_callback);
  start_over_callback_ = std::move(start_over_callback);

  weak_dialog_model_->SetRequestCallback(request_callback);
  weak_dialog_model_->SetBluetoothAdapterPowerOnCallback(
      bluetooth_adapter_power_on_callback);
}

void ChromeAuthenticatorRequestDelegate::ShouldReturnAttestation(
    const std::string& relying_party_id,
    const device::FidoAuthenticator* authenticator,
    bool is_enterprise_attestation,
    base::OnceCallback<void(bool)> callback) {
  if (IsWebauthnRPIDListedInEnterprisePolicy(GetBrowserContext(),
                                             relying_party_id)) {
    // Enterprise attestations should have been approved already and not reach
    // this point.
    DCHECK(!is_enterprise_attestation);
    std::move(callback).Run(true);
    return;
  }

  // Cryptotoken displays its own attestation consent prompt.
  // AuthenticatorCommon does not invoke ShouldReturnAttestation() for those
  // requests.
  if (disable_ui_) {
    NOTREACHED();
    std::move(callback).Run(false);
    return;
  }

#if defined(OS_WIN)
  if (authenticator->IsWinNativeApiAuthenticator() &&
      static_cast<const device::WinWebAuthnApiAuthenticator*>(authenticator)
          ->ShowsPrivacyNotice()) {
    // The OS' native API includes an attestation prompt.
    std::move(callback).Run(true);
    return;
  }
#endif  // defined(OS_WIN)

  weak_dialog_model_->RequestAttestationPermission(is_enterprise_attestation,
                                                   std::move(callback));
}

void ChromeAuthenticatorRequestDelegate::ConfigureCable(
    const url::Origin& origin,
    device::FidoRequestType request_type,
    base::span<const device::CableDiscoveryData> pairings_from_extension,
    device::FidoDiscoveryFactory* discovery_factory) {
  phone_names_.clear();
  phone_public_keys_.clear();

  const bool cable_extension_permitted = ShouldPermitCableExtension(origin);

  std::vector<device::CableDiscoveryData> pairings;
  if (cable_extension_permitted) {
    pairings.insert(pairings.end(), pairings_from_extension.begin(),
                    pairings_from_extension.end());
  }
  const bool cable_extension_provided = !pairings.empty();
  const bool cablev2_extension_provided =
      std::any_of(pairings.begin(), pairings.end(),
                  [](const device::CableDiscoveryData& v) -> bool {
                    return v.version == device::CableDiscoveryData::Version::V2;
                  });

  std::vector<std::unique_ptr<device::cablev2::Pairing>> paired_phones;
  std::vector<AuthenticatorRequestDialogModel::PairedPhone>
      paired_phone_entries;
  base::RepeatingCallback<void(size_t)> contact_phone_callback;
  if (!cable_extension_provided &&
      base::FeatureList::IsEnabled(device::kWebAuthCableSecondFactor)) {
    DCHECK(phone_names_.empty());
    DCHECK(phone_public_keys_.empty());

    paired_phones = GetCablePairings();
    if (!paired_phones.empty()) {
      for (size_t i = 0; i < paired_phones.size(); i++) {
        const auto& phone = paired_phones[i];
        paired_phone_entries.emplace_back(phone->name, i,
                                          phone->peer_public_key_x962);
        phone_names_.push_back(phone->name);
        phone_public_keys_.push_back(phone->peer_public_key_x962);
      }

      contact_phone_callback = discovery_factory->get_cable_contact_callback();
    }
  }
  const bool have_paired_phones = !paired_phones.empty();

  const bool non_extension_cablev2_enabled =
      !cable_extension_permitted &&
      (have_paired_phones ||
       base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport));

  const bool android_accessory_possible =
      base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport) ||
      (cablev2_extension_provided &&
       base::FeatureList::IsEnabled(device::kWebAuthCableServerLink)) ||
      (!cable_extension_permitted &&
       base::FeatureList::IsEnabled(device::kWebAuthCableSecondFactor));

  absl::optional<std::array<uint8_t, device::cablev2::kQRKeySize>>
      qr_generator_key;
  absl::optional<std::string> qr_string;
  if (non_extension_cablev2_enabled ||
      (cablev2_extension_provided &&
       base::FeatureList::IsEnabled(device::kWebAuthCableServerLink))) {
    // A QR key is generated for all caBLEv2 cases but whether the QR code is
    // displayed is up to the UI.
    qr_generator_key.emplace();
    crypto::RandBytes(*qr_generator_key);
    qr_string = device::cablev2::qr::Encode(*qr_generator_key);

    discovery_factory->set_cable_pairing_callback(base::BindRepeating(
        &ChromeAuthenticatorRequestDelegate::HandleCablePairingEvent,
        weak_ptr_factory_.GetWeakPtr()));
    discovery_factory->set_network_context(
        SystemNetworkContextManager::GetInstance()->GetContext());
  }

  if (android_accessory_possible) {
    mojo::Remote<device::mojom::UsbDeviceManager> usb_device_manager;
    content::GetDeviceService().BindUsbDeviceManager(
        usb_device_manager.BindNewPipeAndPassReceiver());
    discovery_factory->set_android_accessory_params(
        std::move(usb_device_manager),
        l10n_util::GetStringUTF8(IDS_WEBAUTHN_CABLEV2_AOA_REQUEST_DESCRIPTION));
  }

  if (cable_extension_provided || non_extension_cablev2_enabled) {
    absl::optional<bool> extension_is_v2;
    if (cable_extension_provided) {
      extension_is_v2 = cablev2_extension_provided;
    }
    weak_dialog_model_->set_cable_transport_info(
        extension_is_v2, std::move(paired_phone_entries),
        std::move(contact_phone_callback), qr_string);
    discovery_factory->set_cable_data(request_type, std::move(pairings),
                                      qr_generator_key,
                                      std::move(paired_phones));
  }
}

void ChromeAuthenticatorRequestDelegate::SelectAccount(
    std::vector<device::AuthenticatorGetAssertionResponse> responses,
    base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)>
        callback) {
  if (disable_ui_) {
    // Cryptotoken requests should never reach account selection.
    NOTREACHED();
    std::move(cancel_callback_).Run();
    return;
  }

  if (!weak_dialog_model_) {
    std::move(cancel_callback_).Run();
    return;
  }

  weak_dialog_model_->SelectAccount(std::move(responses), std::move(callback));
}

void ChromeAuthenticatorRequestDelegate::DisableUI() {
  disable_ui_ = true;
}

bool ChromeAuthenticatorRequestDelegate::IsWebAuthnUIEnabled() {
  // The UI is fully disabled for the entire request duration if either:
  // 1) The request originates from cryptotoken. The UI may be hidden in other
  // circumstances (e.g. while showing the native Windows WebAuthn UI). But in
  // those cases the UI is still enabled and can be shown e.g. for an
  // attestation consent prompt.
  // 2) A specialized UI is replacing the default WebAuthn UI, such as
  // Secure Payment Confirmation or Autofill.
  return !disable_ui_;
}

void ChromeAuthenticatorRequestDelegate::SetConditionalRequest(
    bool is_conditional) {
  is_conditional_ = is_conditional;
}

void ChromeAuthenticatorRequestDelegate::OnTransportAvailabilityEnumerated(
    device::FidoRequestHandlerBase::TransportAvailabilityInfo data) {
  if (g_observer) {
    g_observer->OnTransportAvailabilityEnumerated(this, &data);
  }

  if (disable_ui_ || !transient_dialog_model_holder_) {
    return;
  }

  weak_dialog_model_->AddObserver(this);

  weak_dialog_model_->StartFlow(std::move(data), is_conditional_);

  content::WebContents* web_contents =
      content::WebContents::FromRenderFrameHost(GetRenderFrameHost());
  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  if (browser) {
    browser->window()->UpdatePageActionIcon(PageActionIconType::kWebAuthn);
  }

  ShowAuthenticatorRequestDialog(web_contents,
                                 std::move(transient_dialog_model_holder_));

  if (g_observer) {
    g_observer->UIShown(this);
  }
}

bool ChromeAuthenticatorRequestDelegate::EmbedderControlsAuthenticatorDispatch(
    const device::FidoAuthenticator& authenticator) {
  // Decide whether the //device/fido code should dispatch the current
  // request to an authenticator immediately after it has been
  // discovered, or whether the embedder/UI takes charge of that by
  // invoking its RequestCallback.
  auto transport = authenticator.AuthenticatorTransport();
  return (is_conditional_ || IsWebAuthnUIEnabled()) &&
         (!transport ||  // Windows
          *transport == device::FidoTransportProtocol::kInternal);
}

void ChromeAuthenticatorRequestDelegate::FidoAuthenticatorAdded(
    const device::FidoAuthenticator& authenticator) {
  if (!IsWebAuthnUIEnabled())
    return;

  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->AddAuthenticator(authenticator);
}

void ChromeAuthenticatorRequestDelegate::FidoAuthenticatorRemoved(
    base::StringPiece authenticator_id) {
  if (!IsWebAuthnUIEnabled())
    return;

  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->RemoveAuthenticator(authenticator_id);
}

void ChromeAuthenticatorRequestDelegate::BluetoothAdapterPowerChanged(
    bool is_powered_on) {
  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->OnBluetoothPoweredStateChanged(is_powered_on);
}

bool ChromeAuthenticatorRequestDelegate::SupportsPIN() const {
  return true;
}

void ChromeAuthenticatorRequestDelegate::CollectPIN(
    CollectPINOptions options,
    base::OnceCallback<void(std::u16string)> provide_pin_cb) {
  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->CollectPIN(options.reason, options.error,
                                 options.min_pin_length, options.attempts,
                                 std::move(provide_pin_cb));
}

void ChromeAuthenticatorRequestDelegate::StartBioEnrollment(
    base::OnceClosure next_callback) {
  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->StartInlineBioEnrollment(std::move(next_callback));
}

void ChromeAuthenticatorRequestDelegate::OnSampleCollected(
    int bio_samples_remaining) {
  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->OnSampleCollected(bio_samples_remaining);
}

void ChromeAuthenticatorRequestDelegate::FinishCollectToken() {
  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->FinishCollectToken();
}

void ChromeAuthenticatorRequestDelegate::OnRetryUserVerification(int attempts) {
  if (!weak_dialog_model_)
    return;

  weak_dialog_model_->OnRetryUserVerification(attempts);
}

void ChromeAuthenticatorRequestDelegate::OnStartOver() {
  DCHECK(start_over_callback_);
  start_over_callback_.Run();
}

void ChromeAuthenticatorRequestDelegate::OnModelDestroyed(
    AuthenticatorRequestDialogModel* model) {
  DCHECK(weak_dialog_model_ && weak_dialog_model_ == model);
  weak_dialog_model_ = nullptr;
}

void ChromeAuthenticatorRequestDelegate::OnCancelRequest() {
  // |cancel_callback_| must be invoked at most once as invocation of
  // |cancel_callback_| will destroy |this|.
  DCHECK(cancel_callback_);
  std::move(cancel_callback_).Run();
}

content::RenderFrameHost*
ChromeAuthenticatorRequestDelegate::GetRenderFrameHost() const {
  content::RenderFrameHost* ret =
      content::RenderFrameHost::FromID(render_frame_host_id_);
  DCHECK(ret);
  return ret;
}

content::BrowserContext* ChromeAuthenticatorRequestDelegate::GetBrowserContext()
    const {
  return GetRenderFrameHost()->GetBrowserContext();
}

bool ChromeAuthenticatorRequestDelegate::ShouldPermitCableExtension(
    const url::Origin& origin) {
  if (base::FeatureList::IsEnabled(device::kWebAuthCableExtensionAnywhere)) {
    return true;
  }

  // Because the future of the caBLE extension might be that we transition
  // everything to QR-code or sync-based pairing, we don't want use of the
  // extension to spread without consideration. Therefore it's limited to
  // origins that are already depending on it and test sites.
  if (origin.DomainIs("google.com")) {
    return true;
  }

  const GURL test_site("https://webauthndemo.appspot.com");
  DCHECK(test_site.is_valid());
  return origin.IsSameOriginWith(url::Origin::Create(test_site));
}

// NameForDisplay removes line-breaking characters from |raw_name| to ensure
// that the transport-selection UI isn't too badly broken by nonsense names.
static std::string NameForDisplay(base::StringPiece raw_name) {
  std::u16string unicode_name = base::UTF8ToUTF16(raw_name);
  base::StringPiece16 trimmed_name =
      base::TrimWhitespace(unicode_name, base::TRIM_ALL);
  // These are all the Unicode mandatory line-breaking characters
  // (https://www.unicode.org/reports/tr14/tr14-32.html#Properties).
  constexpr char16_t kLineTerminators[] = {0x0a, 0x0b, 0x0c, 0x0d, 0x85, 0x2028,
                                           0x2029,
                                           // Array must be NUL terminated.
                                           0};
  std::u16string nonbreaking_name;
  base::RemoveChars(trimmed_name, kLineTerminators, &nonbreaking_name);
  return base::UTF16ToUTF8(nonbreaking_name);
}

// PairingFromSyncedDevice extracts the caBLEv2 information from Sync's
// DeviceInfo (if any) into a caBLEv2 pairing. It may return nullptr.
static std::unique_ptr<device::cablev2::Pairing> PairingFromSyncedDevice(
    syncer::DeviceInfo* device,
    const base::Time& now) {
  if (device->last_updated_timestamp() < now) {
    const base::TimeDelta age = now - device->last_updated_timestamp();
    if (age.InHours() > 24 * 14) {
      // Entries older than 14 days are dropped. If changing this, consider
      // updating |cablev2::sync::IDIsValid| too so that the mobile-side is
      // aligned.
      return nullptr;
    }
  }

  const absl::optional<syncer::DeviceInfo::PhoneAsASecurityKeyInfo>&
      maybe_paask_info = device->paask_info();
  if (!maybe_paask_info) {
    return nullptr;
  }

  const syncer::DeviceInfo::PhoneAsASecurityKeyInfo& paask_info =
      *maybe_paask_info;
  auto pairing = std::make_unique<device::cablev2::Pairing>();
  pairing->name = NameForDisplay(device->client_name());

  const absl::optional<device::cablev2::tunnelserver::KnownDomainID>
      tunnel_server_domain = device::cablev2::tunnelserver::ToKnownDomainID(
          paask_info.tunnel_server_domain);
  if (!tunnel_server_domain) {
    // It's possible that a phone is running a more modern version of Chrome
    // and uses an assigned tunnel server domain that is unknown to this code.
    return nullptr;
  }

  pairing->tunnel_server_domain =
      device::cablev2::tunnelserver::DecodeDomain(*tunnel_server_domain);
  pairing->contact_id = paask_info.contact_id;
  pairing->peer_public_key_x962 = paask_info.peer_public_key_x962;
  pairing->secret.assign(paask_info.secret.begin(), paask_info.secret.end());
  pairing->last_updated = device->last_updated_timestamp();

  // The pairing ID from sync is zero-padded to the standard length.
  pairing->id.assign(device::cablev2::kPairingIDSize, 0);
  static_assert(device::cablev2::kPairingIDSize >= sizeof(paask_info.id), "");
  memcpy(pairing->id.data(), &paask_info.id, sizeof(paask_info.id));

  // The channel priority is only approximate and exists to help testing and
  // development. I.e. we want the development or Canary install on a device to
  // shadow the stable channel so that it's possible to test things. This code
  // is matching the string generated by |FormatUserAgentForSync|.
  const std::string& user_agent = device->sync_user_agent();
  if (user_agent.find("-devel") != std::string::npos) {
    pairing->channel_priority = 5;
  } else if (user_agent.find("(canary)") != std::string::npos) {
    pairing->channel_priority = 4;
  } else if (user_agent.find("(dev)") != std::string::npos) {
    pairing->channel_priority = 3;
  } else if (user_agent.find("(beta)") != std::string::npos) {
    pairing->channel_priority = 2;
  } else if (user_agent.find("(stable)") != std::string::npos) {
    pairing->channel_priority = 1;
  } else {
    pairing->channel_priority = 0;
  }

  return pairing;
}

static std::vector<std::unique_ptr<device::cablev2::Pairing>>
GetCablePairingsFromSyncedDevices(Profile* profile) {
  if (g_observer) {
    return g_observer->GetCablePairingsFromSyncedDevices();
  }

  std::vector<std::unique_ptr<device::cablev2::Pairing>> ret;
  syncer::DeviceInfoSyncService* const sync_service =
      DeviceInfoSyncServiceFactory::GetForProfile(profile);
  if (!sync_service) {
    return ret;
  }

  syncer::DeviceInfoTracker* const tracker =
      sync_service->GetDeviceInfoTracker();
  std::vector<std::unique_ptr<syncer::DeviceInfo>> devices =
      tracker->GetAllDeviceInfo();

  const base::Time now = base::Time::Now();
  for (const auto& device : devices) {
    std::unique_ptr<device::cablev2::Pairing> pairing =
        PairingFromSyncedDevice(device.get(), now);
    if (!pairing) {
      continue;
    }
    ret.emplace_back(std::move(pairing));
  }

  return ret;
}

std::vector<std::unique_ptr<device::cablev2::Pairing>>
ChromeAuthenticatorRequestDelegate::GetCablePairings() {
  Profile* profile = Profile::FromBrowserContext(GetBrowserContext());
  if (profile->IsOffTheRecord()) {
    // For Incognito windows we collect the devices from the parent profile.
    // The |AuthenticatorRequestDialogModel| will notice that it's an OTR
    // profile and display a confirmation interstitial for makeCredential calls.
    profile = profile->GetOriginalProfile();
  }

  std::vector<std::unique_ptr<device::cablev2::Pairing>> ret =
      GetCablePairingsFromSyncedDevices(profile);
  std::sort(ret.begin(), ret.end(),
            device::cablev2::Pairing::CompareByMostRecentFirst);

  PrefService* const prefs = profile->GetPrefs();
  const base::ListValue* pref_pairings =
      prefs->GetList(kWebAuthnCablePairingsPrefName);

  for (const auto& pairing : pref_pairings->GetList()) {
    if (!pairing.is_dict()) {
      continue;
    }

    auto out_pairing = std::make_unique<device::cablev2::Pairing>();
    if (!CopyString(&out_pairing->name, GetString(pairing, kPairingPrefName)) ||
        !CopyString(&out_pairing->tunnel_server_domain,
                    GetString(pairing, kPairingPrefTunnelServer)) ||
        !CopyBytestring(&out_pairing->contact_id,
                        GetString(pairing, kPairingPrefContactId)) ||
        !CopyBytestring(&out_pairing->id, GetString(pairing, kPairingPrefId)) ||
        !CopyBytestring(&out_pairing->secret,
                        GetString(pairing, kPairingPrefSecret)) ||
        !CopyBytestring(&out_pairing->peer_public_key_x962,
                        GetString(pairing, kPairingPrefPublicKey))) {
      continue;
    }

    out_pairing->name = NameForDisplay(out_pairing->name);
    ret.emplace_back(std::move(out_pairing));
  }

  // All the pairings from sync come first in |ret|, sorted by most recent
  // first, followed by pairings from prefs, which are known to have unique
  // public keys within themselves. A stable sort by public key will group
  // together any pairings for the same Chrome instance, preferring recent sync
  // records, then |std::unique| will delete all but the first.
  std::stable_sort(ret.begin(), ret.end(),
                   device::cablev2::Pairing::CompareByPublicKey);
  ret.erase(std::unique(ret.begin(), ret.end(),
                        device::cablev2::Pairing::EqualPublicKeys),
            ret.end());

  // ret now contains only a single entry per Chrome install. There can still be
  // multiple entries for a given name, however. Sort by most recent and then by
  // channel. That means that, considering all the entries for a given name,
  // Sync entries on unstable channels have top priority. Within a given
  // channel, the most recent entry has priority.

  std::sort(ret.begin(), ret.end(),
            device::cablev2::Pairing::CompareByMostRecentFirst);
  std::stable_sort(ret.begin(), ret.end(),
                   device::cablev2::Pairing::CompareByLeastStableChannelFirst);

  // The debug log displays in reverse order, so the headline is emitted after
  // the names.
  for (const auto& pairing : ret) {
    FIDO_LOG(DEBUG) << "• " << pairing->name << " " << pairing->last_updated
                    << " priority:" << pairing->channel_priority;
  }
  FIDO_LOG(DEBUG) << "Found " << ret.size() << " caBLEv2 devices";

  return ret;
}

void ChromeAuthenticatorRequestDelegate::HandleCablePairingEvent(
    device::cablev2::PairingEvent event) {
  if (auto* failed_contact_index = absl::get_if<size_t>(&event)) {
    // A pairing was reported to be invalid. Delete it unless it came from Sync,
    // in which case there's nothing to be done.
    ListPrefUpdate update(
        Profile::FromBrowserContext(GetBrowserContext())->GetPrefs(),
        kWebAuthnCablePairingsPrefName);
    DeleteCablePairingByPublicKey(
        update.Get(), Base64(phone_public_keys_[*failed_contact_index]));

    if (weak_dialog_model_) {
      // Contact the next phone with the same name, if any, given that no
      // notification has been sent.
      weak_dialog_model_->OnPhoneContactFailed(
          phone_names_[*failed_contact_index]);
    }
    return;
  }

  // This is called when doing a QR-code pairing with a phone and the phone
  // sends long-term pairing information during the handshake. The pairing
  // information is saved in preferences for future operations.
  if (!base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport)) {
    NOTREACHED();
    return;
  }

  // For Incognito/Guest profiles, pairings will only last for the duration of
  // that session. While an argument could be made that it's safe to persist
  // such pairing for longer, this seems like the safe option initially.
  ListPrefUpdate update(
      Profile::FromBrowserContext(GetBrowserContext())->GetPrefs(),
      kWebAuthnCablePairingsPrefName);

  // Otherwise the event is a new pairing.
  auto& pairing =
      *absl::get_if<std::unique_ptr<device::cablev2::Pairing>>(&event);
  // Find any existing entries with the same public key and replace them. The
  // handshake protocol requires the phone to prove possession of the public
  // key so it's not possible for an evil phone to displace another's pairing.
  std::string public_key_base64 = Base64(pairing->peer_public_key_x962);
  DeleteCablePairingByPublicKey(update.Get(), public_key_base64);

  auto dict = std::make_unique<base::Value>(base::Value::Type::DICTIONARY);
  dict->SetKey(kPairingPrefPublicKey,
               base::Value(std::move(public_key_base64)));
  dict->SetKey(kPairingPrefTunnelServer,
               base::Value(pairing->tunnel_server_domain));
  dict->SetKey(kPairingPrefName, base::Value(std::move(pairing->name)));
  dict->SetKey(kPairingPrefContactId, base::Value(Base64(pairing->contact_id)));
  dict->SetKey(kPairingPrefId, base::Value(Base64(pairing->id)));
  dict->SetKey(kPairingPrefSecret, base::Value(Base64(pairing->secret)));

  base::Time::Exploded now;
  base::Time::Now().UTCExplode(&now);
  dict->SetKey(kPairingPrefTime,
               // RFC 3339 time format.
               base::Value(base::StringPrintf(
                   "%04d-%02d-%02dT%02d:%02d:%02dZ", now.year, now.month,
                   now.day_of_month, now.hour, now.minute, now.second)));

  update->Append(std::move(dict));
}


text:
package com.venky.swf.plugins.collab.db.model.config;

import java.util.List;

import com.venky.geo.GeoLocation;
import com.venky.swf.db.Database;
import com.venky.swf.db.annotations.column.IS_NULLABLE;
import com.venky.swf.db.annotations.column.UNIQUE_KEY;
import com.venky.swf.db.annotations.column.indexing.Index;
import com.venky.swf.db.annotations.model.CONFIGURATION;
import com.venky.swf.db.annotations.model.EXPORTABLE;
import com.venky.swf.db.annotations.model.ORDER_BY;
import com.venky.swf.db.model.Model;
import com.venky.swf.sql.Conjunction;
import com.venky.swf.sql.Expression;
import com.venky.swf.sql.Operator;
import com.venky.swf.sql.Select;

@CONFIGURATION
@EXPORTABLE(false)
@ORDER_BY("NAME")
public interface City extends Model , GeoLocation {
	@Index
	@UNIQUE_KEY("K1,K2")
	public String getName();
	public void setName(String name);

	@Index
	@UNIQUE_KEY("K1,K2")
	@IS_NULLABLE(false)
	public Long getStateId();
	public void setStateId(Long id);
	public State getState();

	@Index
	@UNIQUE_KEY(value = "K2" , allowMultipleRecordsWithNull = false)
	public String getRegionName();
	public void setRegionName(String region);

	public static City findByCountryAndStateAndName(String  countryName , String stateName,String cityName) {
		return findByStateAndName(State.findByCountryAndName(countryName, stateName).getId(), cityName);
	}
	public static City findByStateAndName(long stateId, String cityName) {
		Select s = new Select().from(City.class);
		Expression where = new Expression(s.getPool(),Conjunction.AND);
		where.add(new Expression(s.getPool(),"lower(NAME)",Operator.EQ,cityName.toLowerCase()));
		where.add(new Expression(s.getPool(),"STATE_ID",Operator.EQ,stateId));

		List<City> cities = s.where(where).execute();
		if (cities.size() == 1) {
			return cities.get(0);
		}else {
			City city = Database.getTable(City.class).newRecord();
			city.setStateId(stateId);
			city.setName(cityName);
			city.save();
			return city;
		}
	}

	@IS_NULLABLE
	@UNIQUE_KEY("K3")
	public String getCode();
	public void setCode(String code);

	public static City findByCode(String code) {
		Select s = new Select().from(City.class);
		Expression where = new Expression(s.getPool(), Conjunction.AND);
		where.add(new Expression(s.getPool(),"CODE", Operator.EQ,code));

		List<City> cities = s.where(where).execute();
		if (!cities.isEmpty()) {
			return cities.get(0);
		}else {
			return null;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace MiX.Integrate.Shared.Entities.HosData
{
	public class HosDataRequest
	{
		public HosDataRequest()
		{
			EntityTypeId = ParameterEntityType.Organisation;
			EntityIds = new List<long> { };
		}
		public ParameterEntityType EntityTypeId { get; set; }
		public List<long> EntityIds { get; set; }
	}
}


text:
import os
import random

import screenshot_sync_expectations as expectations

from telemetry import benchmark
from telemetry.core import util
from telemetry.page import page
from telemetry.page import page_test
from telemetry.story import story_set as story_set_module
from telemetry.util import image_util

data_path = os.path.join(
    util.GetChromiumSrcDir(), 'content', 'test', 'data', 'gpu')

class _ScreenshotSyncValidator(page_test.PageTest):
  def CustomizeBrowserOptions(self, options):
    options.AppendExtraBrowserArgs('--force-gpu-rasterization')

  def ValidateAndMeasurePage(self, page, tab, results):
    if not tab.screenshot_supported:
      raise page_test.Failure('Browser does not support screenshot capture')

    def CheckColorMatch(canvasRGB, screenshotRGB):
      for i in range(0, 3):
        if abs(canvasRGB[i] - screenshotRGB[i]) > 1:
          raise page_test.Failure('Color mismatch in component #%d: %d vs %d' %
              (i, canvasRGB[i], screenshotRGB[i]))

    def CheckScreenshot():
      canvasRGB = [];
      for i in range(0, 3):
        canvasRGB.append(random.randint(0, 255))
      tab.EvaluateJavaScript("window.draw(%d, %d, %d);" % tuple(canvasRGB))
      screenshot = tab.Screenshot(5)
      CheckColorMatch(canvasRGB, image_util.Pixels(screenshot))

    repetitions = 50
    for n in range(0, repetitions):
      CheckScreenshot()

class ScreenshotSyncPage(page.Page):
  def __init__(self, story_set, base_dir):
    super(ScreenshotSyncPage, self).__init__(
      url='file://screenshot_sync.html',
      page_set=story_set,
      base_dir=base_dir,
      name='ScreenshotSync')

  def RunNavigateSteps(self, action_runner):
    super(ScreenshotSyncPage, self).RunNavigateSteps(action_runner)

@benchmark.Disabled('linux', 'mac', 'win')
class ScreenshotSyncProcess(benchmark.Benchmark):
  """Tests that screenhots are properly synchronized with the frame one which
  they were requested"""
  test = _ScreenshotSyncValidator

  @classmethod
  def Name(cls):
    return 'screenshot_sync'

  def CreateExpectations(self):
    return expectations.ScreenshotSyncExpectations()

  def CreateStorySet(self, options):
    ps = story_set_module.StorySet(base_dir=data_path, serving_dirs=[''])
    ps.AddStory(ScreenshotSyncPage(ps, ps.base_dir))
    return ps


text:
package org.onvif.ver10.media.wsdl;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;
import org.onvif.ver10.schema.StreamSetup;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="StreamSetup" type="{http://www.onvif.org/ver10/schema}StreamSetup"/>
 *         <element name="ProfileToken" type="{http://www.onvif.org/ver10/schema}ReferenceToken"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "streamSetup",
    "profileToken"
})
@XmlRootElement(name = "GetStreamUri")
public class GetStreamUri {

    @XmlElement(name = "StreamSetup", required = true)
    protected StreamSetup streamSetup;
    @XmlElement(name = "ProfileToken", required = true)
    protected String profileToken;

    /**
     * Gets the value of the streamSetup property.
     *
     * @return
     *     possible object is
     *     {@link StreamSetup }
     *
     */
    public StreamSetup getStreamSetup() {
        return streamSetup;
    }

    /**
     * Sets the value of the streamSetup property.
     *
     * @param value
     *     allowed object is
     *     {@link StreamSetup }
     *
     */
    public void setStreamSetup(StreamSetup value) {
        this.streamSetup = value;
    }

    /**
     * Gets the value of the profileToken property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getProfileToken() {
        return profileToken;
    }

    /**
     * Sets the value of the profileToken property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setProfileToken(String value) {
        this.profileToken = value;
    }

    /**
     * Generates a String representation of the contents of this type.
     * This is an extension method, produced by the 'ts' xjc plugin
     *
     */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
    }

}


text:
/**
 * You are a professional robber planning to rob houses along a street.
 * Each house has a certain amount of money stashed, the only constraint
 * stopping you from robbing each of them is that adjacent houses have
 * security system connected and it will automatically contact the
 * police if two adjacent houses were broken into on the same night.
 *
 * Given a list of non-negative integers representing the amount of
 * money of each house, determine the maximum amount of money you can
 * rob tonight without alerting the police.
 *
 * Example 1:
 *
 * Input: [1,2,3,1]
 * Output: 4
 * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
 * Total amount you can rob = 1 + 3 = 4.
 *
 * Example 2:
 *
 * Input: [2,7,9,3,1]
 * Output: 12
 * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
 * Total amount you can rob = 2 + 9 + 1 = 12.
 */
class Solution {
    public int rob(int[] nums) {
        HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();
        return findLocalMax(nums, 0, cache);
    }

    private int findLocalMax(int[] nums, int start, Map<Integer, Integer> cache) {
        if (cache.containsKey(start)) {
            return cache.get(start);
        }
        int ret = 0;
        if (start >= nums.length) {
            return 0;
        } else if (start == nums.length - 1) {
            ret = nums[start];
        } else if (start == nums.length - 2) {
            if (nums[start] > nums[start + 1]) {
                ret = nums[start];
            } else {
                ret = nums[start + 1];
            }
        } else {
            int curr = nums[start] + findLocalMax(nums, start + 2, cache);
            int alter = nums[start + 1] + findLocalMax(nums, start + 3, cache);
            if (curr > alter) {
                ret = curr;
            } else {
                ret = alter;
            }
        }
        cache.put(start, ret);
        return ret;
    }
}


text:
package binary_tree_longest_consecutive_sequence;

/**
 * Solution to LeetCode problem
 *
 * "Binary Tree Longest Consecutive Sequence"
 *
 *
Problem Description

 *

 * Given a binary tree, find the length of the longest consecutive sequence path.
 *

 * A path is a sequence of nodes from a starting node to any of its descendants in the
 * tree. A consecutive path is a path in which the node values are consecutive.
 */
public class Solution2 {

  public int longestConsecutive(TreeNode root) {
    return longestConsecutive(root, null /* parent */, 0 /* currSeqLen */);
  }

  private int longestConsecutive(TreeNode node, TreeNode parent, int currSeqLen) {
    if (node == null) {
      return currSeqLen;
    }

    currSeqLen = (parent != null && node.val == parent.val + 1) ? currSeqLen + 1 : 1;
    return Math.max(
        currSeqLen,
        Math.max(
            longestConsecutive(node.left, node, currSeqLen),
            longestConsecutive(node.right, node, currSeqLen)));
  }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<style is="custom-style">
  :root {
    --opacity-animation: {
      opacity: 0;
      transition: opacity 0.5s;
    };
    --img-circle: {
      border-radius: 50%;
      background-size: cover;
      background-position: 50% 50%;
    };
    --ellipsis: {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
</style>


text:
using content::BrowserThread;
using content::WebContents;

namespace {

void ShowOfflinePage(
    int render_process_id,
    int render_view_id,
    const GURL& url,
    const chromeos::OfflineLoadPage::CompletionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Check again on UI thread and proceed if it's connected.
  if (!net::NetworkChangeNotifier::IsOffline()) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE, base::Bind(callback, true));
  } else {
    RenderViewHost* render_view_host =
        RenderViewHost::FromID(render_process_id, render_view_id);
    WebContents* web_contents = render_view_host ?
        render_view_host->delegate()->GetAsWebContents() : NULL;
    // There is a chance that the tab closed after we decided to show
    // the offline page on the IO thread and before we actually show the
    // offline page here on the UI thread.
    if (web_contents)
      (new chromeos::OfflineLoadPage(web_contents, url, callback))->Show();
  }
}

}  // namespace

OfflineResourceHandler::OfflineResourceHandler(
    ResourceHandler* handler,
    int host_id,
    int route_id,
    ResourceDispatcherHost* rdh,
    net::URLRequest* request,
    ChromeAppCacheService* appcache_service)
    : next_handler_(handler),
      process_host_id_(host_id),
      render_view_id_(route_id),
      rdh_(rdh),
      request_(request),
      appcache_service_(appcache_service),
      deferred_request_id_(-1) {
  DCHECK(appcache_service_);
}

OfflineResourceHandler::~OfflineResourceHandler() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(appcache_completion_callback_.IsCancelled());
}

bool OfflineResourceHandler::OnUploadProgress(int request_id,
                                              uint64 position,
                                              uint64 size) {
  return next_handler_->OnUploadProgress(request_id, position, size);
}

bool OfflineResourceHandler::OnRequestRedirected(
    int request_id,
    const GURL& new_url,
    content::ResourceResponse* response,
    bool* defer) {
  return next_handler_->OnRequestRedirected(
      request_id, new_url, response, defer);
}

bool OfflineResourceHandler::OnResponseStarted(
    int request_id,
    content::ResourceResponse* response) {
  return next_handler_->OnResponseStarted(request_id, response);
}

bool OfflineResourceHandler::OnResponseCompleted(
    int request_id,
    const net::URLRequestStatus& status,
    const std::string& security_info) {
  return next_handler_->OnResponseCompleted(request_id, status, security_info);
}

void OfflineResourceHandler::OnRequestClosed() {
  if (!appcache_completion_callback_.IsCancelled())
    appcache_completion_callback_.Cancel();

  next_handler_->OnRequestClosed();
}

void OfflineResourceHandler::OnCanHandleOfflineComplete(int rv) {
  // Cancel() to break the circular reference cycle.
  appcache_completion_callback_.Cancel();

  if (deferred_request_id_ == -1) {
    DLOG(FATAL) << "OnCanHandleOfflineComplete called after completion: "
                << " this=" << this;
    return;
  }

  if (rv == net::OK) {
    Resume();
  } else {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        base::Bind(&ShowOfflinePage,
                   process_host_id_,
                   render_view_id_,
                   request_->url(),
                   base::Bind(&OfflineResourceHandler::OnBlockingPageComplete,
                              this)));
  }
}

bool OfflineResourceHandler::OnWillStart(int request_id,
                                         const GURL& url,
                                         bool* defer) {
  if (!ShouldShowOfflinePage(url))
    return next_handler_->OnWillStart(request_id, url, defer);

  deferred_request_id_ = request_id;
  deferred_url_ = url;
  DVLOG(1) << "OnWillStart: this=" << this << ", request id=" << request_id
           << ", url=" << url;

  DCHECK(appcache_completion_callback_.IsCancelled());

  // |appcache_completion_callback_| holds a reference to |this|, so there is a
  // circular reference; however, either
  // OfflineResourceHandler::OnCanHandleOfflineComplete cancels the callback
  // (thus dropping the reference), or CanHandleMainResourceOffline calls the
  // callback which Resets it.
  appcache_completion_callback_.Reset(
      base::Bind(&OfflineResourceHandler::OnCanHandleOfflineComplete, this));
  appcache_service_->CanHandleMainResourceOffline(
      url, request_->first_party_for_cookies(),
      appcache_completion_callback_.callback());

  *defer = true;
  return true;
}

// We'll let the original event handler provide a buffer, and reuse it for
// subsequent reads until we're done buffering.
bool OfflineResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf,
                                         int* buf_size, int min_size) {
  return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}

bool OfflineResourceHandler::OnReadCompleted(int request_id, int* bytes_read) {
  return next_handler_->OnReadCompleted(request_id, bytes_read);
}

void OfflineResourceHandler::OnBlockingPageComplete(bool proceed) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (deferred_request_id_ == -1) {
    LOG(WARNING) << "OnBlockingPageComplete called after completion: "
                 << " this=" << this;
    NOTREACHED();
    return;
  }
  if (proceed) {
    Resume();
  } else {
    int request_id = deferred_request_id_;
    ClearRequestInfo();
    rdh_->CancelRequest(process_host_id_, request_id, false);
  }
}

void OfflineResourceHandler::ClearRequestInfo() {
  deferred_url_ = GURL();
  deferred_request_id_ = -1;
}

bool OfflineResourceHandler::IsRemote(const GURL& url) const {
  return url.SchemeIs(chrome::kFtpScheme) ||
         url.SchemeIs(chrome::kHttpScheme) ||
         url.SchemeIs(chrome::kHttpsScheme);
}

bool OfflineResourceHandler::ShouldShowOfflinePage(const GURL& url) const {
  // Only check main frame. If the network is disconnected while
  // loading other resources, we'll simply show broken link/images.
  return IsRemote(url) &&
      net::NetworkChangeNotifier::IsOffline() &&
      ResourceDispatcherHost::InfoForRequest(request_)->resource_type()
        == ResourceType::MAIN_FRAME;
}

void OfflineResourceHandler::Resume() {
  const GURL url = deferred_url_;
  int request_id = deferred_request_id_;
  ClearRequestInfo();

  bool defer = false;
  DVLOG(1) << "Resume load: this=" << this << ", request id=" << request_id;
  next_handler_->OnWillStart(request_id, url, &defer);
  if (!defer)
    rdh_->StartDeferredRequest(process_host_id_, request_id);
}


text:
class Place < ActiveRecord::Base

  include ActsAsElasticModel

  # some places have geometries that are valid according to PostGIS,
  # but are not being indexed by ES, causing the entire document to
  # not get idexed. This is a fallback method that will disable
  # geometry indexing and try again if the first index failed
  after_commit :double_check_index
  attr_accessor :index_without_geometry

  scope :load_for_index, -> { includes([ :place_geometry, :user ]) }
  settings index: { number_of_shards: 1, analysis: ElasticModel::ANALYSIS } do
    mappings(dynamic: true) do
      indexes :id, type: "integer"
      indexes :place_type, type: "integer"
      indexes :geometry_geojson, type: "geo_shape"
      indexes :location, type: "geo_point", lat_lon: true
      indexes :point_geojson, type: "geo_shape"
      indexes :bbox_area, type: "double"
      indexes :display_name, analyzer: "ascii_snowball_analyzer"
      indexes :display_name_autocomplete, analyzer: "keyword_autocomplete_analyzer",
        search_analyzer: "keyword_analyzer"
    end
  end

  def as_indexed_json(options={})
    preload_for_elastic_index
    {
      id: id,
      name: name,
      display_name: display_name,
      display_name_autocomplete: display_name,
      place_type: place_type,
      admin_level: admin_level,
      bbox_area: bbox_area,
      ancestor_place_ids: ancestor_place_ids,
      user: user ? user.as_indexed_json : nil,
      geometry_geojson: (place_geometry && !index_without_geometry) ?
        ElasticModel.geom_geojson(place_geometry.simplified_geom) : nil,
      location: ElasticModel.point_latlon(latitude, longitude),
      point_geojson: ElasticModel.point_geojson(latitude, longitude)
    }
  end

  def geom_in_elastic_index
    # need to make sure Elasticsearch has refreshed with all
    # changes before checking if this Place record exists
    Place.__elasticsearch__.refresh_index!
    Place.elastic_search(where: { id: id },
      filters: [ { exists: { field: "geometry_geojson" } } ]).
      total_entries > 0
  end

  def double_check_index
    unless geom_in_elastic_index
      self.index_without_geometry = true
      self.elastic_index!
    end
  end

end


text:
<?php

namespace Sahadina\CategoryBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SahadinaCategoryBundle extends Bundle
{
}


text:
import { Component, ViewChild } from '@angular/core';
import { App, Content, LoadingController, MenuController, NavController } from 'ionic-angular';
import { Login } from '../login/login';
import { StampDetail } from '../stamp-detail/stamp-detail';
import { Register } from '../register/register';
import { Leave } from '../leave/leave';
import { Profile } from '../profile/profile';
import { NativeStorage } from '@ionic-native/native-storage';
import { Device } from '@ionic-native/device';
import { StampService } from '../../service/StampService';
import { Geolocation } from '@ionic-native/geolocation';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {
  @ViewChild(Content) content: Content;
  rootPage: any;
  userdetail: any = {};
  dataToday: any = {
    'dateTimeIn': null,
    'dateTimeOut': null,
  };
  devic: string = this.device.platform;
  public dateTimeNow: any = Date();
  public loader: any = this.loadingCtrl.create({
    content: "Please wait..."
  });
  public stampdata: any = {
    'locationIn':
    {
      'lat': '',
      'lng': ''
    },
    'locationOut':
    {
      'lat': '',
      'lng': ''
    },
    'email': '',
    'user': '',
    'dateTimeIn': null,
    'dateTimeOut': null,
    'type': this.devic
  };

  constructor(public app: App, public menu: MenuController, public navCtrl: NavController,
    private nativeStorage: NativeStorage, public stmp: StampService,
    private loadingCtrl: LoadingController, private geolocation: Geolocation,
    private device: Device) {
    menu.enable(true);
    this.nativeStorage.getItem('TimeStampUser').then(
      data => {
        this.userdetail = data;
        this.stampdata.email = this.userdetail.employeeprofile.email;
        this.callCheckTimeAtt();
      },
      error => this.rootPage = Register
    );

    //for chrome test//
    // this.userdetail = {
    //   _id: '5b18e324fc455f2e00887b71'
    // };
    // this.stampdata.email = 'popveera@hotmail.com';
    // this.callCheckTimeAtt();

    //

  }
  callCheckTimeAtt() {
    this.stmp.chkstamp(this.userdetail._id).then((res) => {
      if (res.status == "Not checkin") {

      } else if (res.status == "checkin only") {
        this.dataToday.dateTimeIn = res.data.dateTimeIn;
      } else if (res.status == "checkined today") {
        this.dataToday.dateTimeIn = res.data.dateTimeIn;
        this.dataToday.dateTimeOut = res.data.dateTimeOut;
      }
    }).catch((err) => {
      this.dataToday.dateTimeIn = null;
      this.dataToday.dateTimeOut = null;
    });
  }
  ionViewDidEnter() {
    setInterval(() => {
      this.dateTimeNow = Date();
    }, 1000);
    this.callCheckTimeAtt();
  };

  showMenu() {
    this.menu.open();
  };

  stampFn(lat, lng) {
    this.loader.present();
    this.stmp.chkstamp(this.userdetail._id).then((res) => {
      if (res.status === '' || res.status === 'Not checkin') {
        this.stampdata.user = this.userdetail._id;
        this.stampdata.dateTimeIn = new Date();
        this.stampdata.locationIn.lat = lat;
        this.stampdata.locationIn.lng = lng;
        this.stmp.stampIn(this.stampdata).then(data => {
          this.loader.dismiss();
          this.nativeStorage.setItem('StampToday', data);
          this.navCtrl.push(StampDetail);
        }).catch(err => {
          this.loader.dismiss();
          alert(JSON.stringify(err));
        });
      } else if (res.status === 'checkin only') {
        this.stampdata = res.data;
        this.stampdata.dateTimeOut = new Date();
        this.stampdata.locationOut.lat = lat;
        this.stampdata.locationOut.lng = lng;
        this.stmp.stampOut(this.stampdata).then((data) => {
          this.loader.dismiss();
          this.nativeStorage.setItem('StampToday', data).then(
            () => this.navCtrl.push(StampDetail),
            error => alert('Error! SetItem when stampOut'));
        }).catch((err) => {
          this.loader.dismiss();
          let testErr = JSON.parse(err._body);
          alert('Check Out call service Error in stmp : ' + testErr.message);
        });
      } else {
        this.loader.dismiss();
        this.nativeStorage.setItem('StampToday', res.data).then(
          () => this.navCtrl.push(StampDetail),
          error => alert('Error StampToday'));
      }
    }).catch((err) => {
      this.loader.dismiss();
      let testErr = JSON.parse(err._body);
      alert("ERROR check Stamp : " + testErr.message);
    });
  };

  openPage_stampDetail() {
    alert('stamp!');
    this.stampFn('13.9005307', '100.6385391');
    // this.geolocation.getCurrentPosition().then((resp) => {
    //   let lat = resp.coords.latitude;
    //   let lng = resp.coords.longitude;
    //   this.stampFn(lat, lng);
    // }).catch((error) => {
    //   alert(error);
    // });
  }

  openPage_login() {
    this.navCtrl.push(Login);
  }

  openPage_regis() {
    this.navCtrl.push(Register);
  }

  openPage_leave() {
    this.app.getRootNav().push(Leave);
  }

  openPage_profile() {
    this.app.getRootNav().push(Profile);
  }

  logout() {
    this.nativeStorage.clear();
    this.app.getRootNav().popToRoot();
    setTimeout(() => {
      this.app.getRootNav().push(Login);
    }, 100);
  }

  doClick() {
    this.menu.open();
  }
}


text:
package org.gradle.api.internal.artifacts.repositories.resolver;

public class MavenPattern {
    public static final String M2_PER_MODULE_VERSION_PATTERN = "[artifact]-[revision](-[classifier])(.[ext])";
    public static final String M2_PER_MODULE_PATTERN = "[revision]/" + M2_PER_MODULE_VERSION_PATTERN;
    public static final String M2_PATTERN = "[organisation]/[module]/" + M2_PER_MODULE_PATTERN;
}


text:
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0

package org.terasology.engine.rendering.assets.mesh.resource;

public class VertexByteAttribute extends BaseVertexAttribute {
    public final VertexByteAttribute.AttributeConfiguration configuration;

    /**
     * @param mapping maps a primitive to a given supported type.
     * @param count the number elements that is described by the target
     */
    protected VertexByteAttribute(VertexByteAttribute.AttributeConfiguration attributeConfiguration,
                                  TypeMapping mapping, int count) {
        super(mapping, count);
        this.configuration = attributeConfiguration;
    }

    public interface AttributeConfiguration {
        void write(byte value, int vertIdx, int offset, VertexResource resource);

        byte read(int vertIdx, int offset, VertexResource resource);
    }
}


text:
namespace SIM.Tool.Windows.MainWindowComponents
{
  using System.IO;
  using System.Linq;
  using System.Windows;
  using SIM.Instances;
  using SIM.Pipelines;
  using SIM.Pipelines.InstallModules;
  using SIM.Products;
  using SIM.Tool.Base;
  using SIM.Tool.Base.Plugins;
  using Sitecore.Diagnostics.Base;
  using JetBrains.Annotations;
  using SIM.Core;

  [UsedImplicitly]
  public class OpenVisualStudioButton : IMainWindowButton
  {
    #region Public methods

    public bool IsEnabled(Window mainWindow, Instance instance)
    {
      return instance != null;
    }

    public void OnClick(Window mainWindow, Instance instance)
    {
      if (instance == null)
      {
        return;
      }

      var paths = instance.GetVisualStudioSolutionFiles().ToArray();

      if (paths.Length > 0)
      {
        CoreApp.OpenFile(paths.First());
        return;
      }

      const string NoThanks = "No, thanks";
      const string YesAspNetMvc = "Yes, create new";

      var options = new[] { NoThanks, YesAspNetMvc };
      var result = WindowHelper.AskForSelection("Choose Visual Studio Project Type", null, "There isn't any Visual Studio project in the instance's folder. \n\nWould you like us to create a new one?", options, mainWindow);
      if (result == null || result == NoThanks)
      {
        return;
      }

      var packageName = "Visual Studio 2015 Website Project.zip";
      var product = GetProduct(packageName);
      if (product == null)
      {
        WindowHelper.HandleError("The " + packageName + " package cannot be found in either the .\\Packages folder", false);
        return;
      }

      PipelineManager.StartPipeline("installmodules", new InstallModulesArgs(instance, new[] { product }), isAsync: false);
      var path = instance.GetVisualStudioSolutionFiles().FirstOrDefault();
      Assert.IsTrue(!string.IsNullOrEmpty(path) && FileSystem.FileSystem.Local.File.Exists(path), "The Visual Studio files are missing");

      CoreApp.OpenFile(path);
    }

    #endregion

    #region Private methods

    private static Product GetProduct(string packageName)
    {
      foreach (var folderPath in EnvironmentHelper.FilePackageFolders)
      {
        var packagePath = Path.Combine(folderPath, packageName);
        if (!FileSystem.FileSystem.Local.File.Exists(packagePath))
        {
          continue;
        }

        var product = Product.GetFilePackageProduct(packagePath);
        if (product != null)
        {
          return product;
        }
      }

      return null;
    }

    #endregion
  }
}


text:
package org.apache.flink.test.operators;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.test.operators.util.CollectionDataSets;
import org.apache.flink.test.operators.util.CollectionDataSets.CustomType;
import org.apache.flink.test.util.MultipleProgramsTestBase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Collection;
import java.util.List;

/**
 * Integration tests for {@link FilterFunction} and {@link RichFilterFunction}.
 */
@RunWith(Parameterized.class)
public class FilterITCase extends MultipleProgramsTestBase {
	public FilterITCase(TestExecutionMode mode){
		super(mode);
	}

	@Test
	public void testAllRejectingFilter() throws Exception {
		/*
		 * Test all-rejecting filter.
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
		DataSet<Tuple3<Integer, Long, String>> filterDs = ds.
				filter(new Filter1());

		List<Tuple3<Integer, Long, String>> result = filterDs.collect();

		String expected = "\n";

		compareResultAsTuples(result, expected);
	}

	private static class Filter1 implements FilterFunction<Tuple3<Integer, Long, String>> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean filter(Tuple3<Integer, Long, String> value) throws Exception {
			return false;
		}
	}

	@Test
	public void testAllPassingFilter() throws Exception {
		/*
		 * Test all-passing filter.
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
		DataSet<Tuple3<Integer, Long, String>> filterDs = ds.
				filter(new Filter2());
		List<Tuple3<Integer, Long, String>> result = filterDs.collect();

		String expected = "1,1,Hi\n" +
				"2,2,Hello\n" +
				"3,2,Hello world\n" +
				"4,3,Hello world, how are you?\n" +
				"5,3,I am fine.\n" +
				"6,3,Luke Skywalker\n" +
				"7,4,Comment#1\n" +
				"8,4,Comment#2\n" +
				"9,4,Comment#3\n" +
				"10,4,Comment#4\n" +
				"11,5,Comment#5\n" +
				"12,5,Comment#6\n" +
				"13,5,Comment#7\n" +
				"14,5,Comment#8\n" +
				"15,5,Comment#9\n" +
				"16,6,Comment#10\n" +
				"17,6,Comment#11\n" +
				"18,6,Comment#12\n" +
				"19,6,Comment#13\n" +
				"20,6,Comment#14\n" +
				"21,6,Comment#15\n";

		compareResultAsTuples(result, expected);
	}

	private static class Filter2 implements FilterFunction<Tuple3<Integer, Long, String>> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean filter(Tuple3<Integer, Long, String> value) throws Exception {
			return true;
		}
	}

	@Test
	public void testFilterOnStringTupleField() throws Exception {
		/*
		 * Test filter on String tuple field.
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
		DataSet<Tuple3<Integer, Long, String>> filterDs = ds.
				filter(new Filter3());
		List<Tuple3<Integer, Long, String>> result = filterDs.collect();

		String expected = "3,2,Hello world\n"
				+
				"4,3,Hello world, how are you?\n";

		compareResultAsTuples(result, expected);

	}

	private static class Filter3 implements FilterFunction<Tuple3<Integer, Long, String>> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean filter(Tuple3<Integer, Long, String> value) throws Exception {
			return value.f2.contains("world");
		}
	}

	@Test
	public void testFilterOnIntegerTupleField() throws Exception {
		/*
		 * Test filter on Integer tuple field.
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
		DataSet<Tuple3<Integer, Long, String>> filterDs = ds.
				filter(new Filter4());
		List<Tuple3<Integer, Long, String>> result = filterDs.collect();

		String expected = "2,2,Hello\n" +
				"4,3,Hello world, how are you?\n" +
				"6,3,Luke Skywalker\n" +
				"8,4,Comment#2\n" +
				"10,4,Comment#4\n" +
				"12,5,Comment#6\n" +
				"14,5,Comment#8\n" +
				"16,6,Comment#10\n" +
				"18,6,Comment#12\n" +
				"20,6,Comment#14\n";

		compareResultAsTuples(result, expected);
	}

	private static class Filter4 implements FilterFunction<Tuple3<Integer, Long, String>> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean filter(Tuple3<Integer, Long, String> value) throws Exception {
			return (value.f0 % 2) == 0;
		}
	}

	@Test
	public void testFilterBasicType() throws Exception {
		/*
		 * Test filter on basic type
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<String> ds = CollectionDataSets.getStringDataSet(env);
		DataSet<String> filterDs = ds.
				filter(new Filter5());
		List<String> result = filterDs.collect();

		String expected = "Hi\n" +
				"Hello\n" +
				"Hello world\n" +
				"Hello world, how are you?\n";

		compareResultAsText(result, expected);
	}

	private static class Filter5 implements FilterFunction<String> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean filter(String value) throws Exception {
			return value.startsWith("H");
		}
	}

	@Test
	public void testFilterOnCustomType() throws Exception {
		/*
		 * Test filter on custom type
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<CustomType> ds = CollectionDataSets.getCustomTypeDataSet(env);
		DataSet<CustomType> filterDs = ds.
				filter(new Filter6());
		List<CustomType> result = filterDs.collect();

		String expected = "3,3,Hello world, how are you?\n"
				+
				"3,4,I am fine.\n" +
				"3,5,Luke Skywalker\n";

		compareResultAsText(result, expected);
	}

	private static class Filter6 implements FilterFunction<CustomType> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean filter(CustomType value) throws Exception {
			return value.myString.contains("a");
		}
	}

	@Test
	public void testRichFilterOnStringTupleField() throws Exception {
		/*
		 * Test filter on String tuple field.
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Integer> ints = CollectionDataSets.getIntegerDataSet(env);

		DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
		DataSet<Tuple3<Integer, Long, String>> filterDs = ds.
				filter(new RichFilter1()).withBroadcastSet(ints, "ints");
		List<Tuple3<Integer, Long, String>> result = filterDs.collect();

		String expected = "1,1,Hi\n" +
				"2,2,Hello\n" +
				"3,2,Hello world\n" +
				"4,3,Hello world, how are you?\n";

		compareResultAsTuples(result, expected);
	}

	private static class RichFilter1 extends RichFilterFunction<Tuple3<Integer, Long, String>> {
		private static final long serialVersionUID = 1L;

		int literal = -1;

		@Override
		public void open(Configuration config) {
			Collection<Integer> ints = this.getRuntimeContext().getBroadcastVariable("ints");
			for (int i: ints) {
				literal = literal < i ? i : literal;
			}
		}

		@Override
		public boolean filter(Tuple3<Integer, Long, String> value) throws Exception {
			return value.f0 < literal;
		}
	}

	@Test
	public void testFilterWithBroadcastVariables() throws Exception {
		/*
		 * Test filter with broadcast variables
		 */

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Integer> intDs = CollectionDataSets.getIntegerDataSet(env);

		DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
		DataSet<Tuple3<Integer, Long, String>> filterDs = ds.
				filter(new RichFilter2()).withBroadcastSet(intDs, "ints");
		List<Tuple3<Integer, Long, String>> result = filterDs.collect();

		String expected = "11,5,Comment#5\n" +
				"12,5,Comment#6\n" +
				"13,5,Comment#7\n" +
				"14,5,Comment#8\n" +
				"15,5,Comment#9\n";

		compareResultAsTuples(result, expected);
	}

	private static class RichFilter2 extends RichFilterFunction<Tuple3<Integer, Long, String>> {
		private static final long serialVersionUID = 1L;
		private  int broadcastSum = 0;

		@Override
		public void open(Configuration config) {
			Collection<Integer> ints = this.getRuntimeContext().getBroadcastVariable("ints");
			for (Integer i : ints) {
				broadcastSum += i;
			}
		}

		@Override
		public boolean filter(Tuple3<Integer, Long, String> value) throws Exception {
			return (value.f1 == (broadcastSum / 11));
		}
	}
}


text:
namespace notifier {

namespace {

class GaiaCookieMechanism : public buzz::SaslCookieMechanism {
 public:
  GaiaCookieMechanism(const std::string & mechanism,
                      const std::string & username,
                      const std::string & cookie,
                      const std::string & token_service)
      : buzz::SaslCookieMechanism(
          mechanism, username, cookie, token_service) {}

  virtual ~GaiaCookieMechanism() {}

  virtual buzz::XmlElement* StartSaslAuth() {
    buzz::XmlElement* auth = buzz::SaslCookieMechanism::StartSaslAuth();
    // These attributes are necessary for working with non-gmail gaia
    // accounts.
    const std::string NS_GOOGLE_AUTH_PROTOCOL(
        "http://www.google.com/talk/protocol/auth");
    const buzz::QName QN_GOOGLE_ALLOW_GENERATED_JID_XMPP_LOGIN(
        NS_GOOGLE_AUTH_PROTOCOL, "allow-generated-jid");
    const buzz::QName QN_GOOGLE_AUTH_CLIENT_USES_FULL_BIND_RESULT(
        NS_GOOGLE_AUTH_PROTOCOL, "client-uses-full-bind-result");
    auth->SetAttr(QN_GOOGLE_ALLOW_GENERATED_JID_XMPP_LOGIN, "true");
    auth->SetAttr(QN_GOOGLE_AUTH_CLIENT_USES_FULL_BIND_RESULT, "true");
    return auth;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(GaiaCookieMechanism);
};

}  // namespace

// By default use a Google cookie auth mechanism.
const char GaiaTokenPreXmppAuth::kDefaultAuthMechanism[] = "X-GOOGLE-TOKEN";

GaiaTokenPreXmppAuth::GaiaTokenPreXmppAuth(
    const std::string& username,
    const std::string& token,
    const std::string& token_service,
    const std::string& auth_mechanism)
    : username_(username),
      token_(token),
      token_service_(token_service),
      auth_mechanism_(auth_mechanism) {
  DCHECK(!auth_mechanism_.empty());
}

GaiaTokenPreXmppAuth::~GaiaTokenPreXmppAuth() { }

void GaiaTokenPreXmppAuth::StartPreXmppAuth(
    const buzz::Jid& jid,
    const talk_base::SocketAddress& server,
    const talk_base::CryptString& pass,
    const std::string& auth_cookie) {
  SignalAuthDone();
}

bool GaiaTokenPreXmppAuth::IsAuthDone() const {
  return true;
}

bool GaiaTokenPreXmppAuth::IsAuthorized() const {
  return true;
}

bool GaiaTokenPreXmppAuth::HadError() const {
  return false;
}

int GaiaTokenPreXmppAuth::GetError() const {
  return 0;
}

buzz::CaptchaChallenge GaiaTokenPreXmppAuth::GetCaptchaChallenge() const {
  return buzz::CaptchaChallenge();
}

std::string GaiaTokenPreXmppAuth::GetAuthCookie() const {
  return std::string();
}

std::string GaiaTokenPreXmppAuth::ChooseBestSaslMechanism(
    const std::vector<std::string> & mechanisms, bool encrypted) {
  return (std::find(mechanisms.begin(),
                    mechanisms.end(), auth_mechanism_) !=
          mechanisms.end()) ? auth_mechanism_ : "";
}

buzz::SaslMechanism* GaiaTokenPreXmppAuth::CreateSaslMechanism(
    const std::string& mechanism) {
  if (mechanism == auth_mechanism_)
    return new GaiaCookieMechanism(
        mechanism, username_, token_, token_service_);
  return NULL;
}

}  // namespace notifier


text:
angular.module('directive-file-model',[]).directive('fileModel', ['$parse', "$rootScope", function($parse, $rootScope) {
    return {
        restrict: 'A',
        scope: {
            model: "=fileModel",
            overwrite: "=fileModelOverwrite",
            field: "@field"
                //change:'fileModelChange'
        },
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            element.bind('change', function() {
                scope.$apply(function() {
                    try {
                        scope.model = scope.model || {};
                        if (typeof scope.overwrite !== 'undefined') {
                            scope.overwrite = (scope.overwrite == undefined) ? false : scope.overwrite;
                            scope.overwrite = (typeof scope.overwrite !== 'boolean') ? false : scope.overwrite;
                        }
                        if (scope.overwrite) {
                            scope.model = element[0].files[0];
                        }
                        else {
                            scope.model[scope.field || 'file'] = element[0].files[0];
                        }
                        if (attrs.fileModelChange) {
                            scope.$parent.$eval(attrs.fileModelChange);
                        }

                    }
                    catch (e) {
                        modelSetter(element[0].files[0]);
                    }
                });
            });
        }
    };
}]);


text:
import os

from lib.webinterface import Http404Error, Response, path
from settings import PATHS

# maps file endings to MIME-types
mime_types = {
    '': 'application/octet-stream',
    '.txt': 'text/plain',
    '.js': 'application/javascript',
    '.css': 'text/css',
}

@path('(/static/[\w\./]+)', mode='*')
def static(req, path):
    """ Serves static files from the static directory. """
    views_path = os.path.expanduser(PATHS['VIEWS'])
    full_path = views_path + path[1:]
    # catch path traversal and check if file exists
    if len(os.path.normpath(path)) == 1 or not os.path.isfile(full_path):
        raise Http404Error()
    with open(full_path, 'r') as f:
        r = Response(content=f.read())
    _, ext = os.path.splitext(full_path)
    r.set_header('Content-Type', '%s; charset=UTF-8' %
                 mime_types.get(ext, mime_types['']))
    return r


text:
<?php
class Constants
{
    const PROJECT_PATH = '/labo/fuel_rest/admin_dds/';
    const TEMPLATE_VIEW = 'template.twig';
    const AUTH_TEMPLATE_VIEW = 'auth_template.twig';
}


text:
import io, sys, os

# reverso_original = io.open('inv.dc.uba.ar.zone.rev', encoding='latin-1')

# with io.open('zonas/inv.dc.uba.ar.zone.rev', encoding='latin-1') as origen:
# with open('zonas/inv.dc.uba.ar.zone.rev', 'r') as origen:
buscar = 'NS'
lineaFinalEnc = 0
origen = io.open('zonas/inv.dc.uba.ar.zone.rev', encoding='latin-1')
enum = enumerate(origen, 1)
for num, linea in enum:
    if buscar in linea:
        lineaFinalEnc = num
origen.close()
origen = io.open('zonas/inv.dc.uba.ar.zone.rev', encoding='latin-1')
listaOrigen = origen.read().split(sep='\n')
for i in range(0, lineaFinalEnc):
    print(listaOrigen[i])
origen.close()

'''
    for i in range(1,int(lineaFinalEnc)+1);
        bbb=origen.next().strip()
        #print(i)

'''


text:
Ti=Return or Destruction

sec=Upon termination or expiration of {this_Agreement}, or upon written request {ByParty}, {the_Receiving_Party} will promptly return to {the_Disclosing_Party} or destroy all documents and other tangible materials representing {Confidential_Information} and all copies thereof.

ByParty=of either {party}

=[Z/Sec/1]


text:
package kornell.core.to;

import kornell.core.entity.Enrollment;

public interface EnrollmentTO {
    public static String TYPE = TOFactory.PREFIX + "enrollment+json";

    Enrollment getEnrollment();
    void setEnrollment(Enrollment enrollment);

    String getPersonUUID();
    void setPersonUUID(String personUUID);

    String getFullName();
    void setFullName(String fullName);

    String getUsername();
    void setUsername(String username);

    boolean getHasPowerOver();
    void setHasPowerOver(boolean hasPowerOver);

}


text:
using FluentAssertions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading.Tasks;
using ygo.api.Constants;
using ygo.api.Controllers;
using ygo.application.Dto;
using ygo.application.Paging;
using ygo.application.Queries;
using ygo.application.Queries.ArchetypeSearch;
using ygo.tests.core;

namespace ygo.api.unit.tests.ControllerTests.ArchetypesControllerTests
{
    [TestFixture]
    [Category(TestType.Unit)]
    public class GetArchetypeSearchTests
    {
        private IMediator _mediator;
        private ArchetypesController _sut;

        [SetUp]
        public void SetUp()
        {
            _mediator = Substitute.For<IMediator>();

            _sut = new ArchetypesController(_mediator);
        }

        [Test]
        public async Task Given_An_ArchetypeSearchQuery_If_Not_Successful_Should_Return_BadRequest()
        {
            // Arrange
            var query = new ArchetypeSearchQuery();

            _mediator.Send(Arg.Any<ArchetypeSearchQuery>()).Returns(new QueryResult());

            // Act
            var result = await _sut.GetArchetypeSearch(query);

            // Assert
            result.Should().BeOfType<BadRequestObjectResult>();
        }

        [Test]
        public async Task Given_An_ArchetypeSearchQuery_If_Not_Successful_Should_Return_BadRequest_With_Errors()
        {
            // Arrange
            const string expected = "Page Number must greater than 0.";

            var query = new ArchetypeSearchQuery();

            _mediator.Send(Arg.Any<ArchetypeSearchQuery>()).Returns(new QueryResult{ Errors = new List<string>{ "Page Number must greater than 0."}});

            // Act
            var result = await _sut.GetArchetypeSearch(query) as BadRequestObjectResult;

            // Assert
            result.Should().BeOfType<BadRequestObjectResult>();
            var errors = result?.Value as IEnumerable<string>;
            errors.Should().ContainSingle(expected);
        }

        [Test]
        public async Task Given_An_ArchetypeSearchQuery_If_Successful_But_No_Archetypes_Found_Should_Return_NotFound()
        {
            // Arrange
            var query = new ArchetypeSearchQuery{ SearchTerm = "toons"};

            _mediator.Send(Arg.Any<ArchetypeSearchQuery>()).Returns(new QueryResult{ IsSuccessful = true, Data = new PagedList<ArchetypeDto>(new List<ArchetypeDto>(), 0, 1, 10)});
            _sut.ControllerContext = new ControllerContext();
            _sut.ControllerContext.HttpContext = new DefaultHttpContext();

            // Act
            var result = await _sut.GetArchetypeSearch(query);

            // Assert
            result.Should().BeOfType<NotFoundResult>();
        }

        [Test]
        public async Task Given_An_ArchetypeSearchQuery_If_Successful_Should_Return_OkResult()
        {
            // Arrange
            var query = new ArchetypeSearchQuery{ SearchTerm = "toons"};

            _mediator.Send(Arg.Any<ArchetypeSearchQuery>()).Returns(new QueryResult{ IsSuccessful = true, Data = new PagedList<ArchetypeDto>(new List<ArchetypeDto>
            {
                new ArchetypeDto
                {
                    Id = 2342,
                    Name = "toons",
                    Url = "http://localhost/toons"
                }
            }, 0, 1, 10)});
            _sut.ControllerContext = new ControllerContext {HttpContext = new DefaultHttpContext()};

            var urlHelper = Substitute.For<IUrlHelper>();
            urlHelper.Link(Arg.Any<string>(), Arg.Any<object>()).Returns("http://localhost/toons");

            _sut.Url = urlHelper;

            // Act
            var result = await _sut.GetArchetypeSearch(query);

            // Assert
            result.Should().BeOfType<OkObjectResult>();
        }

        [Test]
        public async Task Given_An_ArchetypeSearchQuery_Should_Invoke_ArchetypeSearchQuery_Once()
        {
            // Arrange
            var query = new ArchetypeSearchQuery{ SearchTerm = "toons"};

            var pagedList = new PagedList<ArchetypeDto>(new List<ArchetypeDto>
            {
                new ArchetypeDto
                {
                    Id = 2342,
                    Name = "toons",
                    Url = "http://localhost/toons"
                }
            }, 40, 2, 10);

            _mediator.Send(Arg.Any<ArchetypeSearchQuery>()).Returns(new QueryResult{ IsSuccessful = true, Data = pagedList});
            _sut.ControllerContext = new ControllerContext {HttpContext = new DefaultHttpContext()};

            var urlHelper = Substitute.For<IUrlHelper>();
            urlHelper.Link(Arg.Any<string>(), Arg.Any<object>()).Returns("http://localhost/toons");

            _sut.Url = urlHelper;

            // Act
            await _sut.GetArchetypeSearch(query);

            // Assert
            await _mediator.Received(1).Send(Arg.Any<ArchetypeSearchQuery>());
        }

        [Test]
        public async Task Given_An_ArchetypeSearchQuery_Should_Return_Pagination_Header()
        {
            // Arrange
            var query = new ArchetypeSearchQuery{ SearchTerm = "toons"};

            _mediator.Send(Arg.Any<ArchetypeSearchQuery>()).Returns(new QueryResult
            {
                IsSuccessful = true,
                Data = new PagedList<ArchetypeDto>(new List<ArchetypeDto>
                {
                    new ArchetypeDto
                    {
                        Id = 2342,
                        Name = "toons",
                        Url = "http://localhost/toons"
                    }
                }, 0, 1, 10)
            });
            _sut.ControllerContext = new ControllerContext {HttpContext = new DefaultHttpContext()};

            var urlHelper = Substitute.For<IUrlHelper>();
            urlHelper.Link(Arg.Any<string>(), Arg.Any<object>()).Returns("http://localhost/toons");

            _sut.Url = urlHelper;

            // Act
            await _sut.GetArchetypeSearch(query);

            // Assert
            _sut.Response.Headers.Should().ContainKey(HttpHeaderConstants.XPagination);
        }
    }
}


text:
//------------------------------------------------------------------------------
// File: VideoCtl.h
//
// Desc: DirectShow base classes.
//
// Copyright (c) 1992-2001 Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------------------------

#ifndef __VIDEOCTL__
#define __VIDEOCTL__

// These help with property page implementations. The first can be used to
// load any string from a resource file. The buffer to load into is passed
// as an input parameter. The same buffer is the return value if the string
// was found otherwise it returns TEXT(""). The GetDialogSize is passed the
// resource ID of a dialog box and returns the size of it in screen pixels

#define STR_MAX_LENGTH 256
LPTSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPTSTR pBuffer, int iResourceID);

#ifdef UNICODE
#define WideStringFromResource StringFromResource
LPSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPSTR pBuffer, int iResourceID);
#else
LPWSTR WINAPI WideStringFromResource(__out_ecount(STR_MAX_LENGTH) LPWSTR pBuffer, int iResourceID);
#endif

BOOL WINAPI GetDialogSize(int iResourceID,     // Dialog box resource identifier
                          DLGPROC pDlgProc,    // Pointer to dialog procedure
                          LPARAM lParam,       // Any user data wanted in pDlgProc
                          __out SIZE *pResult);// Returns the size of dialog box

// Class that aggregates an IDirectDraw interface

class CAggDirectDraw : public IDirectDraw, public CUnknown
{
protected:

    LPDIRECTDRAW m_pDirectDraw;

public:

    DECLARE_IUNKNOWN
    STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv);

    // Constructor and destructor

    CAggDirectDraw(__in_opt LPCTSTR pName,__inout_opt LPUNKNOWN pUnk) :
        CUnknown(pName,pUnk),
        m_pDirectDraw(NULL) { };

    virtual CAggDirectDraw::~CAggDirectDraw() { };

    // Set the object we should be aggregating
    void SetDirectDraw(__inout LPDIRECTDRAW pDirectDraw) {
        m_pDirectDraw = pDirectDraw;
    }

    // IDirectDraw methods

    STDMETHODIMP Compact();
    STDMETHODIMP CreateClipper(DWORD dwFlags,__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper,__inout_opt IUnknown *pUnkOuter);
    STDMETHODIMP CreatePalette(DWORD dwFlags,__in LPPALETTEENTRY lpColorTable,__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette,__inout_opt IUnknown *pUnkOuter);
    STDMETHODIMP CreateSurface(__in LPDDSURFACEDESC lpDDSurfaceDesc,__deref_out LPDIRECTDRAWSURFACE *lplpDDSurface,__inout_opt IUnknown *pUnkOuter);
    STDMETHODIMP DuplicateSurface(__in LPDIRECTDRAWSURFACE lpDDSurface,__deref_out LPDIRECTDRAWSURFACE *lplpDupDDSurface);
    STDMETHODIMP EnumDisplayModes(DWORD dwSurfaceDescCount,__in LPDDSURFACEDESC lplpDDSurfaceDescList,__in LPVOID lpContext,__in LPDDENUMMODESCALLBACK lpEnumCallback);
    STDMETHODIMP EnumSurfaces(DWORD dwFlags,__in LPDDSURFACEDESC lpDDSD,__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpEnumCallback);
    STDMETHODIMP FlipToGDISurface();
    STDMETHODIMP GetCaps(__out LPDDCAPS lpDDDriverCaps,__out LPDDCAPS lpDDHELCaps);
    STDMETHODIMP GetDisplayMode(__out LPDDSURFACEDESC lpDDSurfaceDesc);
    STDMETHODIMP GetFourCCCodes(__inout LPDWORD lpNumCodes,__out_ecount(*lpNumCodes) LPDWORD lpCodes);
    STDMETHODIMP GetGDISurface(__deref_out LPDIRECTDRAWSURFACE *lplpGDIDDSurface);
    STDMETHODIMP GetMonitorFrequency(__out LPDWORD lpdwFrequency);
    STDMETHODIMP GetScanLine(__out LPDWORD lpdwScanLine);
    STDMETHODIMP GetVerticalBlankStatus(__out LPBOOL lpblsInVB);
    STDMETHODIMP Initialize(__in GUID *lpGUID);
    STDMETHODIMP RestoreDisplayMode();
    STDMETHODIMP SetCooperativeLevel(HWND hWnd,DWORD dwFlags);
    STDMETHODIMP SetDisplayMode(DWORD dwWidth,DWORD dwHeight,DWORD dwBpp);
    STDMETHODIMP WaitForVerticalBlank(DWORD dwFlags,HANDLE hEvent);
};

// Class that aggregates an IDirectDrawSurface interface

class CAggDrawSurface : public IDirectDrawSurface, public CUnknown
{
protected:

    LPDIRECTDRAWSURFACE m_pDirectDrawSurface;

public:

    DECLARE_IUNKNOWN
    STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv);

    // Constructor and destructor

    CAggDrawSurface(__in_opt LPCTSTR pName,__inout_opt LPUNKNOWN pUnk) :
        CUnknown(pName,pUnk),
        m_pDirectDrawSurface(NULL) { };

    virtual ~CAggDrawSurface() { };

    // Set the object we should be aggregating
    void SetDirectDrawSurface(__inout LPDIRECTDRAWSURFACE pDirectDrawSurface) {
        m_pDirectDrawSurface = pDirectDrawSurface;
    }

    // IDirectDrawSurface methods

    STDMETHODIMP AddAttachedSurface(__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface);
    STDMETHODIMP AddOverlayDirtyRect(__in LPRECT lpRect);
    STDMETHODIMP Blt(__in LPRECT lpDestRect,__in LPDIRECTDRAWSURFACE lpDDSrcSurface,__in LPRECT lpSrcRect,DWORD dwFlags,__in LPDDBLTFX lpDDBltFx);
    STDMETHODIMP BltBatch(__in_ecount(dwCount) LPDDBLTBATCH lpDDBltBatch,DWORD dwCount,DWORD dwFlags);
    STDMETHODIMP BltFast(DWORD dwX,DWORD dwY,__in LPDIRECTDRAWSURFACE lpDDSrcSurface,__in LPRECT lpSrcRect,DWORD dwTrans);
    STDMETHODIMP DeleteAttachedSurface(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface);
    STDMETHODIMP EnumAttachedSurfaces(__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback);
    STDMETHODIMP EnumOverlayZOrders(DWORD dwFlags,__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpfnCallback);
    STDMETHODIMP Flip(__in LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride,DWORD dwFlags);
    STDMETHODIMP GetAttachedSurface(__in LPDDSCAPS lpDDSCaps,__deref_out LPDIRECTDRAWSURFACE *lplpDDAttachedSurface);
    STDMETHODIMP GetBltStatus(DWORD dwFlags);
    STDMETHODIMP GetCaps(__out LPDDSCAPS lpDDSCaps);
    STDMETHODIMP GetClipper(__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper);
    STDMETHODIMP GetColorKey(DWORD dwFlags,__out LPDDCOLORKEY lpDDColorKey);
    STDMETHODIMP GetDC(__out HDC *lphDC);
    STDMETHODIMP GetFlipStatus(DWORD dwFlags);
    STDMETHODIMP GetOverlayPosition(__out LPLONG lpdwX,__out LPLONG lpdwY);
    STDMETHODIMP GetPalette(__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette);
    STDMETHODIMP GetPixelFormat(__out LPDDPIXELFORMAT lpDDPixelFormat);
    STDMETHODIMP GetSurfaceDesc(__out LPDDSURFACEDESC lpDDSurfaceDesc);
    STDMETHODIMP Initialize(__in LPDIRECTDRAW lpDD,__in LPDDSURFACEDESC lpDDSurfaceDesc);
    STDMETHODIMP IsLost();
    STDMETHODIMP Lock(__in LPRECT lpDestRect,__inout LPDDSURFACEDESC lpDDSurfaceDesc,DWORD dwFlags,HANDLE hEvent);
    STDMETHODIMP ReleaseDC(HDC hDC);
    STDMETHODIMP Restore();
    STDMETHODIMP SetClipper(__in LPDIRECTDRAWCLIPPER lpDDClipper);
    STDMETHODIMP SetColorKey(DWORD dwFlags,__in LPDDCOLORKEY lpDDColorKey);
    STDMETHODIMP SetOverlayPosition(LONG dwX,LONG dwY);
    STDMETHODIMP SetPalette(__in LPDIRECTDRAWPALETTE lpDDPalette);
    STDMETHODIMP Unlock(__in LPVOID lpSurfaceData);
    STDMETHODIMP UpdateOverlay(__in LPRECT lpSrcRect,__in LPDIRECTDRAWSURFACE lpDDDestSurface,__in LPRECT lpDestRect,DWORD dwFlags,__in LPDDOVERLAYFX lpDDOverlayFX);
    STDMETHODIMP UpdateOverlayDisplay(DWORD dwFlags);
    STDMETHODIMP UpdateOverlayZOrder(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSReference);
};

class CLoadDirectDraw
{
    LPDIRECTDRAW m_pDirectDraw;     // The DirectDraw driver instance
    HINSTANCE m_hDirectDraw;        // Handle to the loaded library

public:

    CLoadDirectDraw();
    ~CLoadDirectDraw();

    HRESULT LoadDirectDraw(__in LPSTR szDevice);
    void ReleaseDirectDraw();
    HRESULT IsDirectDrawLoaded();
    LPDIRECTDRAW GetDirectDraw();
    BOOL IsDirectDrawVersion1();
};

#endif // __VIDEOCTL__