text:
namespace {

AutocompleteMatchType::Type GetAutocompleteMatchType(const std::string& type) {
  if (type == "ENTITY")
    return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY;
  if (type == "INFINITE")
    return AutocompleteMatchType::SEARCH_SUGGEST_INFINITE;
  if (type == "PERSONALIZED_QUERY")
    return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED;
  if (type == "PROFILE")
    return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
  return AutocompleteMatchType::SEARCH_SUGGEST;
}

} // namespace

// SuggestionDeletionHandler -------------------------------------------------

// This class handles making requests to the server in order to delete
// personalized suggestions.
class SuggestionDeletionHandler : public net::URLFetcherDelegate {
 public:
  typedef base::Callback<void(bool, SuggestionDeletionHandler*)>
      DeletionCompletedCallback;

  SuggestionDeletionHandler(
      const std::string& deletion_url,
      Profile* profile,
      const DeletionCompletedCallback& callback);

  virtual ~SuggestionDeletionHandler();

 private:
  // net::URLFetcherDelegate:
  virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;

  scoped_ptr<net::URLFetcher> deletion_fetcher_;
  DeletionCompletedCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler);
};

SuggestionDeletionHandler::SuggestionDeletionHandler(
    const std::string& deletion_url,
    Profile* profile,
    const DeletionCompletedCallback& callback) : callback_(callback) {
  GURL url(deletion_url);
  DCHECK(url.is_valid());

  deletion_fetcher_.reset(net::URLFetcher::Create(
      BaseSearchProvider::kDeletionURLFetcherID,
      url,
      net::URLFetcher::GET,
      this));
  deletion_fetcher_->SetRequestContext(profile->GetRequestContext());
  deletion_fetcher_->Start();
};

SuggestionDeletionHandler::~SuggestionDeletionHandler() {
};

void SuggestionDeletionHandler::OnURLFetchComplete(
    const net::URLFetcher* source) {
  DCHECK(source == deletion_fetcher_.get());
  callback_.Run(
      source->GetStatus().is_success() && (source->GetResponseCode() == 200),
      this);
};

// BaseSearchProvider ---------------------------------------------------------

// static
const int BaseSearchProvider::kDefaultProviderURLFetcherID = 1;
const int BaseSearchProvider::kKeywordProviderURLFetcherID = 2;
const int BaseSearchProvider::kDeletionURLFetcherID = 3;

BaseSearchProvider::BaseSearchProvider(AutocompleteProviderListener* listener,
                                       Profile* profile,
                                       AutocompleteProvider::Type type)
    : AutocompleteProvider(listener, profile, type),
      field_trial_triggered_(false),
      field_trial_triggered_in_session_(false),
      suggest_results_pending_(0) {
}

// static
bool BaseSearchProvider::ShouldPrefetch(const AutocompleteMatch& match) {
  return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue;
}

// static
AutocompleteMatch BaseSearchProvider::CreateSearchSuggestion(
    const base::string16& suggestion,
    AutocompleteMatchType::Type type,
    bool from_keyword_provider,
    const TemplateURL* template_url) {
  return CreateSearchSuggestion(
      NULL, AutocompleteInput(), BaseSearchProvider::SuggestResult(
          suggestion, type, suggestion, base::string16(), base::string16(),
          std::string(), std::string(), from_keyword_provider, 0, false, false,
          base::string16()),
      template_url, 0, 0, false);
}

void BaseSearchProvider::Stop(bool clear_cached_results) {
  StopSuggest();
  done_ = true;

  if (clear_cached_results)
    ClearAllResults();
}

void BaseSearchProvider::DeleteMatch(const AutocompleteMatch& match) {
  DCHECK(match.deletable);

  if (!match.GetAdditionalInfo(BaseSearchProvider::kDeletionUrlKey).empty()) {
    deletion_handlers_.push_back(new SuggestionDeletionHandler(
        match.GetAdditionalInfo(BaseSearchProvider::kDeletionUrlKey),
        profile_,
        base::Bind(&BaseSearchProvider::OnDeletionComplete,
                   base::Unretained(this))));
  }

  HistoryService* const history_service =
      HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
  TemplateURL* template_url = match.GetTemplateURL(profile_, false);
  // This may be NULL if the template corresponding to the keyword has been
  // deleted or there is no keyword set.
  if (template_url != NULL) {
    history_service->DeleteMatchingURLsForKeyword(template_url->id(),
                                                  match.contents);
  }

  // Immediately update the list of matches to show the match was deleted,
  // regardless of whether the server request actually succeeds.
  DeleteMatchFromMatches(match);
}

void BaseSearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
  provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
  metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
  new_entry.set_provider(AsOmniboxEventProviderType());
  new_entry.set_provider_done(done_);
  std::vector<uint32> field_trial_hashes;
  OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
  for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
    if (field_trial_triggered_)
      new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
    if (field_trial_triggered_in_session_) {
      new_entry.mutable_field_trial_triggered_in_session()->Add(
          field_trial_hashes[i]);
    }
  }
}

// static
const char BaseSearchProvider::kRelevanceFromServerKey[] =
    "relevance_from_server";
const char BaseSearchProvider::kShouldPrefetchKey[] = "should_prefetch";
const char BaseSearchProvider::kSuggestMetadataKey[] = "suggest_metadata";
const char BaseSearchProvider::kDeletionUrlKey[] = "deletion_url";
const char BaseSearchProvider::kTrue[] = "true";
const char BaseSearchProvider::kFalse[] = "false";

BaseSearchProvider::~BaseSearchProvider() {}

// BaseSearchProvider::Result --------------------------------------------------

BaseSearchProvider::Result::Result(bool from_keyword_provider,
                                   int relevance,
                                   bool relevance_from_server)
    : from_keyword_provider_(from_keyword_provider),
      relevance_(relevance),
      relevance_from_server_(relevance_from_server) {}

BaseSearchProvider::Result::~Result() {}

// BaseSearchProvider::SuggestResult -------------------------------------------

BaseSearchProvider::SuggestResult::SuggestResult(
    const base::string16& suggestion,
    AutocompleteMatchType::Type type,
    const base::string16& match_contents,
    const base::string16& match_contents_prefix,
    const base::string16& annotation,
    const std::string& suggest_query_params,
    const std::string& deletion_url,
    bool from_keyword_provider,
    int relevance,
    bool relevance_from_server,
    bool should_prefetch,
    const base::string16& input_text)
    : Result(from_keyword_provider, relevance, relevance_from_server),
      suggestion_(suggestion),
      type_(type),
      match_contents_prefix_(match_contents_prefix),
      annotation_(annotation),
      suggest_query_params_(suggest_query_params),
      deletion_url_(deletion_url),
      should_prefetch_(should_prefetch) {
  match_contents_ = match_contents;
  DCHECK(!match_contents_.empty());
  ClassifyMatchContents(true, input_text);
}

BaseSearchProvider::SuggestResult::~SuggestResult() {}

void BaseSearchProvider::SuggestResult::ClassifyMatchContents(
    const bool allow_bolding_all,
    const base::string16& input_text) {
  if (input_text.empty()) {
    // In case of zero-suggest results, do not highlight matches.
    match_contents_class_.push_back(
        ACMatchClassification(0, ACMatchClassification::NONE));
    return;
  }

  base::string16 lookup_text = input_text;
  if (type_ == AutocompleteMatchType::SEARCH_SUGGEST_INFINITE) {
    const size_t contents_index =
        suggestion_.length() - match_contents_.length();
    // Ensure the query starts with the input text, and ends with the match
    // contents, and the input text has an overlap with contents.
    if (StartsWith(suggestion_, input_text, true) &&
        EndsWith(suggestion_, match_contents_, true) &&
        (input_text.length() > contents_index)) {
      lookup_text = input_text.substr(contents_index);
    }
  }
  size_t lookup_position = match_contents_.find(lookup_text);
  if (!allow_bolding_all && (lookup_position == base::string16::npos)) {
    // Bail if the code below to update the bolding would bold the whole
    // string.  Note that the string may already be entirely bolded; if
    // so, leave it as is.
    return;
  }
  match_contents_class_.clear();
  // We do intra-string highlighting for suggestions - the suggested segment
  // will be highlighted, e.g. for input_text = "you" the suggestion may be
  // "youtube", so we'll bold the "tube" section: you*tube*.
  if (input_text != match_contents_) {
    if (lookup_position == base::string16::npos) {
      // The input text is not a substring of the query string, e.g. input
      // text is "slasdot" and the query string is "slashdot", so we bold the
      // whole thing.
      match_contents_class_.push_back(
          ACMatchClassification(0, ACMatchClassification::MATCH));
    } else {
      // We don't iterate over the string here annotating all matches because
      // it looks odd to have every occurrence of a substring that may be as
      // short as a single character highlighted in a query suggestion result,
      // e.g. for input text "s" and query string "southwest airlines", it
      // looks odd if both the first and last s are highlighted.
      if (lookup_position != 0) {
        match_contents_class_.push_back(
            ACMatchClassification(0, ACMatchClassification::MATCH));
      }
      match_contents_class_.push_back(
          ACMatchClassification(lookup_position, ACMatchClassification::NONE));
      size_t next_fragment_position = lookup_position + lookup_text.length();
      if (next_fragment_position < match_contents_.length()) {
        match_contents_class_.push_back(ACMatchClassification(
            next_fragment_position, ACMatchClassification::MATCH));
      }
    }
  } else {
    // Otherwise, match_contents_ is a verbatim (what-you-typed) match, either
    // for the default provider or a keyword search provider.
    match_contents_class_.push_back(
        ACMatchClassification(0, ACMatchClassification::NONE));
  }
}

bool BaseSearchProvider::SuggestResult::IsInlineable(
    const base::string16& input) const {
  return StartsWith(suggestion_, input, false);
}

int BaseSearchProvider::SuggestResult::CalculateRelevance(
    const AutocompleteInput& input,
    bool keyword_provider_requested) const {
  if (!from_keyword_provider_ && keyword_provider_requested)
    return 100;
  return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
}

// BaseSearchProvider::NavigationResult ----------------------------------------

BaseSearchProvider::NavigationResult::NavigationResult(
    const AutocompleteProvider& provider,
    const GURL& url,
    const base::string16& description,
    bool from_keyword_provider,
    int relevance,
    bool relevance_from_server,
    const base::string16& input_text,
    const std::string& languages)
    : Result(from_keyword_provider, relevance, relevance_from_server),
      url_(url),
      formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
          url,
          provider.StringForURLDisplay(url, true, false))),
      description_(description) {
  DCHECK(url_.is_valid());
  CalculateAndClassifyMatchContents(true, input_text, languages);
}

BaseSearchProvider::NavigationResult::~NavigationResult() {}

void BaseSearchProvider::NavigationResult::CalculateAndClassifyMatchContents(
    const bool allow_bolding_nothing,
    const base::string16& input_text,
    const std::string& languages) {
  if (input_text.empty()) {
    // In case of zero-suggest results, do not highlight matches.
    match_contents_class_.push_back(
        ACMatchClassification(0, ACMatchClassification::NONE));
    return;
  }

  // First look for the user's input inside the formatted url as it would be
  // without trimming the scheme, so we can find matches at the beginning of the
  // scheme.
  const URLPrefix* prefix =
      URLPrefix::BestURLPrefix(formatted_url_, input_text);
  size_t match_start = (prefix == NULL) ?
      formatted_url_.find(input_text) : prefix->prefix.length();
  bool trim_http = !AutocompleteInput::HasHTTPScheme(input_text) &&
                   (!prefix || (match_start != 0));
  const net::FormatUrlTypes format_types =
      net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);

  base::string16 match_contents = net::FormatUrl(url_, languages, format_types,
      net::UnescapeRule::SPACES, NULL, NULL, &match_start);
  // If the first match in the untrimmed string was inside a scheme that we
  // trimmed, look for a subsequent match.
  if (match_start == base::string16::npos)
    match_start = match_contents.find(input_text);
  // Update |match_contents_| and |match_contents_class_| if it's allowed.
  if (allow_bolding_nothing || (match_start != base::string16::npos)) {
    match_contents_ = match_contents;
    // Safe if |match_start| is npos; also safe if the input is longer than the
    // remaining contents after |match_start|.
    AutocompleteMatch::ClassifyLocationInString(match_start,
        input_text.length(), match_contents_.length(),
        ACMatchClassification::URL, &match_contents_class_);
  }
}

bool BaseSearchProvider::NavigationResult::IsInlineable(
    const base::string16& input) const {
  return
      URLPrefix::BestURLPrefix(base::UTF8ToUTF16(url_.spec()), input) != NULL;
}

int BaseSearchProvider::NavigationResult::CalculateRelevance(
    const AutocompleteInput& input,
    bool keyword_provider_requested) const {
  return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
}

// BaseSearchProvider::Results -------------------------------------------------

BaseSearchProvider::Results::Results() : verbatim_relevance(-1) {}

BaseSearchProvider::Results::~Results() {}

void BaseSearchProvider::Results::Clear() {
  suggest_results.clear();
  navigation_results.clear();
  verbatim_relevance = -1;
  metadata.clear();
}

bool BaseSearchProvider::Results::HasServerProvidedScores() const {
  if (verbatim_relevance >= 0)
    return true;

  // Right now either all results of one type will be server-scored or they will
  // all be locally scored, but in case we change this later, we'll just check
  // them all.
  for (SuggestResults::const_iterator i(suggest_results.begin());
       i != suggest_results.end(); ++i) {
    if (i->relevance_from_server())
      return true;
  }
  for (NavigationResults::const_iterator i(navigation_results.begin());
       i != navigation_results.end(); ++i) {
    if (i->relevance_from_server())
      return true;
  }

  return false;
}

// BaseSearchProvider ---------------------------------------------------------

// static
AutocompleteMatch BaseSearchProvider::CreateSearchSuggestion(
    AutocompleteProvider* autocomplete_provider,
    const AutocompleteInput& input,
    const SuggestResult& suggestion,
    const TemplateURL* template_url,
    int accepted_suggestion,
    int omnibox_start_margin,
    bool append_extra_query_params) {
  AutocompleteMatch match(autocomplete_provider, suggestion.relevance(), false,
                          suggestion.type());

  if (!template_url)
    return match;
  match.keyword = template_url->keyword();
  match.contents = suggestion.match_contents();
  match.contents_class = suggestion.match_contents_class();
  if (suggestion.type() == AutocompleteMatchType::SEARCH_SUGGEST_INFINITE) {
    match.RecordAdditionalInfo(
        kACMatchPropertyInputText, base::UTF16ToUTF8(input.text()));
    match.RecordAdditionalInfo(
        kACMatchPropertyContentsPrefix,
        base::UTF16ToUTF8(suggestion.match_contents_prefix()));
    match.RecordAdditionalInfo(
        kACMatchPropertyContentsStartIndex,
        static_cast<int>(
            suggestion.suggestion().length() - match.contents.length()));
  }

  if (!suggestion.annotation().empty())
    match.description = suggestion.annotation();

  // suggestion.match_contents() should have already been collapsed.
  match.allowed_to_be_default_match =
      (base::CollapseWhitespace(input.text(), false) ==
       suggestion.match_contents());

  // When the user forced a query, we need to make sure all the fill_into_edit
  // values preserve that property.  Otherwise, if the user starts editing a
  // suggestion, non-Search results will suddenly appear.
  if (input.type() == AutocompleteInput::FORCED_QUERY)
    match.fill_into_edit.assign(base::ASCIIToUTF16("?"));
  if (suggestion.from_keyword_provider())
    match.fill_into_edit.append(match.keyword + base::char16(' '));
  if (!input.prevent_inline_autocomplete() &&
      StartsWith(suggestion.suggestion(), input.text(), false)) {
    match.inline_autocompletion =
        suggestion.suggestion().substr(input.text().length());
    match.allowed_to_be_default_match = true;
  }
  match.fill_into_edit.append(suggestion.suggestion());

  const TemplateURLRef& search_url = template_url->url_ref();
  DCHECK(search_url.SupportsReplacement());
  match.search_terms_args.reset(
      new TemplateURLRef::SearchTermsArgs(suggestion.suggestion()));
  match.search_terms_args->original_query = input.text();
  match.search_terms_args->accepted_suggestion = accepted_suggestion;
  match.search_terms_args->omnibox_start_margin = omnibox_start_margin;
  match.search_terms_args->suggest_query_params =
      suggestion.suggest_query_params();
  match.search_terms_args->append_extra_query_params =
      append_extra_query_params;
  // This is the destination URL sans assisted query stats.  This must be set
  // so the AutocompleteController can properly de-dupe; the controller will
  // eventually overwrite it before it reaches the user.
  match.destination_url =
      GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));

  // Search results don't look like URLs.
  match.transition = suggestion.from_keyword_provider() ?
      content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;

  return match;
}

// static
scoped_ptr<base::Value> BaseSearchProvider::DeserializeJsonData(
    std::string json_data) {
  // The JSON response should be an array.
  for (size_t response_start_index = json_data.find("["), i = 0;
       response_start_index != std::string::npos && i < 5;
       response_start_index = json_data.find("[", 1), i++) {
    // Remove any XSSI guards to allow for JSON parsing.
    if (response_start_index > 0)
      json_data.erase(0, response_start_index);

    JSONStringValueSerializer deserializer(json_data);
    deserializer.set_allow_trailing_comma(true);
    int error_code = 0;
    scoped_ptr<base::Value> data(deserializer.Deserialize(&error_code, NULL));
    if (error_code == 0)
      return data.Pass();
  }
  return scoped_ptr<base::Value>();
}

// static
bool BaseSearchProvider::ZeroSuggestEnabled(
    const GURL& suggest_url,
    const TemplateURL* template_url,
    AutocompleteInput::PageClassification page_classification,
    Profile* profile) {
  if (!OmniboxFieldTrial::InZeroSuggestFieldTrial())
    return false;

  // Make sure we are sending the suggest request through HTTPS to prevent
  // exposing the current page URL or personalized results without encryption.
  if (!suggest_url.SchemeIs(content::kHttpsScheme))
    return false;

  // Don't show zero suggest on the NTP.
  // TODO(hfung): Experiment with showing MostVisited zero suggest on NTP
  // under the conditions described in crbug.com/305366.
  if ((page_classification ==
       AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS) ||
      (page_classification ==
       AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS))
    return false;

  // Don't run if there's no profile or in incognito mode.
  if (profile == NULL || profile->IsOffTheRecord())
    return false;

  // Don't run if we can't get preferences or search suggest is not enabled.
  PrefService* prefs = profile->GetPrefs();
  if (!prefs->GetBoolean(prefs::kSearchSuggestEnabled))
    return false;

  // Only make the request if we know that the provider supports zero suggest
  // (currently only the prepopulated Google provider).
  if (template_url == NULL || !template_url->SupportsReplacement() ||
      TemplateURLPrepopulateData::GetEngineType(*template_url) !=
      SEARCH_ENGINE_GOOGLE)
    return false;

  return true;
}

// static
bool BaseSearchProvider::CanSendURL(
    const GURL& current_page_url,
    const GURL& suggest_url,
    const TemplateURL* template_url,
    AutocompleteInput::PageClassification page_classification,
    Profile* profile) {
  if (!ZeroSuggestEnabled(suggest_url, template_url, page_classification,
                          profile))
    return false;

  if (!current_page_url.is_valid())
    return false;

  // Only allow HTTP URLs or HTTPS URLs for the same domain as the search
  // provider.
  if ((current_page_url.scheme() != content::kHttpScheme) &&
      ((current_page_url.scheme() != content::kHttpsScheme) ||
       !net::registry_controlled_domains::SameDomainOrHost(
           current_page_url, suggest_url,
           net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)))
    return false;

  // Check field trials and settings allow sending the URL on suggest requests.
  ProfileSyncService* service =
      ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
  sync_driver::SyncPrefs sync_prefs(profile->GetPrefs());
  if (service == NULL ||
      !service->IsSyncEnabledAndLoggedIn() ||
      !sync_prefs.GetPreferredDataTypes(syncer::UserTypes()).Has(
          syncer::PROXY_TABS) ||
      service->GetEncryptedDataTypes().Has(syncer::SESSIONS))
    return false;

  return true;
}

void BaseSearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
  DCHECK(!done_);
  suggest_results_pending_--;
  DCHECK_GE(suggest_results_pending_, 0);  // Should never go negative.

  const bool is_keyword = IsKeywordFetcher(source);

  // Ensure the request succeeded and that the provider used is still available.
  // A verbatim match cannot be generated without this provider, causing errors.
  const bool request_succeeded =
      source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
      GetTemplateURL(is_keyword);

  LogFetchComplete(request_succeeded, is_keyword);

  bool results_updated = false;
  if (request_succeeded) {
    const net::HttpResponseHeaders* const response_headers =
        source->GetResponseHeaders();
    std::string json_data;
    source->GetResponseAsString(&json_data);

    // JSON is supposed to be UTF-8, but some suggest service providers send
    // JSON files in non-UTF-8 encodings.  The actual encoding is usually
    // specified in the Content-Type header field.
    if (response_headers) {
      std::string charset;
      if (response_headers->GetCharset(&charset)) {
        base::string16 data_16;
        // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
        if (base::CodepageToUTF16(json_data, charset.c_str(),
                                  base::OnStringConversionError::FAIL,
                                  &data_16))
          json_data = base::UTF16ToUTF8(data_16);
      }
    }

    scoped_ptr<base::Value> data(DeserializeJsonData(json_data));
    results_updated = data.get() && ParseSuggestResults(
        *data.get(), is_keyword, GetResultsToFill(is_keyword));
  }

  UpdateMatches();
  if (done_ || results_updated)
    listener_->OnProviderUpdate(results_updated);
}

void BaseSearchProvider::AddMatchToMap(const SuggestResult& result,
                                       const std::string& metadata,
                                       int accepted_suggestion,
                                       bool mark_as_deletable,
                                       MatchMap* map) {
  InstantService* instant_service =
      InstantServiceFactory::GetForProfile(profile_);
  // Android and iOS have no InstantService.
  const int omnibox_start_margin = instant_service ?
      instant_service->omnibox_start_margin() : chrome::kDisableStartMargin;

  AutocompleteMatch match = CreateSearchSuggestion(
      this, GetInput(result.from_keyword_provider()), result,
      GetTemplateURL(result.from_keyword_provider()), accepted_suggestion,
      omnibox_start_margin, ShouldAppendExtraParams(result));
  if (!match.destination_url.is_valid())
    return;
  match.search_terms_args->bookmark_bar_pinned =
      profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
  match.RecordAdditionalInfo(kRelevanceFromServerKey,
                             result.relevance_from_server() ? kTrue : kFalse);
  match.RecordAdditionalInfo(kShouldPrefetchKey,
                             result.should_prefetch() ? kTrue : kFalse);

  if (!result.deletion_url().empty()) {
    GURL url(match.destination_url.GetOrigin().Resolve(result.deletion_url()));
    if (url.is_valid()) {
      match.RecordAdditionalInfo(kDeletionUrlKey, url.spec());
      match.deletable = true;
    }
  } else if (mark_as_deletable) {
    match.deletable = true;
  }

  // Metadata is needed only for prefetching queries.
  if (result.should_prefetch())
    match.RecordAdditionalInfo(kSuggestMetadataKey, metadata);

  // Try to add |match| to |map|.  If a match for this suggestion is
  // already in |map|, replace it if |match| is more relevant.
  // NOTE: Keep this ToLower() call in sync with url_database.cc.
  MatchKey match_key(
      std::make_pair(base::i18n::ToLower(result.suggestion()),
                     match.search_terms_args->suggest_query_params));
  const std::pair<MatchMap::iterator, bool> i(
       map->insert(std::make_pair(match_key, match)));

  bool should_prefetch = result.should_prefetch();
  if (!i.second) {
    // NOTE: We purposefully do a direct relevance comparison here instead of
    // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
    // added first" rather than "items alphabetically first" when the scores
    // are equal. The only case this matters is when a user has results with
    // the same score that differ only by capitalization; because the history
    // system returns results sorted by recency, this means we'll pick the most
    // recent such result even if the precision of our relevance score is too
    // low to distinguish the two.
    if (match.relevance > i.first->second.relevance) {
      match.duplicate_matches.insert(match.duplicate_matches.end(),
                                     i.first->second.duplicate_matches.begin(),
                                     i.first->second.duplicate_matches.end());
      i.first->second.duplicate_matches.clear();
      match.duplicate_matches.push_back(i.first->second);
      i.first->second = match;
    } else {
      i.first->second.duplicate_matches.push_back(match);
      if (match.keyword == i.first->second.keyword) {
        // Old and new matches are from the same search provider. It is okay to
        // record one match's prefetch data onto a different match (for the same
        // query string) for the following reasons:
        // 1. Because the suggest server only sends down a query string from
        // which we construct a URL, rather than sending a full URL, and because
        // we construct URLs from query strings in the same way every time, the
        // URLs for the two matches will be the same. Therefore, we won't end up
        // prefetching something the server didn't intend.
        // 2. Presumably the server sets the prefetch bit on a match it things
        // is sufficiently relevant that the user is likely to choose it.
        // Surely setting the prefetch bit on a match of even higher relevance
        // won't violate this assumption.
        should_prefetch |= ShouldPrefetch(i.first->second);
        i.first->second.RecordAdditionalInfo(kShouldPrefetchKey,
                                             should_prefetch ? kTrue : kFalse);
        if (should_prefetch)
          i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
      }
    }
  }
}

bool BaseSearchProvider::ParseSuggestResults(const base::Value& root_val,
                                             bool is_keyword_result,
                                             Results* results) {
  base::string16 query;
  const base::ListValue* root_list = NULL;
  const base::ListValue* results_list = NULL;
  const AutocompleteInput& input = GetInput(is_keyword_result);

  if (!root_val.GetAsList(&root_list) || !root_list->GetString(0, &query) ||
      query != input.text() || !root_list->GetList(1, &results_list))
    return false;

  // 3rd element: Description list.
  const base::ListValue* descriptions = NULL;
  root_list->GetList(2, &descriptions);

  // 4th element: Disregard the query URL list for now.

  // Reset suggested relevance information.
  results->verbatim_relevance = -1;

  // 5th element: Optional key-value pairs from the Suggest server.
  const base::ListValue* types = NULL;
  const base::ListValue* relevances = NULL;
  const base::ListValue* suggestion_details = NULL;
  const base::DictionaryValue* extras = NULL;
  int prefetch_index = -1;
  if (root_list->GetDictionary(4, &extras)) {
    extras->GetList("google:suggesttype", &types);

    // Discard this list if its size does not match that of the suggestions.
    if (extras->GetList("google:suggestrelevance", &relevances) &&
        (relevances->GetSize() != results_list->GetSize()))
      relevances = NULL;
    extras->GetInteger("google:verbatimrelevance",
                       &results->verbatim_relevance);

    // Check if the active suggest field trial (if any) has triggered either
    // for the default provider or keyword provider.
    bool triggered = false;
    extras->GetBoolean("google:fieldtrialtriggered", &triggered);
    field_trial_triggered_ |= triggered;
    field_trial_triggered_in_session_ |= triggered;

    const base::DictionaryValue* client_data = NULL;
    if (extras->GetDictionary("google:clientdata", &client_data) && client_data)
      client_data->GetInteger("phi", &prefetch_index);

    if (extras->GetList("google:suggestdetail", &suggestion_details) &&
        suggestion_details->GetSize() != results_list->GetSize())
      suggestion_details = NULL;

    // Store the metadata that came with the response in case we need to pass it
    // along with the prefetch query to Instant.
    JSONStringValueSerializer json_serializer(&results->metadata);
    json_serializer.Serialize(*extras);
  }

  // Clear the previous results now that new results are available.
  results->suggest_results.clear();
  results->navigation_results.clear();

  base::string16 suggestion;
  std::string type;
  int relevance = GetDefaultResultRelevance();
  // Prohibit navsuggest in FORCED_QUERY mode.  Users wants queries, not URLs.
  const bool allow_navsuggest = input.type() != AutocompleteInput::FORCED_QUERY;
  const std::string languages(
      profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
  const base::string16& trimmed_input =
      base::CollapseWhitespace(input.text(), false);
  for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) {
    // Google search may return empty suggestions for weird input characters,
    // they make no sense at all and can cause problems in our code.
    if (suggestion.empty())
      continue;

    // Apply valid suggested relevance scores; discard invalid lists.
    if (relevances != NULL && !relevances->GetInteger(index, &relevance))
      relevances = NULL;

    if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
      // Do not blindly trust the URL coming from the server to be valid.
      GURL url(URLFixerUpper::FixupURL(
          base::UTF16ToUTF8(suggestion), std::string()));
      if (url.is_valid() && allow_navsuggest) {
        base::string16 title;
        if (descriptions != NULL)
          descriptions->GetString(index, &title);
        results->navigation_results.push_back(NavigationResult(
            *this, url, title, is_keyword_result, relevance,
            relevances != NULL, input.text(), languages));
      }
    } else {
      AutocompleteMatchType::Type match_type = GetAutocompleteMatchType(type);
      bool should_prefetch = static_cast<int>(index) == prefetch_index;
      const base::DictionaryValue* suggestion_detail = NULL;
      base::string16 match_contents = suggestion;
      base::string16 match_contents_prefix;
      base::string16 annotation;
      std::string suggest_query_params;
      std::string deletion_url;

      if (suggestion_details) {
        suggestion_details->GetDictionary(index, &suggestion_detail);
        if (suggestion_detail) {
          suggestion_detail->GetString("du", &deletion_url);
          suggestion_detail->GetString("t", &match_contents);
          suggestion_detail->GetString("mp", &match_contents_prefix);
          // Error correction for bad data from server.
          if (match_contents.empty())
            match_contents = suggestion;
          suggestion_detail->GetString("a", &annotation);
          suggestion_detail->GetString("q", &suggest_query_params);
        }
      }

      // TODO(kochi): Improve calculator suggestion presentation.
      results->suggest_results.push_back(SuggestResult(
          base::CollapseWhitespace(suggestion, false), match_type,
          base::CollapseWhitespace(match_contents, false),
          match_contents_prefix, annotation, suggest_query_params,
          deletion_url, is_keyword_result, relevance, relevances != NULL,
          should_prefetch, trimmed_input));
    }
  }
  SortResults(is_keyword_result, relevances, results);
  return true;
}

void BaseSearchProvider::SortResults(bool is_keyword,
                                     const base::ListValue* relevances,
                                     Results* results) {
}

void BaseSearchProvider::DeleteMatchFromMatches(
    const AutocompleteMatch& match) {
  for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i) {
    // Find the desired match to delete by checking the type and contents.
    // We can't check the destination URL, because the autocomplete controller
    // may have reformulated that. Not that while checking for matching
    // contents works for personalized suggestions, if more match types gain
    // deletion support, this algorithm may need to be re-examined.
    if (i->contents == match.contents && i->type == match.type) {
      matches_.erase(i);
      break;
    }
  }
}

void BaseSearchProvider::OnDeletionComplete(
    bool success, SuggestionDeletionHandler* handler) {
  RecordDeletionResult(success);
  SuggestionDeletionHandlers::iterator it = std::find(
      deletion_handlers_.begin(), deletion_handlers_.end(), handler);
  DCHECK(it != deletion_handlers_.end());
  deletion_handlers_.erase(it);
}


text:
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from tekton import router
from gaecookie.decorator import no_csrf
from rota_app import facade
from routes.rotas.admin import new, edit

def delete(_handler, rota_id):
    facade.delete_rota_cmd(rota_id)()
    _handler.redirect(router.to_path(index))

@no_csrf
def index():
    cmd = facade.list_rotas_cmd()
    rotas = cmd()
    edit_path = router.to_path(edit)
    delete_path = router.to_path(delete)
    short_form = facade.rota_short_form()

    def short_rota_dict(rota):
        rota_dct = short_form.fill_with_model(rota)
        rota_dct['edit_path'] = router.to_path(edit_path, rota_dct['id'])
        rota_dct['delete_path'] = router.to_path(delete_path, rota_dct['id'])
        return rota_dct

    short_rotas = [short_rota_dict(rota) for rota in rotas]
    context = {'rotas': short_rotas,
               'new_path': router.to_path(new)}
    return TemplateResponse(context)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sylius\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150818142828 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE sylius_payment_method_translation (id INT AUTO_INCREMENT NOT NULL, translatable_id INT NOT NULL, name VARCHAR(255) NOT NULL, description VARCHAR(255) DEFAULT NULL, locale VARCHAR(255) NOT NULL, INDEX IDX_966BE3A12C2AC5D3 (translatable_id), UNIQUE INDEX sylius_payment_method_translation_uniq_trans (translatable_id, locale), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE sylius_payment_method_translation ADD CONSTRAINT FK_966BE3A12C2AC5D3 FOREIGN KEY (translatable_id) REFERENCES sylius_payment_method (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE sylius_payment_method DROP name, DROP description');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE sylius_payment_method_translation');
        $this->addSql('ALTER TABLE sylius_payment_method ADD name VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, ADD description VARCHAR(255) DEFAULT NULL COLLATE utf8_unicode_ci');
    }
}


text:
package pacman.definition.scriptable.notEqual;

import pacman.definition.ActivityDefinition;
import pacman.definition.NotEqualDefinition;
import pacman.definition.scriptable.DefinitionAdapter;
import pacman.definition.scriptable.DefinitionExtension;

public class NotEqualDefinitionExtension implements DefinitionExtension {
	public String getName() {
		return "NotEqual";
	}

	public String getAdapterName() {
		return NotEqualDefinitionAdapter.class.getSimpleName();
	}

	public Class<? extends DefinitionAdapter<?>> getAdapterType() {
		return NotEqualDefinitionAdapter.class;
	}

	public ActivityDefinition create(Object... args) {
		return args == null ? new NotEqualDefinition() : new NotEqualDefinition((String) args[0]);
	}
}


text:
<?php

require_once __DIR__.'/actionresult.php';

interface IComponent {
    public function Init($init_data);
}

interface IControllerComponent extends IComponent {
    public function GetRouteName();
    public function HandleRequest($path, $query);
}

abstract class ComponentBase implements IComponent{
    public abstract function Init($init_data);

    public static function Instance()
    {
        static $instance = null;
        if ($instance === null)
        {
            $instance = new static();
        }
        return $instance;
    }

    protected static function getLogger() {
        static $logger;
        if ($logger === null) {
            $logger = new Logger(get_called_class());
        }
        return $logger;
    }
}

abstract class ControllerComponentBase extends ComponentBase implements IControllerComponent {
    public abstract function GetRouteName();
    public function HandleRequest($path, $query) {
        $action = $path[2];
        $method = $_SERVER['REQUEST_METHOD'];

        $function_name = "{$method}_{$action}";

        if (!method_exists($this, $function_name)) {
            $function_name = $action;
        }

        if (!method_exists($this, $function_name)) {
            return false;
        }

        $return_value = $this->$function_name($path, $query);
        if (isset($return_value)) {
            if ($return_value instanceof ActionResult) {
                $return_value->Output();
            }
        }
        return true;
    }

    protected function View($view_name) {
        include(ROOTPATH."/Views/$view_name.php");
    }
}

?>


text:
using Content.Client.CombatMode;
using Content.Client.Gameplay;
using Content.Client.Outline;
using Content.Client.Viewport;
using Content.Shared.ActionBlocker;
using Content.Shared.CCVar;
using Content.Shared.CombatMode;
using Content.Shared.DragDrop;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Events;
using Content.Shared.Popups;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.Player;
using Robust.Client.State;
using Robust.Shared.Configuration;
using Robust.Shared.Input;
using Robust.Shared.Input.Binding;
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
using DrawDepth = Content.Shared.DrawDepth.DrawDepth;

namespace Content.Client.DragDrop
{
    /// <summary>
    /// Handles clientside drag and drop logic
    /// </summary>
    [UsedImplicitly]
    public sealed class DragDropSystem : SharedDragDropSystem
    {
        [Dependency] private readonly IStateManager _stateManager = default!;
        [Dependency] private readonly IInputManager _inputManager = default!;
        [Dependency] private readonly IEyeManager _eyeManager = default!;
        [Dependency] private readonly IPlayerManager _playerManager = default!;
        [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
        [Dependency] private readonly IConfigurationManager _cfgMan = default!;
        [Dependency] private readonly InteractionOutlineSystem _outline = default!;
        [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!;
        [Dependency] private readonly CombatModeSystem _combatMode = default!;
        [Dependency] private readonly InputSystem _inputSystem = default!;
        [Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!;
        [Dependency] private readonly EntityLookupSystem _lookup = default!;

        // how often to recheck possible targets (prevents calling expensive
        // check logic each update)
        private const float TargetRecheckInterval = 0.25f;

        // if a drag ends up being cancelled and it has been under this
        // amount of time since the mousedown, we will "replay" the original
        // mousedown event so it can be treated like a regular click
        private const float MaxMouseDownTimeForReplayingClick = 0.85f;

        private const string ShaderDropTargetInRange = "SelectionOutlineInrange";
        private const string ShaderDropTargetOutOfRange = "SelectionOutline";

        // entity performing the drag action

        private EntityUid _dragger;
        private readonly List<IDraggable> _draggables = new();
        private EntityUid _dragShadow;

        // time since mouse down over the dragged entity
        private float _mouseDownTime;
        // how much time since last recheck of all possible targets
        private float _targetRecheckTime;
        // reserved initial mousedown event so we can replay it if no drag ends up being performed
        private PointerInputCmdHandler.PointerInputCmdArgs? _savedMouseDown;
        // whether we are currently replaying the original mouse down, so we
        // can ignore any events sent to this system
        private bool _isReplaying;

        private DragDropHelper<EntityUid> _dragDropHelper = default!;

        private ShaderInstance? _dropTargetInRangeShader;
        private ShaderInstance? _dropTargetOutOfRangeShader;

        private readonly List<SpriteComponent> _highlightedSprites = new();

        public override void Initialize()
        {
            UpdatesOutsidePrediction = true;
            UpdatesAfter.Add(typeof(EyeUpdateSystem));

            _dragDropHelper = new DragDropHelper<EntityUid>(OnBeginDrag, OnContinueDrag, OnEndDrag);
            _cfgMan.OnValueChanged(CCVars.DragDropDeadZone, SetDeadZone, true);

            _dropTargetInRangeShader = _prototypeManager.Index<ShaderPrototype>(ShaderDropTargetInRange).Instance();
            _dropTargetOutOfRangeShader = _prototypeManager.Index<ShaderPrototype>(ShaderDropTargetOutOfRange).Instance();
            // needs to fire on mouseup and mousedown so we can detect a drag / drop
            CommandBinds.Builder
                .BindBefore(EngineKeyFunctions.Use, new PointerInputCmdHandler(OnUse, false), new[] { typeof(SharedInteractionSystem) })
                .Register<DragDropSystem>();
        }

        private void SetDeadZone(float deadZone)
        {
            _dragDropHelper.Deadzone = deadZone;
        }

        public override void Shutdown()
        {
            _cfgMan.UnsubValueChanged(CCVars.DragDropDeadZone, SetDeadZone);
            _dragDropHelper.EndDrag();
            CommandBinds.Unregister<DragDropSystem>();
            base.Shutdown();
        }

        private bool OnUse(in PointerInputCmdHandler.PointerInputCmdArgs args)
        {
            // not currently predicted
            if (_inputSystem.Predicted) return false;

            // currently replaying a saved click, don't handle this because
            // we already decided this click doesn't represent an actual drag attempt
            if (_isReplaying) return false;

            if (args.State == BoundKeyState.Down)
            {
                return OnUseMouseDown(args);
            }
            else if (args.State == BoundKeyState.Up)
            {
                return OnUseMouseUp(args);
            }

            return false;
        }

        private bool OnUseMouseDown(in PointerInputCmdHandler.PointerInputCmdArgs args)
        {
            if (args.Session?.AttachedEntity is not {Valid: true} dragger ||
                _combatMode.IsInCombatMode())
            {
                return false;
            }

            // cancel any current dragging if there is one (shouldn't be because they would've had to have lifted
            // the mouse, canceling the drag, but just being cautious)
            _dragDropHelper.EndDrag();

            // possibly initiating a drag
            // check if the clicked entity is draggable
            if (!EntityManager.EntityExists(args.EntityUid))
            {
                return false;
            }

            // check if the entity is reachable
            if (!_interactionSystem.InRangeUnobstructed(dragger, args.EntityUid))
            {
                return false;
            }

            var canDrag = false;
            foreach (var draggable in EntityManager.GetComponents<IDraggable>(args.EntityUid))
            {
                var dragEventArgs = new StartDragDropEvent(dragger, args.EntityUid);

                if (!draggable.CanStartDrag(dragEventArgs))
                {
                    continue;
                }

                _draggables.Add(draggable);
                canDrag = true;
            }

            if (!canDrag)
            {
                return false;
            }

            // wait to initiate a drag
            _dragDropHelper.MouseDown(args.EntityUid);
            _dragger = dragger;
            _mouseDownTime = 0;

            // don't want anything else to process the click,
            // but we will save the event so we can "re-play" it if this drag does
            // not turn into an actual drag so the click can be handled normally
            _savedMouseDown = args;

            return true;

        }

        private bool OnBeginDrag()
        {
            if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged))
            {
                // something happened to the clicked entity or we moved the mouse off the target so
                // we shouldn't replay the original click
                return false;
            }

            if (EntityManager.TryGetComponent<SpriteComponent?>(_dragDropHelper.Dragged, out var draggedSprite))
            {
                // pop up drag shadow under mouse
                var mousePos = _eyeManager.ScreenToMap(_dragDropHelper.MouseScreenPosition);
                _dragShadow = EntityManager.SpawnEntity("dragshadow", mousePos);
                var dragSprite = EntityManager.GetComponent<SpriteComponent>(_dragShadow);
                dragSprite.CopyFrom(draggedSprite);
                dragSprite.RenderOrder = EntityManager.CurrentTick.Value;
                dragSprite.Color = dragSprite.Color.WithAlpha(0.7f);
                // keep it on top of everything
                dragSprite.DrawDepth = (int) DrawDepth.Overlays;
                if (!dragSprite.NoRotation)
                {
                    EntityManager.GetComponent<TransformComponent>(_dragShadow).WorldRotation = EntityManager.GetComponent<TransformComponent>(_dragDropHelper.Dragged).WorldRotation;
                }

                HighlightTargets();
                _outline.SetEnabled(false);

                // drag initiated
                return true;
            }

            Logger.Warning("Unable to display drag shadow for {0} because it" +
                           " has no sprite component.", EntityManager.GetComponent<MetaDataComponent>(_dragDropHelper.Dragged).EntityName);
            return false;
        }

        private bool OnContinueDrag(float frameTime)
        {
            if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged) ||
                _combatMode.IsInCombatMode())
            {
                return false;
            }

            DebugTools.AssertNotNull(_dragger);

            // still in range of the thing we are dragging?
            if (!_interactionSystem.InRangeUnobstructed(_dragger, _dragDropHelper.Dragged))
            {
                return false;
            }

            // TODO: would use MapPosition instead if it had a setter, but it has no setter.
            // is that intentional, or should we add a setter for Transform.MapPosition?
            if (_dragShadow == default)
                return false;

            _targetRecheckTime += frameTime;
            if (_targetRecheckTime > TargetRecheckInterval)
            {
                HighlightTargets();
                _targetRecheckTime -= TargetRecheckInterval;
            }

            return true;
        }

        private void OnEndDrag()
        {
            RemoveHighlights();
            if (_dragShadow != default)
            {
                EntityManager.DeleteEntity(_dragShadow);
            }

            _outline.SetEnabled(true);
            _dragShadow = default;
            _draggables.Clear();
            _dragger = default;
            _mouseDownTime = 0;
            _savedMouseDown = null;
        }

        private bool OnUseMouseUp(in PointerInputCmdHandler.PointerInputCmdArgs args)
        {
            if (_dragDropHelper.IsDragging == false || _dragDropHelper.Dragged == default)
            {
                // haven't started the drag yet, quick mouseup, definitely treat it as a normal click by
                // replaying the original cmd
                if (_savedMouseDown.HasValue && _mouseDownTime < MaxMouseDownTimeForReplayingClick)
                {
                    var savedValue = _savedMouseDown.Value;
                    _isReplaying = true;
                    // adjust the timing info based on the current tick so it appears as if it happened now
                    var replayMsg = savedValue.OriginalMessage;
                    var adjustedInputMsg = new FullInputCmdMessage(args.OriginalMessage.Tick, args.OriginalMessage.SubTick,
                        replayMsg.InputFunctionId, replayMsg.State, replayMsg.Coordinates, replayMsg.ScreenCoordinates, replayMsg.Uid);

                    if (savedValue.Session != null)
                    {
                        _inputSystem.HandleInputCommand(savedValue.Session, EngineKeyFunctions.Use, adjustedInputMsg, true);
                    }

                    _isReplaying = false;
                }
                _dragDropHelper.EndDrag();
                return false;
            }

            if (_dragger == default)
            {
                _dragDropHelper.EndDrag();
                return false;
            }

            IList<EntityUid> entities;

            if (_stateManager.CurrentState is GameplayState screen)
            {
                entities = screen.GetEntitiesUnderPosition(args.Coordinates);
            }
            else
            {
                entities = Array.Empty<EntityUid>();
            }

            var outOfRange = false;

            foreach (var entity in entities)
            {
                if (entity == _dragDropHelper.Dragged) continue;

                // check if it's able to be dropped on by current dragged entity
                var dropArgs = new DragDropEvent(_dragger, args.Coordinates, _dragDropHelper.Dragged, entity);

                // TODO: Cache valid CanDragDrops
                if (ValidDragDrop(dropArgs) != true) continue;

                if (!_interactionSystem.InRangeUnobstructed(dropArgs.User, dropArgs.Target)
                    || !_interactionSystem.InRangeUnobstructed(dropArgs.User, dropArgs.Dragged))
                {
                    outOfRange = true;
                    continue;
                }

                foreach (var draggable in _draggables)
                {
                    if (!draggable.CanDrop(dropArgs)) continue;

                    // tell the server about the drop attempt
                    RaiseNetworkEvent(new DragDropRequestEvent(args.Coordinates, _dragDropHelper.Dragged,
                        entity));

                    draggable.Drop(dropArgs);

                    _dragDropHelper.EndDrag();
                    return true;
                }
            }

            if (outOfRange &&
                _playerManager.LocalPlayer?.ControlledEntity is { } player &&
                player.IsValid())
            {
                player.PopupMessage(Loc.GetString("drag-drop-system-out-of-range-text"));
            }

            _dragDropHelper.EndDrag();
            return false;
        }

        // TODO make this just use TargetOutlineSystem
        private void HighlightTargets()
        {
            if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged) ||
                _dragShadow == default || Deleted(_dragShadow))
            {
                Logger.Warning("Programming error. Can't highlight drag and drop targets, not currently " +
                               "dragging anything or dragged entity / shadow was deleted.");
                return;
            }

            // highlights the possible targets which are visible
            // and able to be dropped on by the current dragged entity

            // remove current highlights
            RemoveHighlights();

            // find possible targets on screen even if not reachable
            // TODO: Duplicated in SpriteSystem and TargetOutlineSystem. Should probably be cached somewhere for a frame?
            var mousePos = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition).Position;
            var bounds = new Box2(mousePos - 1.5f, mousePos + 1.5f);
            var pvsEntities = _lookup.GetEntitiesIntersecting(_eyeManager.CurrentMap, bounds, LookupFlags.Approximate | LookupFlags.Anchored);
            foreach (var pvsEntity in pvsEntities)
            {
                if (!EntityManager.TryGetComponent(pvsEntity, out SpriteComponent? inRangeSprite) ||
                    !inRangeSprite.Visible ||
                    pvsEntity == _dragDropHelper.Dragged) continue;

                // check if it's able to be dropped on by current dragged entity
                var dropArgs = new DragDropEvent(_dragger, EntityManager.GetComponent<TransformComponent>(pvsEntity).Coordinates, _dragDropHelper.Dragged, pvsEntity);

                var valid = ValidDragDrop(dropArgs);
                if (valid == null) continue;

                // We'll do a final check given server-side does this before any dragdrop can take place.
                if (valid.Value)
                {
                    valid = _interactionSystem.InRangeUnobstructed(dropArgs.Target, dropArgs.Dragged)
                        && _interactionSystem.InRangeUnobstructed(dropArgs.Target, dropArgs.Target);
                }

                if (inRangeSprite.PostShader != null &&
                    inRangeSprite.PostShader != _dropTargetInRangeShader &&
                    inRangeSprite.PostShader != _dropTargetOutOfRangeShader)
                    return;

                // highlight depending on whether its in or out of range
                inRangeSprite.PostShader = valid.Value ? _dropTargetInRangeShader : _dropTargetOutOfRangeShader;
                inRangeSprite.RenderOrder = EntityManager.CurrentTick.Value;
                _highlightedSprites.Add(inRangeSprite);
            }
        }

        private void RemoveHighlights()
        {
            foreach (var highlightedSprite in _highlightedSprites)
            {
                if (highlightedSprite.PostShader != _dropTargetInRangeShader && highlightedSprite.PostShader != _dropTargetOutOfRangeShader)
                    continue;

                highlightedSprite.PostShader = null;
                highlightedSprite.RenderOrder = 0;
            }

            _highlightedSprites.Clear();
        }

        /// <summary>
        ///     Are these args valid for drag-drop?
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns>null if the target doesn't support IDragDropOn</returns>
        private bool? ValidDragDrop(DragDropEvent eventArgs)
        {
            if (!_actionBlockerSystem.CanInteract(eventArgs.User, eventArgs.Target))
            {
                return false;
            }

            // CanInteract() doesn't support checking a second "target" entity.
            // Doing so manually:
            var ev = new GettingInteractedWithAttemptEvent(eventArgs.User, eventArgs.Dragged);
            RaiseLocalEvent(eventArgs.Dragged, ev, true);
            if (ev.Cancelled)
                return false;

            var valid = CheckDragDropOn(eventArgs);

            foreach (var comp in EntityManager.GetComponents<IDragDropOn>(eventArgs.Target))
            {
                if (!comp.CanDragDropOn(eventArgs))
                {
                    valid = false;
                    // dragDropOn.Add(comp);
                    continue;
                }

                valid = true;
                break;
            }

            if (valid != true) return valid;

            // Need at least one IDraggable to return true or else we can't do shit
            valid = false;

            foreach (var comp in EntityManager.GetComponents<IDraggable>(eventArgs.User))
            {
                if (!comp.CanDrop(eventArgs)) continue;
                valid = true;
                break;
            }

            return valid;
        }

        public override void Update(float frameTime)
        {
            base.Update(frameTime);

            _dragDropHelper.Update(frameTime);
        }

        public override void FrameUpdate(float frameTime)
        {
            base.FrameUpdate(frameTime);

            // Update position every frame to make it smooth.
            if (_dragDropHelper.IsDragging)
            {
                var mousePos = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition);
                Transform(_dragShadow).WorldPosition = mousePos.Position;
            }
        }
    }
}


text:
var classCSF_1_1Zpt_1_1ExpressionEvaluators_1_1CSharpExpressions_1_1AssemblyReferenceConfigurationElement =
[
    [ "Name", "classCSF_1_1Zpt_1_1ExpressionEvaluators_1_1CSharpExpressions_1_1AssemblyReferenceConfigurationElement.html#a61cae094fd7892f39411899a60f4a6ae", null ]
];


text:
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import messages

from wildcard import api

class BaseDomainForm(forms.SelfHandlingForm):

    name = forms.CharField(label=_("Name"))

class CreateDomainForm(BaseDomainForm):

    def handle(self, request, data):
        try:
            domain = api.ripcord.domain_create(request, **data)
            messages.success(
                request,
                _(
                    'Domain "%s" was successfully created.'
                ) % data['name']
            )
            return domain
        except Exception:
            exceptions.handle(request, _('Unable to create domain.'))

class UpdateDomainForm(BaseDomainForm):

    uuid = forms.CharField(
        label=_("UUID"),
        widget=forms.TextInput(attrs={'readonly': 'true'}),
    )

    def __init__(self, *args, **kwargs):
        super(UpdateDomainForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder.remove('uuid')
        self.fields.keyOrder.insert(0, 'uuid')

    def handle(self, request, data):
        uuid = data.pop('uuid')
        try:
            api.ripcord.domain_update(request, uuid, **data)
            messages.success(
                request,
                _('Domain has been updated successfully.')
            )
        except Exception:
            exceptions.handle(request, ignore=True)
            messages.error(request, _('Unable to update the domain.'))
        return True


text:
/**
 * Min sparse table example
 *
 *
Download the code:

 * $ git clone https://github.com/williamfiset/algorithms
 *
 *
Run:

 * $ ./gradlew run -Palgorithm=datastructures.sparsetable.examples.MinSparseTable
 *
 *
Construction complexity: O(nlogn), query complexity: O(1)
 *
 * @author William Fiset, william.alexandre.fiset@gmail.com
 */
package com.williamfiset.algorithms.datastructures.sparsetable.examples;

// Sparse table for efficient minimum range queries in O(1) with O(nlogn) space
public class MinSparseTable {

  // Example usage:
  public static void main(String[] args) {
    // index values: 0, 1,  2, 3, 4,  5, 6
    long[] values = {1, 2, -3, 2, 4, -1, 5};
    MinSparseTable sparseTable = new MinSparseTable(values);

    System.out.println(sparseTable.queryMin(1, 5)); // prints -3
    System.out.println(sparseTable.queryMinIndex(1, 5)); // prints 2

    System.out.println(sparseTable.queryMin(3, 3)); // prints 2
    System.out.println(sparseTable.queryMinIndex(3, 3)); // prints 3

    System.out.println(sparseTable.queryMin(3, 6)); // prints -1
    System.out.println(sparseTable.queryMinIndex(3, 6)); // prints 5
  }

  // The number of elements in the original input array.
  private int n;

  // The maximum power of 2 needed. This value is floor(log2(n))
  private int P;

  // Fast log base 2 logarithm lookup table, 1 <= i <= n
  private int[] log2;

  // The sparse table values.
  private long[][] dp;

  // Index Table (IT) associated with the values in the sparse table. This table
  // is only useful when we want to query the index of the min (or max) element
  // in the range [l, r] rather than the value itself. The index table doesn't
  // make sense for most other range query types like gcd or sum.
  private int[][] it;

  public MinSparseTable(long[] values) {
    n = values.length;
    P = (int) (Math.log(n) / Math.log(2));
    dp = new long[P + 1][n];
    it = new int[P + 1][n];

    for (int i = 0; i < n; i++) {
      dp[0][i] = values[i];
      it[0][i] = i;
    }

    log2 = new int[n + 1];
    for (int i = 2; i <= n; i++) {
      log2[i] = log2[i / 2] + 1;
    }

    // Build sparse table combining the values of the previous intervals.
    for (int p = 1; p <= P; p++) {
      for (int i = 0; i + (1 << p) <= n; i++) {
        long leftInterval = dp[p - 1][i];
        long rightInterval = dp[p - 1][i + (1 << (p - 1))];
        dp[p][i] = Math.min(leftInterval, rightInterval);

        // Propagate the index of the best value
        if (leftInterval <= rightInterval) {
          it[p][i] = it[p - 1][i];
        } else {
          it[p][i] = it[p - 1][i + (1 << (p - 1))];
        }
      }
    }
  }

  // Do a min query on the interval [l, r] in O(1).
  //
  // We can get O(1) query by finding the smallest power of 2 that fits within
  // the interval length which we'll call k. Then we can query the intervals
  // [l, l+k] and [r-k+1, r] (which likely overlap) and apply the function
  // again. Some functions (like min and max) don't care about overlapping
  // intervals so this trick works, but for a function like sum this would
  // return the wrong result since it is not an idempotent binary function
  // (aka an overlap friendly function).
  private long queryMin(int l, int r) {
    int length = r - l + 1;
    int p = log2[length];
    int k = 1 << p; // 2 to the power of p
    return Math.min(dp[p][l], dp[p][r - k + 1]);
  }

  // Returns the index of the minimum element in the range [l, r].
  public int queryMinIndex(int l, int r) {
    int length = r - l + 1;
    int p = log2[length];
    int k = 1 << p; // 2 to the power of p
    long leftInterval = dp[p][l];
    long rightInterval = dp[p][r - k + 1];
    if (leftInterval <= rightInterval) {
      return it[p][l];
    } else {
      return it[p][r - k + 1];
    }
  }
}


text:
window.prepareTerrain = function() {
    var terrain = new BABYLON.TerrainMaterial("terrain", scene);
    terrain.specularColor = new BABYLON.Color3(0.5, 0.5, 0.5);
    terrain.specularPower = 64;
    terrain.mixTexture = new BABYLON.Texture("textures/mixMap.png", scene);
    terrain.diffuseTexture1 = new BABYLON.Texture("textures/floor.png", scene);
    terrain.diffuseTexture2 = new BABYLON.Texture("textures/rock.png", scene);
    terrain.diffuseTexture3 = new BABYLON.Texture("textures/grass.png", scene);

    terrain.bumpTexture1 = new BABYLON.Texture("textures/floor_bump.png", scene);
    terrain.bumpTexture2 = new BABYLON.Texture("textures/rockn.png", scene);
    terrain.bumpTexture3 = new BABYLON.Texture("textures/grassn.png", scene);

    terrain.diffuseTexture1.uScale = terrain.diffuseTexture1.vScale = 10;
    terrain.diffuseTexture2.uScale = terrain.diffuseTexture2.vScale = 10;
    terrain.diffuseTexture3.uScale = terrain.diffuseTexture3.vScale = 10;

    return terrain;
};


text:
Threads
=======

.. _threaduml:

Thread
------

The Thread class is a subclass of threading.Thread that implements the convenience constructor suggested by Alan Downey in the `Little Book of Semaphores`. It really just sets it to daemonic and calls `start()` automatically.

.. uml::

   Thread --|> threading.Thread
   Thread: MethodType t


text:
Rails Tips
==========

Rails Tips are random things we come by while riding Rails and like to share with the world.

## Contents

/tests/
  - Guard with Spork for RSpec, Cucumber and Test::Unit (guard_spork.md)

## Contributing
Feel free to contribute any cool tip you have. Please make sure your tip works in a default Rails 4 environment, unless otherwise specified.


text:
package de.danoeh.antennapod.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import androidx.appcompat.app.AlertDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.event.UnreadItemsUpdateEvent;
import de.danoeh.antennapod.core.feed.SubscriptionsFilter;
import de.danoeh.antennapod.core.feed.SubscriptionsFilterGroup;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.ui.common.RecursiveRadioGroup;

public class SubscriptionsFilterDialog {
    public static void showDialog(Context context) {
        SubscriptionsFilter subscriptionsFilter = UserPreferences.getSubscriptionsFilter();
        final Set<String> filterValues = new HashSet<>(Arrays.asList(subscriptionsFilter.getValues()));
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getString(R.string.pref_filter_feed_title));

        LayoutInflater inflater = LayoutInflater.from(context);
        View layout = inflater.inflate(R.layout.filter_dialog, null, false);
        LinearLayout rows = layout.findViewById(R.id.filter_rows);
        builder.setView(layout);

        for (SubscriptionsFilterGroup item : SubscriptionsFilterGroup.values()) {
            RecursiveRadioGroup row = (RecursiveRadioGroup) inflater.inflate(R.layout.filter_dialog_row, null);
            RadioButton filter1 = row.findViewById(R.id.filter_dialog_radioButton1);
            RadioButton filter2 = row.findViewById(R.id.filter_dialog_radioButton2);
            filter1.setText(item.values[0].displayName);
            filter1.setTag(item.values[0].filterId);
            if (item.values.length == 2) {
                filter2.setText(item.values[1].displayName);
                filter2.setTag(item.values[1].filterId);
            } else {
                filter2.setVisibility(View.GONE);
            }
            rows.addView(row);
        }

        for (String filterId : filterValues) {
            if (!TextUtils.isEmpty(filterId)) {
                ((RadioButton) layout.findViewWithTag(filterId)).setChecked(true);
            }
        }

        builder.setPositiveButton(R.string.confirm_label, (dialog, which) -> {
            filterValues.clear();
            for (int i = 0; i < rows.getChildCount(); i++) {
                if (!(rows.getChildAt(i) instanceof RecursiveRadioGroup)) {
                    continue;
                }
                RecursiveRadioGroup group = (RecursiveRadioGroup) rows.getChildAt(i);
                if (group.getCheckedButton() != null) {
                    String tag = (String) group.getCheckedButton().getTag();
                    if (tag != null) { // Clear buttons use no tag
                        filterValues.add((String) group.getCheckedButton().getTag());
                    }
                }
            }
            updateFilter(filterValues);
        });
        builder.setNegativeButton(R.string.cancel_label, null);
        builder.show();
    }

    private static void updateFilter(Set<String> filterValues) {
        SubscriptionsFilter subscriptionsFilter = new SubscriptionsFilter(filterValues.toArray(new String[0]));
        UserPreferences.setSubscriptionsFilter(subscriptionsFilter);
        EventBus.getDefault().post(new UnreadItemsUpdateEvent());
    }
}


text:
const PreloginPayload = require('../../src/prelogin-payload');
const assert = require('chai').assert;

function assertPayload(payload, encryptionString) {
  assert.strictEqual(payload.version.major, 0);
  assert.strictEqual(payload.version.minor, 0);
  assert.strictEqual(payload.version.patch, 0);
  assert.strictEqual(payload.version.trivial, 1);
  assert.strictEqual(payload.version.subbuild, 1);

  assert.strictEqual(payload.encryptionString, encryptionString);
  assert.strictEqual(payload.instance, 0);
  assert.strictEqual(payload.threadId, 0);
  assert.strictEqual(payload.marsString, 'OFF');
  assert.strictEqual(payload.fedAuthRequired, 1);
}

describe('prelogin-payload-assert', function() {
  it('should not encrypt', function() {
    const payload = new PreloginPayload();
    assertPayload(payload, 'NOT_SUP');
  });

  it('should encrypt', function() {
    const payload = new PreloginPayload({ encrypt: true });
    assertPayload(payload, 'ON');
  });

  it('should create from buffer', function() {
    const payload = new PreloginPayload();
    new PreloginPayload(payload.data);
    assertPayload(payload, 'NOT_SUP');
  });
});


text:
<resources>

    <string name="app_name">Share n Ride</string>

    <!-- Home Exit Notification -->
    <string name="home_exit">EXIT</string>
    <string name="home_confirm_exit">Confirm exit?</string>
    <string name="home_cancel">Cancel</string>
    <string name="home_close">Close</string>

    <string name="facebook_app_id">1143272665731321</string>

    <string name="email_empty">Please insert email</string>
    <string name="password_empty">Please insert password</string>
    <string name="student_id_empty">Please insert password</string>
    <string name="phone_empty">Please insert password</string>

    <string-array name="smoker">
        <item>Yes</item>
        <item>No</item>
    </string-array>

    <string-array name="car">
        <item>alza</item>
        <item>axia</item>
        <item>cezza</item>
        <item>iris</item>
        <item>kancil</item>
        <item>kenari</item>
        <item>myvi</item>
        <item>pesona</item>
        <item>saga</item>
    </string-array>

    <!-- State -->
    <string-array name="state">
        <item>Perak</item>
        <item>Pahang</item>
        <item>Johor</item>
        <item>Kedah</item>
        <item>Penang</item>
        <item>Selangor</item>
        <item>Melaka</item>
        <item>Terengganu</item>
        <item>Kelantan</item>
        <item>Kuala Lumpur</item>
        <item>Negeri Sembilan</item>
        <item>Sabah</item>
        <item>Sarawak</item>
        <item>Perlis</item>
        <item>Labuan</item>
    </string-array>
</resources>


text:
#include <unordered_set>

#include "Control/Control.h"
#include "Control/ControlRegistry.h"
#include "Core/Transformer/ControlRegistryTransformer.h"
#include "Core/Transformer/TransformerUtils.h"

namespace multiAgentExperience {
namespace library {
namespace core {
namespace transformer {

static bool isValidControlType(const multiAgentExperience::control::ControlType type) {
    return type == multiAgentExperience::control::ControlType::STOP;
}

ControlRegistryTransformer::ControlRegistryTransformer(std::shared_ptr<control::ControlRegistry> controlRegistry) :
        m_controlRegistry{controlRegistry} {
}

void ControlRegistryTransformer::update(std::set<std::shared_ptr<multiAgentExperience::control::Control>> controls) {
    std::unordered_set<std::shared_ptr<library::control::Control>> transformedControls;

    for (const auto& externalControl : controls) {
        if (isValidControlType(externalControl->type)) {
            auto convertedControlType = TransformerUtils::convertControlTypeToControlName(externalControl->type);
            auto control = library::control::Control::create(
                convertedControlType, [externalControl]() { externalControl->task(); });
            transformedControls.insert(control);
        }
    }

    m_controlRegistry->update(transformedControls);
}

}  // namespace transformer
}  // namespace core
}  // namespace library
}  // namespace multiAgentExperience


text:
package main

import (
	"log"
	"os"
	"runtime"

	"github.com/promisedlandt/dom4tools/command"

	"github.com/mitchellh/cli"
	"github.com/mitchellh/go-homedir"
	"gopkg.in/alecthomas/kingpin.v2"
)

var CurrentRunContext command.RunContext

var Ui cli.Ui

const (
	ErrorPrefix  = "!!!: "
	AskPrefix    = "???: "
	OutputPrefix = "d4t: "
)

func main() {
	var useBasicUi bool
	var completionMode bool // for use in autocompletion scripts, don't execute commands
	colorizeUi := true
	args := os.Args

	if len(args) > 1 {
		if args[1] == "cd" {
			useBasicUi = true
			colorizeUi = false
		}
	}

	for i, arg := range args {
		if arg == "--bash-completion" {
			useBasicUi = true
			colorizeUi = false
			completionMode = true

			args = append(args[:i], args[i+1:]...)
			break
		}
	}

	for i, arg := range args {
		if arg == "--simple-output" {
			useBasicUi = true
			colorizeUi = false

			args = append(args[:i], args[i+1:]...)
			break
		}
	}

	if useBasicUi {
		Ui = &cli.BasicUi{Writer: os.Stdout}
	} else {
		Ui = &cli.PrefixedUi{
			AskPrefix:    AskPrefix,
			OutputPrefix: OutputPrefix,
			InfoPrefix:   OutputPrefix,
			ErrorPrefix:  ErrorPrefix,
			Ui:           &cli.BasicUi{Writer: os.Stdout},
		}
	}

	// TODO: check if exists
	CurrentRunContext.BasePath = defaultDominions4BasePath()
	CurrentRunContext.BaseConfigurationPath = defaultDominions4BaseConfigurationPath()
	CurrentRunContext.DownloadsDirectory = defaultDownloadsDirectory()

	meta := command.Meta{
		Ui:             Ui,
		RunContext:     &CurrentRunContext,
		Color:          colorizeUi,
		CompletionOnly: completionMode,
	}

	args, err := meta.Process(args[1:])

	if err != nil {
		meta.Ui.Error(err.Error())
		os.Exit(1)
	}

	exitStatus := 0
	var commandNames []string

	app := kingpin.New("d4t", "Manage your Dominions 4 games from the command line.")
	commandNames = append(commandNames, command.ConfigureCdCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureListCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureCreateCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureBackupCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureRestoreCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureReplayCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureSubmitCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureResubmitCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureGetCommand(app, &meta))
	commandNames = append(commandNames, command.ConfigureVersionCommand(app, &meta, Version, VersionPrerelease, GitCommit))

	// Show the names of the subcommands but execute no commands
	if completionMode && len(args) == 0 {
		for _, commandName := range commandNames {
			meta.Ui.Output(commandName)
		}
		os.Exit(0)
	}

	_, err = app.Parse(args)

	if err != nil {
		if len(err.Error()) > 0 {
			meta.Ui.Error(err.Error())
		}
		exitStatus = 1
	}

	os.Exit(exitStatus)
}

// Path to the directory where downloaded files are stored by default
func defaultDownloadsDirectory() (downloadsDirectory string) {
	if runtime.GOOS == "windows" {
		downloadsDirectory = os.ExpandEnv("${USERPROFILE}\\Downloads")
	} else {
		base, err := homedir.Expand("~/Downloads")
		if err != nil {
			log.Fatal(err)
		}
		downloadsDirectory = base
	}

	return
}

// Path to the default dom4tools configuration file
func defaultDominions4BaseConfigurationPath() (configurationPath string) {
	if runtime.GOOS == "windows" {
		configurationPath = os.ExpandEnv("${LOCALAPPDATA}\\dom4tools\\config.json")
	} else {
		base, err := homedir.Expand("~/.dom4tools/config.json")
		if err != nil {
			log.Fatal(err)
		}
		configurationPath = base
	}

	return
}

// Path to the default Dominions 4 data directory
func defaultDominions4BasePath() (basePath string) {
	if runtime.GOOS == "windows" {
		basePath = os.ExpandEnv("${APPDATA}\\Dominions4")
	} else {
		base, err := homedir.Expand("~/dominions4")
		if err != nil {
			log.Fatal(err)
		}
		basePath = base
	}

	return
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_KEY_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_KEY_H_

#include <memory>
#include <utility>

#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-shared.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"

namespace blink {

// An IndexedDB primary or index key.
//
// The IndexedDB backing store regards script values written as object store
// record values as fairly opaque data (see IDBValue and IDBValueWrapping).
// However, it needs a fair amount of visibility into script values used as
// primary keys and index keys. For this reason, keys are represented using a
// dedicated data type that fully exposes its contents to the backing store.
class MODULES_EXPORT IDBKey {
  USING_FAST_MALLOC(IDBKey);

 public:
  typedef Vector<std::unique_ptr<IDBKey>> KeyArray;

  static std::unique_ptr<IDBKey> CreateInvalid() {
    return base::WrapUnique(new IDBKey());
  }

  static std::unique_ptr<IDBKey> CreateNone() {
    return base::WrapUnique(new IDBKey(mojom::IDBKeyType::None));
  }

  static std::unique_ptr<IDBKey> CreateNumber(double number) {
    return base::WrapUnique(new IDBKey(mojom::IDBKeyType::Number, number));
  }

  static std::unique_ptr<IDBKey> CreateBinary(
      scoped_refptr<SharedBuffer> binary) {
    return base::WrapUnique(new IDBKey(std::move(binary)));
  }

  static std::unique_ptr<IDBKey> CreateString(const String& string) {
    return base::WrapUnique(new IDBKey(string));
  }

  static std::unique_ptr<IDBKey> CreateDate(double date) {
    return base::WrapUnique(new IDBKey(mojom::IDBKeyType::Date, date));
  }

  static std::unique_ptr<IDBKey> CreateArray(KeyArray array) {
    return base::WrapUnique(new IDBKey(std::move(array)));
  }

  static std::unique_ptr<IDBKey> Clone(const std::unique_ptr<IDBKey>& rkey_in) {
    return IDBKey::Clone(rkey_in.get());
  }

  static std::unique_ptr<IDBKey> Clone(const IDBKey* rkey);

  ~IDBKey();

  mojom::IDBKeyType GetType() const { return type_; }
  bool IsValid() const;

  const KeyArray& Array() const {
    DCHECK_EQ(type_, mojom::IDBKeyType::Array);
    return array_;
  }

  scoped_refptr<SharedBuffer> Binary() const {
    DCHECK_EQ(type_, mojom::IDBKeyType::Binary);
    return binary_;
  }

  const String& GetString() const {
    DCHECK_EQ(type_, mojom::IDBKeyType::String);
    return string_;
  }

  double Date() const {
    DCHECK_EQ(type_, mojom::IDBKeyType::Date);
    return number_;
  }

  double Number() const {
    DCHECK_EQ(type_, mojom::IDBKeyType::Number);
    return number_;
  }

  int Compare(const IDBKey* other) const;
  bool IsLessThan(const IDBKey* other) const;
  bool IsEqual(const IDBKey* other) const;
  size_t SizeEstimate() const { return size_estimate_; }

  // Returns a new key array with invalid keys and duplicates removed.
  //
  // The items in the key array are moved out of the given IDBKey, which must be
  // an array. For this reason, the method is a static method that receives its
  // argument via an std::unique_ptr.
  //
  // The return value will be pasesd to the backing store, which requires
  // Web types. Returning the correct types directly avoids copying later on
  // (wasted CPU cycles and code size).
  static Vector<std::unique_ptr<IDBKey>> ToMultiEntryArray(
      std::unique_ptr<IDBKey> array_key);

 private:
  DISALLOW_COPY_AND_ASSIGN(IDBKey);

  IDBKey();
  IDBKey(mojom::IDBKeyType type);
  IDBKey(mojom::IDBKeyType type, double number);
  explicit IDBKey(const String& value);
  explicit IDBKey(scoped_refptr<SharedBuffer> value);
  explicit IDBKey(KeyArray key_array);

  mojom::IDBKeyType type_;
  KeyArray array_;
  scoped_refptr<SharedBuffer> binary_;
  const String string_;
  const double number_ = 0;

  // Initialized in IDBKey constructors based on key type and value size (see
  // idb_key.cc).  Returned via SizeEstimate() and used in IndexedDB code to
  // verify that a given key is small enough to pass over IPC.
  size_t size_estimate_;
};

// An index id, and corresponding set of keys to insert.
struct IDBIndexKeys {
  int64_t id;
  Vector<std::unique_ptr<IDBKey>> keys;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_KEY_H_


text:
/*
 * REVISION HISTORY:
 *
 * Date          Author(s)
 * CR            Headline
 * ============  ==============================================================
 * Mar 02, 2005  Luiz Felipe Guimaraes
 * 11            Implement DMT Use Cases
 * ============  ==============================================================
 */

package org.osgi.test.cases.dmt.tc3.tbc.DataPlugin.TransactionalDataSession;

import org.osgi.service.dmt.DmtData;
import org.osgi.service.dmt.DmtException;
import org.osgi.service.dmt.DmtSession;
import org.osgi.test.cases.dmt.tc3.tbc.DmtConstants;
import org.osgi.test.cases.dmt.tc3.tbc.DmtTestControl;
import org.osgi.test.cases.dmt.tc3.tbc.DataPlugin.TestDataPlugin;
import org.osgi.test.cases.dmt.tc3.tbc.DataPlugin.TestDataPluginActivator;
import org.osgi.test.support.compatibility.DefaultTestBundleControl;

import junit.framework.TestCase;

/**
 * @author Luiz Felipe Guimaraes
 *
 * This test case validates the implementation of setNodeValue method,
 * according to MEG specification
 */
public class SetNodeValue {

	private DmtTestControl tbc;

	public SetNodeValue(DmtTestControl tbc) {
		this.tbc = tbc;
	}

	public void run() {
		testSetNodeValue001();
		testSetNodeValue002();
	}

	/**
	 * Asserts that DmtAdmin correctly forwards the call of setNodeValue
	 * to the correct plugin.
	 *
	 * @spec ReadWriteDataSession.setNodeValue(String[],DmtData)
	 */
	public void testSetNodeValue001() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testSetNodeValue001");
			session = tbc.getDmtAdmin().getSession(TestDataPluginActivator.ROOT,
					DmtSession.LOCK_TYPE_ATOMIC);
			DmtData data = new DmtData("test");
			session.setNodeValue(TestDataPluginActivator.LEAF_NODE, data);
			TestCase.assertEquals("Asserts that DmtAdmin fowarded "+ TestDataPlugin.SETNODEVALUE+" to the correct plugin",TestDataPlugin.SETNODEVALUE,DmtConstants.TEMPORARY);
			TestCase.assertEquals("Asserts that DmtAdmin the parameter was fowarded to the correct plugin without modification",data.toString(),DmtConstants.PARAMETER_2);
		} catch (Exception e) {
			DmtTestControl.failUnexpectedException(e);
		} finally {
			tbc.cleanUp(session,true);
		}
	}

	/**
	 * Asserts that DmtAdmin correctly forwards the DmtException thrown by the plugin
	 *
	 * @spec ReadWriteDataSession.setNodeValue(String[],DmtData)
	 */
	public void testSetNodeValue002() {
		DmtSession session = null;
		try {
			DefaultTestBundleControl.log("#testSetNodeValue002");
			session = tbc.getDmtAdmin().getSession(TestDataPluginActivator.ROOT,
					DmtSession.LOCK_TYPE_ATOMIC);
			session.setNodeValue(TestDataPluginActivator.LEAF_NODE_EXCEPTION,new DmtData("test"));
			DefaultTestBundleControl.failException("#", DmtException.class);
		} catch (DmtException e) {
			TestCase.assertEquals("Asserts that DmtAdmin fowarded the DmtException with the correct subtree: ", TestDataPluginActivator.LEAF_NODE_EXCEPTION, e
					.getURI());
			TestCase.assertEquals("Asserts that DmtAdmin fowarded the DmtException with the correct code: ", DmtException.CONCURRENT_ACCESS, e
					.getCode());
			TestCase.assertTrue("Asserts that DmtAdmin fowarded the DmtException with the correct message. ", e
					.getMessage().indexOf(TestDataPlugin.SETNODEVALUE)>-1);
		} catch (Exception e) {
			DmtTestControl.failExpectedOtherException(DmtException.class, e);
		} finally {
			tbc.cleanUp(session,true);
		}
	}
}


text:
{% extends "base.html" %}

{% load static from staticfiles %}
{% load bootstrap %}
{% load thread_tags %}
{% block headers %}
<link type="text/css" rel="stylesheet" href="{% static 'ui/css/announcements.css' %}" />

{% endblock %}

{% block content %}
{% if can_edit %}
<form action="{% url 'managers:edit_announcement' announcement_pk=announcement.pk %}" class="pull-right">
    <button class="btn btn btn-primary"> Edit</button>
</form>
{% endif %}

{{ page_name }}

    {{ announcement.manager }}
    ({{ announcement.incumbent|display_user:user }}), {{ announcement.post_date }}:

{{ announcement.body|safe }}
  {% if announcement.incumbent.user = user or user.is_superuser %}
    <form class="pull-right" method="post" action="">
      {% csrf_token %}
      {{ unpin_form }}
      {% if announcement.pinned %}
      <button type="submit" class="main_link warning_link" name="unpin" title="Unpin from homepage">Unpin</button>
      {% else %}
      <button type="submit" class="main_link success_link" name="unpin" title="Pin to homepage">Pin</button>
      {% endif %}
    </form>
    <form class="pull-right" action="{% url 'managers:edit_announcement' announcement_pk=announcement.pk %}">
        <button type="submit" class="main_link primary_link" title="Edit this announcement">Edit</button>
    </form>
{% endif %}

{% endblock %}


text:
package interfaces

import (
	"net/http"

	"code.google.com/p/go.net/context"

	"github.com/janicduplessis/projectgo/ct/usecases"
)

const (
	KeyUser string = "User"
)

type ModelResponse struct {
	Model interface{}
}

type Webservice interface {
	SendJson(w http.ResponseWriter, obj interface{})
	ReadJson(w http.ResponseWriter, r *http.Request, obj interface{}) error
	Redirect(w http.ResponseWriter, r *http.Request, url string)
	Log(msg string)
	Error(w http.ResponseWriter, err error)
	StartSession(ctx context.Context, w http.ResponseWriter, r *http.Request, user *usecases.User) error
	EndSession(ctx context.Context, w http.ResponseWriter, r *http.Request) error
	AddHandler(url string, authenticated bool, fn func(context.Context, http.ResponseWriter, *http.Request))
}


text:
Devoluções

                <input type="hidden" name="captcha">

                <form class="form-horizontal" <?php echo form_open_multipart('emprestimos/devolucao_recibo'); ?>

                    Acervo

                        <input type="text" class="form-control" placeholder="Informe o numero ou pesquise pelo nome" id="id_tombo" name="id_tombo">

                      <button type="button"id="abrir_devolucao" class="btn btn-info btn-flat"></button>

                    <button type="submit" class="btn bg-green  btn-lg btn-flat btn-block" name="devolver" id="devolver"  value="devolver"  >DEVOLVER</button>

                    <input type="text"  class="form-control" id="titulo"  name="titulo"  readonly="true">
                    <input type="text"  class="form-control" id="idaluno"  name="idaluno"  readonly="true">
                    <input type="text"  class="form-control" id="datadevolucaoreal"  name="datadevolucaoreal"  readonly="true">

                </form>

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Pesquisa no Acervo

                                Pesquisa Nome

                                    <input type="text"  class="form-control"  name="pesquisar_tombo" required="required" value="">

                                    <button type="button" class="btn btn-primary  btn-sm" id="buscar_emprestimo" >Pesquisa</button>

                                <img style="margin-left: 33%" src="<?php echo base_url('assets/img/ajax-loader.gif')?>"  alt="">


text:
const {set, cd, sed, rm} = require('shelljs');
const path = require('path');
const log = console.log;

log('===== about to run the postinstall-patches.js script     =====');
// fail on first error
set('-e');
// print commands as being executed
set('-v');
// jump to project root
cd(path.join(__dirname, '../'));

/* EXAMPLE PATCH:
// https://github.com/ReactiveX/rxjs/pull/3302
// make node_modules/rxjs compilable with Typescript 2.7
// remove when we update to rxjs v6
log('\n# patch: reactivex/rxjs#3302 make node_modules/rxjs compilable with Typescript 2.7');
sed('-i', '(\'response\' in xhr)', '(\'response\' in (xhr as any))',
    'node_modules/rxjs/src/observable/dom/AjaxObservable.ts');
*/

// fixes rxjs bazel build: https://github.com/ReactiveX/rxjs/pull/3454
sed('-i', /^  srcs = glob.*/,
    'srcs = glob(["*.ts", "**/*.ts"], exclude = ["internal/Rx.ts", "internal-compatibility/**",  "internal/patching/**", "umd.ts"]),',
    'node_modules/rxjs/src/BUILD.bazel');

log('===== finished running the postinstall-patches.js script =====');


text:
<?php
/**
 * OcExtension
 *
 * --- BEGIN ModelDoc ---
 *
 * Table {{extension}}
 * @property integer $extension_id
 * @property string $type
 * @property string $code
 *
 * @see \CActiveRecord
 * @method \OcExtension find($condition = '', array $params = array())
 * @method \OcExtension findByPk($pk, $condition = '', array $params = array())
 * @method \OcExtension findByAttributes(array $attributes, $condition = '', array $params = array())
 * @method \OcExtension findBySql($sql, array $params = array())
 * @method \OcExtension[] findAll($condition = '', array $params = array())
 * @method \OcExtension[] findAllByPk($pk, $condition = '', array $params = array())
 * @method \OcExtension[] findAllByAttributes(array $attributes, $condition = '', array $params = array())
 * @method \OcExtension[] findAllBySql($sql, array $params = array())
 * @method \OcExtension with()
 * @method \OcExtension together()
 * @method \OcExtension cache($duration, $dependency = null, $queryCount = 1)
 * @method \OcExtension resetScope($resetDefault = true)
 * @method \OcExtension populateRecord($attributes, $callAfterFind = true)
 * @method \OcExtension[] populateRecords($data, $callAfterFind = true, $index = null)
 *
 * --- END ModelDoc ---
 */

class OcExtension extends CActiveRecord
{

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return OcExtension the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{extension}}';
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'extension_id' => Yii::t('app', 'Extension'),
            'type' => Yii::t('app', 'Type'),
            'code' => Yii::t('app', 'Code'),
        );
    }

}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import ReactRouter from 'react-router';

export default class FacebookSocialPage extends React.Component {

	render() {

		let styleVal = {

			border: "none",
			overflow: "hidden"
		};

		return (

			<iframe
				src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2Fvizjust&tabs=timeline&width=340&height=500&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true&appId=1750136755257522"
				width="340" height="500"
				style={ styleVal }
				scrolling="no" frameborder="0" allowTransparency="true">
			</iframe>

		)

	}

}