text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////

#include "IResearchViewNode.h"

#include "Aql/Ast.h"
#include "Aql/Collection.h"
#include "Aql/Condition.h"
#include "Aql/ExecutionBlockImpl.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/ExecutionPlan.h"
#include "Aql/IResearchViewExecutor.h"
#include "Aql/NoResultsExecutor.h"
#include "Aql/Query.h"
#include "Aql/SingleRowFetcher.h"
#include "Aql/SortCondition.h"
#include "Aql/types.h"
#include "Basics/NumberUtils.h"
#include "Basics/StringUtils.h"
#include "Cluster/ClusterFeature.h"
#include "Cluster/ClusterInfo.h"
#include "IResearch/AqlHelper.h"
#include "IResearch/IResearchCommon.h"
#include "IResearch/IResearchView.h"
#include "IResearch/IResearchViewCoordinator.h"
#include "StorageEngine/TransactionState.h"
#include "Utils/CollectionNameResolver.h"
#include "VocBase/LogicalCollection.h"

#include <velocypack/Iterator.h>

namespace {

using namespace arangodb;
using namespace arangodb::iresearch;

////////////////////////////////////////////////////////////////////////////////
/// @brief surrogate root for all queries without a filter
////////////////////////////////////////////////////////////////////////////////
aql::AstNode const ALL(aql::AstNodeValue(true));

inline bool filterConditionIsEmpty(aql::AstNode const* filterCondition) {
  return filterCondition == &ALL;
}

// -----------------------------------------------------------------------------
// --SECTION--       helpers for std::vector<arangodb::iresearch::IResearchSort>
// -----------------------------------------------------------------------------

void toVelocyPack(velocypack::Builder& builder,
                  std::vector<Scorer> const& scorers, bool verbose) {
  VPackArrayBuilder arrayScope(&builder);
  for (auto const& scorer : scorers) {
    VPackObjectBuilder objectScope(&builder);
    builder.add("id", VPackValue(scorer.var->id));
    builder.add("name", VPackValue(scorer.var->name));  // for explainer.js
    builder.add(VPackValue("node"));
    scorer.node->toVelocyPack(builder, verbose);
  }
}

std::vector<Scorer> fromVelocyPack(aql::ExecutionPlan& plan, velocypack::Slice const& slice) {
  if (!slice.isArray()) {
    LOG_TOPIC("b50b2", ERR, arangodb::iresearch::TOPIC)
        << "invalid json format detected while building IResearchViewNode "
           "sorting from velocy pack, array expected";
    return {};
  }

  auto* ast = plan.getAst();
  TRI_ASSERT(ast);
  auto const* vars = plan.getAst()->variables();
  TRI_ASSERT(vars);

  std::vector<Scorer> scorers;

  size_t i = 0;
  for (auto const sortSlice : velocypack::ArrayIterator(slice)) {
    auto const varIdSlice = sortSlice.get("id");

    if (!varIdSlice.isNumber()) {
      LOG_TOPIC("c3790", ERR, arangodb::iresearch::TOPIC)
          << "malformed variable identifier at line '" << i << "', number expected";
      return {};
    }

    auto const varId = varIdSlice.getNumber<aql::VariableId>();
    auto const* var = vars->getVariable(varId);

    if (!var) {
      LOG_TOPIC("4eeb9", ERR, arangodb::iresearch::TOPIC)
          << "unable to find variable '" << varId << "' at line '" << i
          << "' while building IResearchViewNode sorting from velocy pack";
      return {};
    }

    // will be owned by Ast
    auto* node = new aql::AstNode(ast, sortSlice.get("node"));

    scorers.emplace_back(var, node);
    ++i;
  }

  return scorers;
}

// -----------------------------------------------------------------------------
// --SECTION--                            helpers for IResearchViewNode::Options
// -----------------------------------------------------------------------------

void toVelocyPack(velocypack::Builder& builder, IResearchViewNode::Options const& options) {
  VPackObjectBuilder objectScope(&builder);
  builder.add("waitForSync", VPackValue(options.forceSync));

  if (!options.restrictSources) {
    builder.add("collections", VPackValue(VPackValueType::Null));
  } else {
    VPackArrayBuilder arrayScope(&builder, "collections");
    for (auto const cid : options.sources) {
      builder.add(VPackValue(cid));
    }
  }
}

bool fromVelocyPack(velocypack::Slice optionsSlice, IResearchViewNode::Options& options) {
  if (optionsSlice.isNone()) {
    // no options specified
    return true;
  }

  if (!optionsSlice.isObject()) {
    return false;
  }

  // forceSync
  {
    auto const optionSlice = optionsSlice.get("waitForSync");

    if (!optionSlice.isNone()) {
      // 'waitForSync' is optional
      if (!optionSlice.isBool()) {
        return false;
      }

      options.forceSync = optionSlice.getBool();
    }
  }

  // collections
  {
    auto const optionSlice = optionsSlice.get("collections");

    if (!optionSlice.isNone() && !optionSlice.isNull()) {
      if (!optionSlice.isArray()) {
        return false;
      }

      for (auto idSlice : VPackArrayIterator(optionSlice)) {
        if (!idSlice.isNumber()) {
          return false;
        }

        auto const cid = idSlice.getNumber<TRI_voc_cid_t>();

        if (!cid) {
          return false;
        }

        options.sources.insert(cid);
      }

      options.restrictSources = true;
    }
  }

  return true;
}

bool parseOptions(aql::Query& query, LogicalView const& view, aql::AstNode const* optionsNode,
                  IResearchViewNode::Options& options, std::string& error) {
  typedef bool (*OptionHandler)(aql::Query&, LogicalView const& view, aql::AstNode const&,
                                IResearchViewNode::Options&, std::string&);

  static std::map<irs::string_ref, OptionHandler> const Handlers{
      // cppcheck-suppress constStatement
      {"collections",
       [](aql::Query& query, LogicalView const& view, aql::AstNode const& value,
          IResearchViewNode::Options& options, std::string& error) {
         if (value.isNullValue()) {
           // have nothing to restrict
           return true;
         }

         if (!value.isArray()) {
           error =
               "null value or array of strings or numbers"
               " is expected for option 'collections'";
           return false;
         }

         auto& resolver = query.resolver();
         ::arangodb::containers::HashSet<TRI_voc_cid_t> sources;

         // get list of CIDs for restricted collections
         for (size_t i = 0, n = value.numMembers(); i < n; ++i) {
           auto const* sub = value.getMemberUnchecked(i);
           TRI_ASSERT(sub);

           switch (sub->value.type) {
             case aql::VALUE_TYPE_INT: {
               sources.insert(TRI_voc_cid_t(sub->getIntValue(true)));
               break;
             }

             case aql::VALUE_TYPE_STRING: {
               auto name = sub->getString();

               auto collection = resolver.getCollection(name);

               if (!collection) {
                 // check if TRI_voc_cid_t is passed as string
                 auto const cid =
                     NumberUtils::atoi_zero<TRI_voc_cid_t>(name.data(),
                                                           name.data() + name.size());

                 collection = resolver.getCollection(cid);

                 if (!collection) {
                   error = "invalid data source name '" + name +
                           "' while parsing option 'collections'";
                   return false;
                 }
               }

               sources.insert(collection->id());
               break;
             }

             default: {
               error =
                   "null value or array of strings or numbers"
                   " is expected for option 'collections'";
               return false;
             }
           }
         }

         // check if CIDs are valid
         size_t sourcesFound = 0;
         auto checkCids = [&sources, &sourcesFound](TRI_voc_cid_t cid) {
           sourcesFound += size_t(sources.contains(cid));
           return true;
         };
         view.visitCollections(checkCids);

         if (sourcesFound != sources.size()) {
           error = "only " + basics::StringUtils::itoa(sourcesFound) +
                   " out of " + basics::StringUtils::itoa(sources.size()) +
                   " provided collection(s) in option 'collections' are "
                   "registered with the view '" +
                   view.name() + "'";
           return false;
         }

         // parsing is done
         options.sources = std::move(sources);
         options.restrictSources = true;

         return true;
       }},
      // cppcheck-suppress constStatement
      {"waitForSync", [](aql::Query& /*query*/, LogicalView const& /*view*/,
                         aql::AstNode const& value,
                         IResearchViewNode::Options& options, std::string& error) {
         if (!value.isValueType(aql::VALUE_TYPE_BOOL)) {
           error = "boolean value expected for option 'waitForSync'";
           return false;
         }

         options.forceSync = value.getBoolValue();
         return true;
       }}};

  if (!optionsNode) {
    // nothing to parse
    return true;
  }

  if (aql::NODE_TYPE_OBJECT != optionsNode->type) {
    // must be an object
    return false;
  }

  const size_t n = optionsNode->numMembers();

  for (size_t i = 0; i < n; ++i) {
    auto const* attribute = optionsNode->getMemberUnchecked(i);

    if (!attribute || attribute->type != aql::NODE_TYPE_OBJECT_ELEMENT ||
        !attribute->isValueType(aql::VALUE_TYPE_STRING) || !attribute->numMembers()) {
      // invalid or malformed node detected
      return false;
    }

    irs::string_ref const attributeName(attribute->getStringValue(),
                                        attribute->getStringLength());

    auto const handler = Handlers.find(attributeName);

    if (handler == Handlers.end()) {
      // no handler found for attribute
      continue;
    }

    auto const* value = attribute->getMemberUnchecked(0);

    if (!value) {
      // can't handle attribute
      return false;
    }

    if (!value->isConstant()) {
      // 'Ast::injectBindParameters` doesn't handle
      // constness of parent nodes correctly, re-evaluate flags
      value->removeFlag(aql::DETERMINED_CONSTANT);

      if (!value->isConstant()) {
        // can't handle non-const values in options
        return false;
      }
    }

    if (!handler->second(query, view, *value, options, error)) {
      // can't handle attribute
      return false;
    }
  }

  return true;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                     other helpers
// -----------------------------------------------------------------------------

// in loop or non-deterministic
bool hasDependencies(aql::ExecutionPlan const& plan, aql::AstNode const& node,
                     aql::Variable const& ref,
                     ::arangodb::containers::HashSet<aql::Variable const*>& vars) {
  vars.clear();
  aql::Ast::getReferencedVariables(&node, vars);
  vars.erase(&ref);  // remove "our" variable

  for (auto const* var : vars) {
    auto* setter = plan.getVarSetBy(var->id);

    if (!setter) {
      // unable to find setter
      continue;
    }

    if (!setter->isDeterministic()) {
      // found nondeterministic setter
      return true;
    }

    switch (setter->getType()) {
      case aql::ExecutionNode::ENUMERATE_COLLECTION:
      case aql::ExecutionNode::ENUMERATE_LIST:
      case aql::ExecutionNode::SUBQUERY:
      case aql::ExecutionNode::COLLECT:
      case aql::ExecutionNode::TRAVERSAL:
      case aql::ExecutionNode::INDEX:
      case aql::ExecutionNode::SHORTEST_PATH:
      case aql::ExecutionNode::K_SHORTEST_PATHS:
      case aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW:
        // we're in the loop with dependent context
        return true;
      default:
        break;
    }
  }

  return false;
}

/// @returns true if a given node is located inside a loop or subquery
bool isInInnerLoopOrSubquery(aql::ExecutionNode const& node) {
  auto* cur = &node;

  while (true) {
    auto const* dep = cur->getFirstDependency();

    if (!dep) {
      break;
    }

    switch (dep->getType()) {
      case aql::ExecutionNode::ENUMERATE_COLLECTION:
      case aql::ExecutionNode::INDEX:
      case aql::ExecutionNode::TRAVERSAL:
      case aql::ExecutionNode::ENUMERATE_LIST:
      case aql::ExecutionNode::SHORTEST_PATH:
      case aql::ExecutionNode::K_SHORTEST_PATHS:
      case aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW:
        // we're in a loop
        return true;
      default:
        break;
    }

    cur = dep;
  }

  TRI_ASSERT(cur);
  return cur->getType() == aql::ExecutionNode::SINGLETON &&
         cur->id() != 1;  // SIGNLETON nodes in subqueries have id != 1
}

/// negative value - value is dirty
/// _volatilityMask & 1 == volatile filter
/// _volatilityMask & 2 == volatile sort
int evaluateVolatility(IResearchViewNode const& node) {
  auto const inDependentScope = isInInnerLoopOrSubquery(node);
  auto const& plan = *node.plan();
  auto const& outVariable = node.outVariable();

  ::arangodb::containers::HashSet<aql::Variable const*> vars;
  int mask = 0;

  // evaluate filter condition volatility
  auto& filterCondition = node.filterCondition();
  if (!::filterConditionIsEmpty(&filterCondition) && inDependentScope) {
    irs::set_bit<0>(::hasDependencies(plan, filterCondition, outVariable, vars), mask);
  }

  // evaluate sort condition volatility
  auto& scorers = node.scorers();
  if (!scorers.empty() && inDependentScope) {
    vars.clear();

    for (auto const& scorer : scorers) {
      if (::hasDependencies(plan, *scorer.node, outVariable, vars)) {
        irs::set_bit<1>(mask);
        break;
      }
    }
  }

  return mask;
}

std::function<bool(TRI_voc_cid_t)> const viewIsEmpty = [](TRI_voc_cid_t) {
  return false;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief index reader implementation over multiple irs::index_reader
/// @note it is assumed that ViewState resides in the same
///       TransactionState as the IResearchView ViewState, therefore a separate
///       lock is not required to be held
////////////////////////////////////////////////////////////////////////////////
class Snapshot : public IResearchView::Snapshot, private irs::util::noncopyable {
 public:
  typedef std::vector<std::pair<TRI_voc_cid_t, irs::sub_reader const*>> readers_t;

  Snapshot(readers_t&& readers, uint64_t docs_count, uint64_t live_docs_count) NOEXCEPT
      : _readers(std::move(readers)),
        _docs_count(docs_count),
        _live_docs_count(live_docs_count) {}

  /// @brief constructs snapshot from a given snapshot
  ///        according to specified set of collections
  Snapshot(const IResearchView::Snapshot& rhs,
           ::arangodb::containers::HashSet<TRI_voc_cid_t> const& collections);

  /// @returns corresponding sub-reader
  virtual const irs::sub_reader& operator[](size_t i) const NOEXCEPT override {
    assert(i < readers_.size());
    return *(_readers[i].second);
  }

  virtual TRI_voc_cid_t cid(size_t i) const NOEXCEPT override {
    assert(i < readers_.size());
    return _readers[i].first;
  }

  /// @returns number of documents
  virtual uint64_t docs_count() const NOEXCEPT override { return _docs_count; }

  /// @returns number of live documents
  virtual uint64_t live_docs_count() const NOEXCEPT override {
    return _live_docs_count;
  }

  /// @returns total number of opened writers
  virtual size_t size() const NOEXCEPT override { return _readers.size(); }

 private:
  readers_t _readers;
  uint64_t _docs_count;
  uint64_t _live_docs_count;
};  // Snapshot

Snapshot::Snapshot(const IResearchView::Snapshot& rhs,
                   ::arangodb::containers::HashSet<TRI_voc_cid_t> const& collections)
    : _docs_count(0), _live_docs_count(0) {
  for (size_t i = 0, size = rhs.size(); i < size; ++i) {
    auto const cid = rhs.cid(i);

    if (!collections.contains(cid)) {
      continue;
    }

    auto& segment = rhs[i];

    _docs_count += segment.docs_count();
    _live_docs_count += segment.live_docs_count();
    _readers.emplace_back(cid, &segment);
  }
}

typedef std::shared_ptr<IResearchView::Snapshot const> SnapshotPtr;

/// @brief Since cluster is not transactional and each distributed
///        part of a query starts it's own trasaction associated
///        with global query identifier, there is no single place
///        to store a snapshot and we do the following:
///
///   1. Each query part on DB server gets the list of shards
///      to be included into a query and starts its own transaction
///
///   2. Given the list of shards we take view snapshot according
///      to the list of restricted data sources specified in options
///      of corresponding IResearchViewNode
///
///   3. If waitForSync is specified, we refresh snapshot
///      of each shard we need and finally put it to transaction
///      associated to a part of the distributed query. We use
///      default snapshot key if there are no restricted sources
///      specified in options or IResearchViewNode address otherwise
///
///      Custom key is needed for the following query
///      (assume 'view' is lined with 'c1' and 'c2' in the example below):
///           FOR d IN view OPTIONS { collections : [ 'c1' ] }
///           FOR x IN view OPTIONS { collections : [ 'c2' ] }
///           RETURN {d, x}
///
SnapshotPtr snapshotDBServer(IResearchViewNode const& node, transaction::Methods& trx) {
  TRI_ASSERT(ServerState::instance()->isDBServer());

  static IResearchView::SnapshotMode const SNAPSHOT[]{IResearchView::SnapshotMode::FindOrCreate,
                                                      IResearchView::SnapshotMode::SyncAndReplace};

  auto& view = LogicalView::cast<IResearchView>(*node.view());
  auto& options = node.options();
  auto* resolver = trx.resolver();
  TRI_ASSERT(resolver);

  ::arangodb::containers::HashSet<TRI_voc_cid_t> collections;
  for (auto& shard : node.shards()) {
    auto collection = resolver->getCollection(shard);

    if (!collection) {
      THROW_ARANGO_EXCEPTION(
          arangodb::Result(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND,
                           std::string("failed to find shard by id '") + shard + "'"));
    }

    if (options.restrictSources && !options.sources.contains(collection->planId())) {
      // skip restricted collections if any
      continue;
    }

    collections.emplace(collection->id());
  }

  void const* snapshotKey = nullptr;

  if (options.restrictSources) {
    // use node address as the snapshot identifier
    snapshotKey = &node;
  }

  // use aliasing ctor
  return {SnapshotPtr(), view.snapshot(trx, SNAPSHOT[size_t(options.forceSync)],
                                       &collections, snapshotKey)};
}

/// @brief Since single-server is transactional we do the following:
///
///   1. When transaction starts we put index snapshot into it
///
///   2. If waitForSync is specified, we refresh snapshot
///      taken in (1), object itself remains valid
///
///   3. If there are no restricted sources in a query, we reuse
///      snapshot taken in (1),
///      otherwise we reassemble restricted snapshot based on the
///      original one taken in (1) and return it
///
SnapshotPtr snapshotSingleServer(IResearchViewNode const& node, transaction::Methods& trx) {
  TRI_ASSERT(ServerState::instance()->isSingleServer());

  static IResearchView::SnapshotMode const SNAPSHOT[]{IResearchView::SnapshotMode::Find,
                                                      IResearchView::SnapshotMode::SyncAndReplace};

  auto& view = LogicalView::cast<IResearchView>(*node.view());
  auto& options = node.options();

  // use aliasing ctor
  auto reader = SnapshotPtr(SnapshotPtr(),
                            view.snapshot(trx, SNAPSHOT[size_t(options.forceSync)]));

  if (options.restrictSources && reader) {
    // reassemble reader
    reader = std::make_shared<Snapshot>(*reader, options.sources);
  }

  return reader;
}

const char* NODE_DATABASE_PARAM = "database";
const char* NODE_VIEW_NAME_PARAM = "view";
const char* NODE_VIEW_ID_PARAM = "viewId";
const char* NODE_OUT_VARIABLE_PARAM = "outVariable";
const char* NODE_OUT_NM_DOC_PARAM = "outNmDocId";
const char* NODE_OUT_NM_COL_PARAM = "outNmColPtr";
const char* NODE_CONDITION_PARAM = "condition";
const char* NODE_SCORERS_PARAM = "scorers";
const char* NODE_SHARDS_PARAM = "shards";
const char* NODE_OPTIONS_PARAM = "options";
const char* NODE_VOLATILITY_PARAM = "volatility";
const char* NODE_PRIMARY_SORT_PARAM = "primarySort";
const char* NODE_PRIMARY_SORT_BUCKETS_PARAM = "primarySortBuckets";

}  // namespace

namespace arangodb {
namespace iresearch {

// -----------------------------------------------------------------------------
// --SECTION--                                  IResearchViewNode implementation
// -----------------------------------------------------------------------------

IResearchViewNode::IResearchViewNode(aql::ExecutionPlan& plan, size_t id,
                                     TRI_vocbase_t& vocbase,
                                     std::shared_ptr<const LogicalView> const& view,
                                     aql::Variable const& outVariable,
                                     aql::AstNode* filterCondition,
                                     aql::AstNode* options, std::vector<Scorer>&& scorers)
    : aql::ExecutionNode(&plan, id),
      _vocbase(vocbase),
      _view(view),
      _outVariable(&outVariable),
      _outNonMaterializedDocId(nullptr),
      _outNonMaterializedColPtr(nullptr),
      // in case if filter is not specified
      // set it to surrogate 'RETURN ALL' node
      _filterCondition(filterCondition ? filterCondition : &ALL),
      _scorers(std::move(scorers)) {
  TRI_ASSERT(_view);
  TRI_ASSERT(iresearch::DATA_SOURCE_TYPE == _view->type());
  TRI_ASSERT(LogicalView::category() == _view->category());

  auto* ast = plan.getAst();
  TRI_ASSERT(ast && ast->query());

  // FIXME any other way to validate options before object creation???
  std::string error;
  if (!parseOptions(*ast->query(), *_view, options, _options, error)) {
    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
                                   "invalid ArangoSearch options provided: " + error);
  }
}

IResearchViewNode::IResearchViewNode(aql::ExecutionPlan& plan, velocypack::Slice const& base)
    : aql::ExecutionNode(&plan, base),
      _vocbase(plan.getAst()->query()->vocbase()),
      _outVariable(
          aql::Variable::varFromVPack(plan.getAst(), base, NODE_OUT_VARIABLE_PARAM)),
      _outNonMaterializedDocId(
          aql::Variable::varFromVPack(plan.getAst(), base, NODE_OUT_NM_DOC_PARAM, true)),
      _outNonMaterializedColPtr(
          aql::Variable::varFromVPack(plan.getAst(), base, NODE_OUT_NM_COL_PARAM, true)),
      // in case if filter is not specified
      // set it to surrogate 'RETURN ALL' node
      _filterCondition(&ALL),
      _scorers(fromVelocyPack(plan, base.get(NODE_SCORERS_PARAM))) {
  if ((_outNonMaterializedColPtr != nullptr) != (_outNonMaterializedDocId != nullptr)) {
    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
      std::string("invalid node config, '").append(NODE_OUT_NM_DOC_PARAM)
        .append("' attribute should be consistent with '")
        .append(NODE_OUT_NM_COL_PARAM).append("' attribute"));
  }

  // view
  auto const viewIdSlice = base.get(NODE_VIEW_ID_PARAM);

  if (!viewIdSlice.isString()) {
    THROW_ARANGO_EXCEPTION_MESSAGE(
        TRI_ERROR_BAD_PARAMETER,
        std::string("invalid vpack format, '").append(NODE_VIEW_ID_PARAM)
          .append("' attribute is intended to be a string"));
  }

  auto const viewId = viewIdSlice.copyString();

  if (ServerState::instance()->isSingleServer()) {
    _view = _vocbase.lookupView(basics::StringUtils::uint64(viewId));
  } else {
    // need cluster wide view
    TRI_ASSERT(_vocbase.server().hasFeature<ClusterFeature>());
    _view = _vocbase.server().getFeature<ClusterFeature>().clusterInfo().getView(
        _vocbase.name(), viewId);
  }

  if (!_view || iresearch::DATA_SOURCE_TYPE != _view->type()) {
    THROW_ARANGO_EXCEPTION_MESSAGE(
        TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND,
        "unable to find ArangoSearch view with id '" + viewId + "'");
  }

  // filter condition
  auto const filterSlice = base.get(NODE_CONDITION_PARAM);

  if (filterSlice.isObject() && !filterSlice.isEmptyObject()) {
    // AST will own the node
    _filterCondition = new aql::AstNode(plan.getAst(), filterSlice);
  }

  // shards
  auto const shardsSlice = base.get(NODE_SHARDS_PARAM);

  if (shardsSlice.isArray()) {
    TRI_ASSERT(plan.getAst() && plan.getAst()->query());
    auto const* collections = plan.getAst()->query()->collections();
    TRI_ASSERT(collections);

    for (auto const shardSlice : velocypack::ArrayIterator(shardsSlice)) {
      auto const shardId = shardSlice.copyString();  // shardID is collection name on db server
      auto const* shard = collections->get(shardId);

      if (!shard) {
        LOG_TOPIC("6fba2", ERR, arangodb::iresearch::TOPIC)
            << "unable to lookup shard '" << shardId << "' for the view '"
            << _view->name() << "'";
        continue;
      }

      _shards.push_back(shard->name());
    }
  } else {
    LOG_TOPIC("a48f3", ERR, arangodb::iresearch::TOPIC)
        << "invalid 'IResearchViewNode' json format: unable to find 'shards' "
           "array";
  }

  // options
  TRI_ASSERT(plan.getAst() && plan.getAst()->query());

  auto const options = base.get(NODE_OPTIONS_PARAM);

  if (!::fromVelocyPack(options, _options)) {
    THROW_ARANGO_EXCEPTION_MESSAGE(
        TRI_ERROR_BAD_PARAMETER,
        "failed to parse 'IResearchViewNode' options: " + options.toString());
  }

  // volatility mask
  auto const volatilityMaskSlice = base.get(NODE_VOLATILITY_PARAM);

  if (volatilityMaskSlice.isNumber()) {
    _volatilityMask = volatilityMaskSlice.getNumber<int>();
  }

  // primary sort
  auto const primarySortSlice = base.get(NODE_PRIMARY_SORT_PARAM);

  if (!primarySortSlice.isNone()) {
    std::string error;
    IResearchViewSort sort;
    if (!sort.fromVelocyPack(primarySortSlice, error)) {
      THROW_ARANGO_EXCEPTION_MESSAGE(
          TRI_ERROR_BAD_PARAMETER,
          "failed to parse 'IResearchViewNode' primary sort: " +
              primarySortSlice.toString() + ", error: '" + error + "'");
    }

    TRI_ASSERT(_view);
    auto& primarySort = LogicalView::cast<IResearchView>(*_view).primarySort();

    if (sort != primarySort) {
      THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
                                     "primary sort " + primarySortSlice.toString() +
                                         " for 'IResearchViewNode' doesn't "
                                         "match the one specified in view '" +
                                         _view->name() + "'");
    }

    if (!primarySort.empty()) {
      size_t primarySortBuckets = primarySort.size();

      auto const primarySortBucketsSlice = base.get(NODE_PRIMARY_SORT_BUCKETS_PARAM);

      if (!primarySortBucketsSlice.isNone()) {
        if (!primarySortBucketsSlice.isNumber()) {
          THROW_ARANGO_EXCEPTION_MESSAGE(
              TRI_ERROR_BAD_PARAMETER,
              "invalid vpack format: 'primarySortBuckets' attribute is "
              "intended to be a number");
        }

        primarySortBuckets = primarySortBucketsSlice.getNumber<size_t>();

        if (primarySortBuckets > primarySort.size()) {
          THROW_ARANGO_EXCEPTION_MESSAGE(
              TRI_ERROR_BAD_PARAMETER,
              "invalid vpack format: value of 'primarySortBuckets' attribute "
              "'" +
                  std::to_string(primarySortBuckets) +
                  "' is greater than number of buckets specified in "
                  "'primarySort' attribute '" +
                  std::to_string(primarySort.size()) + "' of the view '" +
                  _view->name() + "'");
        }
      }

      // set sort from corresponding view
      _sort.first = &primarySort;
      _sort.second = primarySortBuckets;
    }
  }
}

void IResearchViewNode::planNodeRegisters(
    std::vector<aql::RegisterId>& nrRegsHere, std::vector<aql::RegisterId>& nrRegs,
    std::unordered_map<aql::VariableId, aql::VarInfo>& varInfo,
    unsigned int& totalNrRegs, unsigned int depth) const {
  nrRegsHere.emplace_back(0);

  // create a copy of the last value here
  // this is requried because back returns a reference and emplace/push_back
  // may invalidate all references
  aql::RegisterCount const prevRegistersCount = nrRegs.back();
  nrRegs.emplace_back(prevRegistersCount);
  //  if (isInInnerLoop()) {
  //    return;
  //  }

  // plan registers for output scores
  for (auto const& scorer : _scorers) {
    ++nrRegsHere[depth];
    ++nrRegs[depth];
    varInfo.emplace(scorer.var->id, aql::VarInfo(depth, totalNrRegs++));
  }

  // Plan register for document-id only block
  if (isLateMaterialized()) {
    ++nrRegsHere[depth];
    ++nrRegs[depth];
    varInfo.emplace(_outNonMaterializedColPtr->id, aql::VarInfo(depth, totalNrRegs++));
    ++nrRegsHere[depth];
    ++nrRegs[depth];
    varInfo.emplace(_outNonMaterializedDocId->id, aql::VarInfo(depth, totalNrRegs++));
  } else {
    ++nrRegsHere[depth];
    ++nrRegs[depth];
    varInfo.emplace(_outVariable->id, aql::VarInfo(depth, totalNrRegs++));
  }
}

std::pair<bool, bool> IResearchViewNode::volatility(bool force /*=false*/) const {
  if (force || _volatilityMask < 0) {
    _volatilityMask = evaluateVolatility(*this);
  }

  return std::make_pair(irs::check_bit<0>(_volatilityMask),  // filter
                        irs::check_bit<1>(_volatilityMask));  // sort
}

/// @brief toVelocyPack, for EnumerateViewNode
void IResearchViewNode::toVelocyPackHelper(VPackBuilder& nodes, unsigned flags,
                                           std::unordered_set<ExecutionNode const*>& seen) const {
  // call base class method
  aql::ExecutionNode::toVelocyPackHelperGeneric(nodes, flags, seen);

  // system info
  nodes.add(NODE_DATABASE_PARAM, VPackValue(_vocbase.name()));
  // need 'view' field to correctly print view name in JS explanation
  nodes.add(NODE_VIEW_NAME_PARAM, VPackValue(_view->name()));
  nodes.add(NODE_VIEW_ID_PARAM, VPackValue(basics::StringUtils::itoa(_view->id())));

  // our variable
  nodes.add(VPackValue(NODE_OUT_VARIABLE_PARAM));
  _outVariable->toVelocyPack(nodes);

  if (_outNonMaterializedDocId != nullptr) {
    nodes.add(VPackValue(NODE_OUT_NM_DOC_PARAM));
    _outNonMaterializedDocId->toVelocyPack(nodes);
  }

  if (_outNonMaterializedColPtr != nullptr) {
    nodes.add(VPackValue(NODE_OUT_NM_COL_PARAM));
    _outNonMaterializedColPtr->toVelocyPack(nodes);
  }

  // filter condition
  nodes.add(VPackValue(NODE_CONDITION_PARAM));
  if (!::filterConditionIsEmpty(_filterCondition)) {
    _filterCondition->toVelocyPack(nodes, flags != 0);
  } else {
    nodes.openObject();
    nodes.close();
  }

  // sort condition
  nodes.add(VPackValue(NODE_SCORERS_PARAM));
  ::toVelocyPack(nodes, _scorers, flags != 0);

  // shards
  {
    VPackArrayBuilder arrayScope(&nodes, NODE_SHARDS_PARAM);
    for (auto& shard : _shards) {
      nodes.add(VPackValue(shard));
    }
  }

  // options
  nodes.add(VPackValue(NODE_OPTIONS_PARAM));
  ::toVelocyPack(nodes, _options);

  // volatility mask
  nodes.add(NODE_VOLATILITY_PARAM, VPackValue(_volatilityMask));

  // primarySort
  if (_sort.first && !_sort.first->empty()) {
    {
      VPackArrayBuilder arrayScope(&nodes, NODE_PRIMARY_SORT_PARAM);
      _sort.first->toVelocyPack(nodes);
    }
    nodes.add(NODE_PRIMARY_SORT_BUCKETS_PARAM, VPackValue(_sort.second));
  }

  nodes.close();
}

std::vector<std::reference_wrapper<aql::Collection const>> IResearchViewNode::collections() const {
  TRI_ASSERT(_plan && _plan->getAst() && _plan->getAst()->query());
  auto const* collections = _plan->getAst()->query()->collections();
  TRI_ASSERT(collections);

  std::vector<std::reference_wrapper<aql::Collection const>> viewCollections;

  auto visitor = [&viewCollections, collections](TRI_voc_cid_t cid) -> bool {
    auto const id = basics::StringUtils::itoa(cid);
    auto const* collection = collections->get(id);

    if (collection) {
      viewCollections.push_back(*collection);
    } else {
      LOG_TOPIC("ee270", WARN, arangodb::iresearch::TOPIC)
          << "collection with id '" << id << "' is not registered with the query";
    }

    return true;
  };

  if (_options.restrictSources) {
    viewCollections.reserve(_options.sources.size());
    for (auto const cid : _options.sources) {
      visitor(cid);
    }
  } else {
    _view->visitCollections(visitor);
  }

  return viewCollections;
}

/// @brief clone ExecutionNode recursively
aql::ExecutionNode* IResearchViewNode::clone(aql::ExecutionPlan* plan, bool withDependencies,
                                             bool withProperties) const {
  TRI_ASSERT(plan);

  auto* outVariable = _outVariable;
  auto* outNonMaterializedDocId = _outNonMaterializedDocId;
  auto* outNonMaterializedColId = _outNonMaterializedColPtr;

  if (withProperties) {
    outVariable = plan->getAst()->variables()->createVariable(outVariable);
    if (outNonMaterializedDocId != nullptr) {
      TRI_ASSERT(_outNonMaterializedColPtr != nullptr);
      outNonMaterializedDocId = plan->getAst()->variables()->createVariable(outNonMaterializedDocId);
    }
    if (outNonMaterializedColId != nullptr) {
      TRI_ASSERT(_outNonMaterializedDocId != nullptr);
      outNonMaterializedColId = plan->getAst()->variables()->createVariable(outNonMaterializedColId);
    }
  }

  auto node =
      std::make_unique<IResearchViewNode>(*plan, _id, _vocbase, _view, *outVariable,
                                          const_cast<aql::AstNode*>(_filterCondition),
                                          nullptr, decltype(_scorers)(_scorers));
  node->_shards = _shards;
  node->_options = _options;
  node->_volatilityMask = _volatilityMask;
  node->_sort = _sort;
  if (outNonMaterializedColId != nullptr && outNonMaterializedDocId != nullptr) {
    node->setLateMaterialized(outNonMaterializedColId, outNonMaterializedDocId);
  }
  return cloneHelper(std::move(node), withDependencies, withProperties);
}

bool IResearchViewNode::empty() const noexcept {
  return _view->visitCollections(viewIsEmpty);
}

/// @brief the cost of an enumerate view node
aql::CostEstimate IResearchViewNode::estimateCost() const {
  if (_dependencies.empty()) {
    return aql::CostEstimate::empty();
  }
  // TODO: get a better guess from view
  aql::CostEstimate estimate = _dependencies[0]->getCost();
  estimate.estimatedCost += estimate.estimatedNrItems;
  return estimate;
}

/// @brief getVariablesUsedHere, modifying the set in-place
void IResearchViewNode::getVariablesUsedHere(
    ::arangodb::containers::HashSet<aql::Variable const*>& vars) const {
  if (!::filterConditionIsEmpty(_filterCondition)) {
    aql::Ast::getReferencedVariables(_filterCondition, vars);
  }

  for (auto& scorer : _scorers) {
    aql::Ast::getReferencedVariables(scorer.node, vars);
  }
}

std::vector<arangodb::aql::Variable const*> IResearchViewNode::getVariablesSetHere() const {
    std::vector<arangodb::aql::Variable const*> vars(_scorers.size() +
                                                     // document or  collection + docId for late materialization
                                                    (isLateMaterialized() ? 2 : 1));

    std::transform(_scorers.begin(), _scorers.end(), vars.begin(),
      [](auto const& scorer) { return scorer.var; });
    if (isLateMaterialized()) {
      vars[vars.size() - 2] = _outNonMaterializedColPtr;
      vars[vars.size() - 1] = _outNonMaterializedDocId;
    } else {
      vars[vars.size() - 1] = _outVariable;
    }
    return vars;
  }

std::shared_ptr<std::unordered_set<aql::RegisterId>> IResearchViewNode::calcInputRegs() const {
  std::shared_ptr<std::unordered_set<aql::RegisterId>> inputRegs =
      std::make_shared<std::unordered_set<aql::RegisterId>>();

  if (!::filterConditionIsEmpty(_filterCondition)) {
    ::arangodb::containers::HashSet<aql::Variable const*> vars;
    aql::Ast::getReferencedVariables(_filterCondition, vars);

    for (auto const& it : vars) {
      aql::RegisterId reg = varToRegUnchecked(*it);
      // The filter condition may refer to registers that are written here
      if (reg < getNrInputRegisters()) {
        inputRegs->emplace(reg);
      }
    }
  }

  return inputRegs;
}

void IResearchViewNode::filterCondition(aql::AstNode const* node) noexcept {
  _filterCondition = !node ? &ALL : node;
}

bool IResearchViewNode::filterConditionIsEmpty() const noexcept {
  return ::filterConditionIsEmpty(_filterCondition);
}

std::unique_ptr<aql::ExecutionBlock> IResearchViewNode::createBlock(
    aql::ExecutionEngine& engine,
    std::unordered_map<aql::ExecutionNode*, aql::ExecutionBlock*> const&) const {
  if (ServerState::instance()->isCoordinator()) {
    // coordinator in a cluster: empty view case

#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
    TRI_ASSERT(ServerState::instance()->isCoordinator());
#endif
    aql::ExecutionNode const* previousNode = getFirstDependency();
    TRI_ASSERT(previousNode != nullptr);
    aql::ExecutorInfos infos(arangodb::aql::make_shared_unordered_set(),
                             arangodb::aql::make_shared_unordered_set(),
                             getRegisterPlan()->nrRegs[previousNode->getDepth()],
                             getRegisterPlan()->nrRegs[getDepth()],
                             getRegsToClear(), calcRegsToKeep());

    return std::make_unique<aql::ExecutionBlockImpl<aql::NoResultsExecutor>>(&engine, this,
                                                                             std::move(infos));
  }

  auto* trx = engine.getQuery()->trx();

  if (!trx) {
    LOG_TOPIC("7c905", WARN, arangodb::iresearch::TOPIC)
        << "failed to get transaction while creating IResearchView "
           "ExecutionBlock";

    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
                                   "failed to get transaction while creating "
                                   "IResearchView ExecutionBlock");
  }

  auto& view = LogicalView::cast<IResearchView>(*this->view());

  std::shared_ptr<IResearchView::Snapshot const> reader;

  LOG_TOPIC("82af6", TRACE, arangodb::iresearch::TOPIC)
      << "Start getting snapshot for view '" << view.name() << "'";

  if (options().forceSync &&
      trx->state()->hasHint(arangodb::transaction::Hints::Hint::GLOBAL_MANAGED)) {
    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
                                   "cannot use waitForSync with "
                                   "views and transactions");
  }

  // we manage snapshot differently in single-server/db server,
  // see description of functions below to learn how
  if (ServerState::instance()->isDBServer()) {
    reader = snapshotDBServer(*this, *trx);
  } else {
    reader = snapshotSingleServer(*this, *trx);
  }

  if (!reader) {
    LOG_TOPIC("9bb93", WARN, arangodb::iresearch::TOPIC)
        << "failed to get snapshot while creating arangosearch view "
           "ExecutionBlock for view '"
        << view.name() << "'";

    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
                                   "failed to get snapshot while creating "
                                   "arangosearch view ExecutionBlock");
  }

  if (0 == reader->size()) {
    // nothing to query
    aql::ExecutionNode const* previousNode = getFirstDependency();
    TRI_ASSERT(previousNode != nullptr);
    aql::ExecutorInfos infos(arangodb::aql::make_shared_unordered_set(),
                             arangodb::aql::make_shared_unordered_set(),
                             getRegisterPlan()->nrRegs[previousNode->getDepth()],
                             getRegisterPlan()->nrRegs[getDepth()],
                             getRegsToClear(), calcRegsToKeep());

    return std::make_unique<aql::ExecutionBlockImpl<aql::NoResultsExecutor>>(&engine, this,
                                                                             std::move(infos));
  }

  LOG_TOPIC("33853", TRACE, arangodb::iresearch::TOPIC)
      << "Finish getting snapshot for view '" << view.name() << "'";

  bool const ordered = !_scorers.empty();
  bool const materialized = !isLateMaterialized();
  // We have one output register for documents, which is always the first after
  // the input registers.
  auto const firstOutputRegister = getNrInputRegisters();
  auto numScoreRegisters = static_cast<aql::RegisterCount>(_scorers.size());

  aql::RegisterCount numDocumentRegs = 0;
  // We could be asked to produce only document/collection ids for later materialization or full document body at once
  if (materialized) {
    numDocumentRegs += 1;
  } else {
    numDocumentRegs += 2;
  }

  // We have one additional output register for each scorer, before
  // the output register(s) for documents (one or two, depending on late materialization)
  // These must of course fit in the
  // available registers. There may be unused registers reserved for later
  // blocks.
  TRI_ASSERT(getNrInputRegisters() + numDocumentRegs + numScoreRegisters <= getNrOutputRegisters());
  std::shared_ptr<std::unordered_set<aql::RegisterId>> writableOutputRegisters =
      aql::make_shared_unordered_set();
  writableOutputRegisters->reserve(numDocumentRegs + numScoreRegisters);
  for (aql::RegisterId reg = firstOutputRegister;
       reg < firstOutputRegister + numScoreRegisters + numDocumentRegs; reg++) {
    writableOutputRegisters->emplace(reg);
  }

  TRI_ASSERT(writableOutputRegisters->size() == numDocumentRegs + numScoreRegisters);
  TRI_ASSERT(writableOutputRegisters->begin() != writableOutputRegisters->end());
  TRI_ASSERT(firstOutputRegister == *std::min_element(writableOutputRegisters->begin(),
                                                      writableOutputRegisters->end()));
  aql::ExecutorInfos infos =
      createRegisterInfos(calcInputRegs(), std::move(writableOutputRegisters));

  aql::IResearchViewExecutorInfos executorInfos{std::move(infos),
                                                reader,
                                                firstOutputRegister,
                                                numScoreRegisters,
                                                *engine.getQuery(),
                                                scorers(),
                                                _sort,
                                                *plan(),
                                                outVariable(),
                                                filterCondition(),
                                                volatility(),
                                                getRegisterPlan()->varInfo,
                                                getDepth()};

  if (_sort.first) {
    TRI_ASSERT(!_sort.first->empty()); // guaranteed by optimizer rule
    if (materialized) {
      if (!ordered) {
        return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewMergeExecutor<false, true>>>(
          &engine, this, std::move(executorInfos));
      }

      return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewMergeExecutor<true, true>>>(
        &engine, this, std::move(executorInfos));
    } else {
      if (!ordered) {
        return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewMergeExecutor<false, false>>>(
          &engine, this, std::move(executorInfos));
      }
      return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewMergeExecutor<true, false>>>(
        &engine, this, std::move(executorInfos));
    }
  }
  if (materialized) {
    if (!ordered) {
      return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewExecutor<false, true>>>(
        &engine, this, std::move(executorInfos));
    }
    return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewExecutor<true, true>>>(
      &engine, this, std::move(executorInfos));
  } else {
    if (!ordered) {
      return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewExecutor<false, false>>>(
        &engine, this, std::move(executorInfos));
    }
    return std::make_unique<aql::ExecutionBlockImpl<aql::IResearchViewExecutor<true, false>>>(
      &engine, this, std::move(executorInfos));
  }
}

}  // namespace iresearch
}  // namespace arangodb


text:
class CannedBrowsingDataAppCacheHelper;
class CannedBrowsingDataCookieHelper;
class CannedBrowsingDataDatabaseHelper;
class CannedBrowsingDataFileSystemHelper;
class CannedBrowsingDataIndexedDBHelper;
class CannedBrowsingDataLocalStorageHelper;
class CannedBrowsingDataServerBoundCertHelper;
class GURL;
class Profile;

class LocalSharedObjectsContainer {
 public:
  explicit LocalSharedObjectsContainer(Profile* profile);
  ~LocalSharedObjectsContainer();

  // Empties the container.
  void Reset();

  // Returns the number of objects stored in the container.
  size_t GetObjectCount() const;

  // Returns the number of objects for the given |origin|.
  size_t GetObjectCountForDomain(const GURL& url) const;

  CannedBrowsingDataAppCacheHelper* appcaches() const {
    return appcaches_;
  }
  CannedBrowsingDataCookieHelper* cookies() const {
    return cookies_;
  }
  CannedBrowsingDataDatabaseHelper* databases() const {
    return databases_;
  }
  CannedBrowsingDataFileSystemHelper* file_systems() const {
    return file_systems_;
  }
  CannedBrowsingDataIndexedDBHelper* indexed_dbs() const {
    return indexed_dbs_;
  }
  CannedBrowsingDataLocalStorageHelper* local_storages() const {
    return local_storages_;
  }
  CannedBrowsingDataServerBoundCertHelper* server_bound_certs() const {
    return server_bound_certs_;
  }
  CannedBrowsingDataLocalStorageHelper* session_storages() const {
    return session_storages_;
  }

 private:
  scoped_refptr<CannedBrowsingDataAppCacheHelper> appcaches_;
  scoped_refptr<CannedBrowsingDataCookieHelper> cookies_;
  scoped_refptr<CannedBrowsingDataDatabaseHelper> databases_;
  scoped_refptr<CannedBrowsingDataFileSystemHelper> file_systems_;
  scoped_refptr<CannedBrowsingDataIndexedDBHelper> indexed_dbs_;
  scoped_refptr<CannedBrowsingDataLocalStorageHelper> local_storages_;
  scoped_refptr<CannedBrowsingDataServerBoundCertHelper> server_bound_certs_;
  scoped_refptr<CannedBrowsingDataLocalStorageHelper> session_storages_;

  DISALLOW_COPY_AND_ASSIGN(LocalSharedObjectsContainer);
};

#endif  // CHROME_BROWSER_CONTENT_SETTINGS_LOCAL_SHARED_OBJECTS_CONTAINER_H_

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace EcommerceBundle\Repository;

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * SecurityRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SecurityRepository extends \Doctrine\ORM\EntityRepository implements UserLoaderInterface
{
    /**
     * Loads the user for the given username.
     *
     * This method must return null if the user is not found.
     *
     * @param string $username The username
     *
     * @return UserInterface|null
     */
    public function loadUserByUsername($username)
    {
        $queryBuilder = $this->createQueryBuilder('u');
        $queryBuilder
            ->where($queryBuilder->expr()->eq('u.username', ':username'))
            ->orWhere($queryBuilder->expr()->eq('u.email', ':username'))
            ->setParameter(':username', $username);

        return $queryBuilder->getQuery()->getOneOrNullResult();
    }
}


text:
using namespace OC;

void OCResourceRequest::setPayload(OCPayload* payload)
{
    MessageContainer info;

    if(payload == nullptr)
    {
        return;
    }
    if(payload->type != PAYLOAD_TYPE_REPRESENTATION)
    {
        throw std::logic_error("Wrong payload type");
        return;
    }

    info.setPayload(payload);

    const std::vector<OCRepresentation>& reps = info.representations();
    if(reps.size() >0)
    {
        std::vector<OCRepresentation>::const_iterator itr = reps.begin();
        std::vector<OCRepresentation>::const_iterator back = reps.end();
        m_representation = *itr;
        ++itr;

        for(;itr != back; ++itr)
        {
            m_representation.addChild(*itr);
        }
    }
    else
    {
        oclog() << "setPayload Error: "<<OC::Exception::INVALID_REPRESENTATION<< std::flush;
    }
}


text:
'use strict';

angular.module('mean').controller('PlayersController', ['$scope', 'Global', 'Players', '$stateParams', '$location',
    function ($scope, Global, Players, $stateParams, $location) {
        $scope.global = Global;

        $scope.players = {
            name: 'players'
        };

        $scope.findAll = function () {
            Players.query(function (players) {
                $scope.players = players;
            });
        };

        $scope.findOne = function () {
            Players.get({
                playerId: $stateParams.playerId
            }, function (player) {
                $scope.player = player;
            });
        };
    }
]);


text:
import RootQuery from './RootQuery';
import {Request} from 'express';
import RootMutation from './RootMutation';
import {makeExecutableSchema} from 'graphql-tools';
import Types from './types/index';
import MainResolver from './resolvers/MainResolver'
import * as jwt from 'jsonwebtoken';

const Schema = `
    schema {
        query: RootQuery
        mutation: RootMutation
    }
`

let SchemaType =  makeExecutableSchema({
    typeDefs:[Schema, RootMutation, RootQuery, Types],
    resolvers: MainResolver
});

export default SchemaType;


text:
function affixTopDirective($window) {
  'ngInject';

  var $win = angular.element($window);

  return {
    restrict: 'A',
    scope: {},
    link: linkFn
  };

  function linkFn(scope, elem, attrs, fn) {

    var topClass = attrs.affixTop, // get CSS class from directive's attribute value
        offsetTop = elem.prop('offsetTop'); // get element's top relative to the document
        //console.log(topClass);

    window.onscroll = function () {
      //console.log("hello");
      //console.log('top ' + offsetTop);
      //console.log(window.scrollY);

      if (window.scrollY >= offsetTop + 15) {
        elem.addClass(topClass);
      } else {
        elem.removeClass(topClass);
      }

      // any $scope variable updates
      scope.$digest();
    };

  }
}

export default affixTopDirective;


text:
#define CORE_LOGGING_MODULE_NAME "UnitTest"
#define CORE_LOGGING_MODULE_LEVEL CL_ALL_FILE

//#include "CoreDebugPrint.h"
#include "UnitTest.h"
#include "UnitTestFramework.h"

// Add all reference invocations here
#if !defined(__SYMBIAN__) && !defined(_WIN32_WCE)
// UT_REFERENCE_TEST_FILE(JTCTestTryLock);
// UT_REFERENCE_TEST_FILE(JTCUncaughtException);
// UT_REFERENCE_TEST_FILE(JTCStaticMonitorTest);
// UT_REFERENCE_TEST_FILE(JTCReentrantMonitorTest);
// UT_REFERENCE_TEST_FILE(JTCMonitorTest2);
// UT_REFERENCE_TEST_FILE(JTCMonitorTest);
// UT_REFERENCE_TEST_FILE(JTCDeadMonitorTest);
// UT_REFERENCE_TEST_FILE(JTCTestRWLock);
// UT_REFERENCE_TEST_FILE(JTCWaitTest);
// UT_REFERENCE_TEST_FILE(JTCThreadCreateTest);
// UT_REFERENCE_TEST_FILE(JTCThreadStateTest);
// UT_REFERENCE_TEST_FILE(JTCTSSTest);
// UT_REFERENCE_TEST_FILE(JTCThreadExitTest);
// UT_REFERENCE_TEST_FILE(JTCThreadIDTest);
#endif

#if defined(_WIN32_WCE)
UT_REFERENCE_TEST_FILE(WinTileMapToolkitTests);
#endif

UnitTest::UnitTest(const char* name)
   : RegressionTest(name)
{

}

void UnitTest::startTest()
{
   typedef UnitTestFramework::TestVector TestVector;

   UnitTestFramework& framework = UnitTestFramework::instance();

   TestVector& tests = framework.getTests();

   for(TestVector::iterator itr = tests.begin(); itr != tests.end(); itr++)
   {
      framework.addNewTest();
      UnitTestStruct& t = *itr;
      // coreprintln("+ Starting unit test %s", t.name);
      printf("+ Starting unit test %s\n", t.name);
      t.func(framework);
   }

   if(framework.getNumTests() == 0) {
      // coreprintln("No unit tests registered.");
      printf("No unit tests registered.\n");
      setTestPassed();
   } else {
      if (framework.getNumFailedTests() > 0) {
         setTestFailed("One or more unit tests did not pass.");
      } else {
         setTestPassed();
      }
   }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['addpage'] = 'Agregar página';
$string['defaultpage'] = 'Página My Moodle por defecto';
$string['defaultprofilepage'] = 'Página de perfil por defecto';
$string['delpage'] = 'Eliminar página';
$string['managepages'] = 'Gestionar páginas';
$string['mymoodle'] = 'Área personal';
$string['nocourses'] = 'No hay información del curso para mostrar.';
$string['noguest'] = 'Los invitados no pueden acceder a la página \'Área personal\'';
$string['pinblocks'] = 'Configurar bloques actualizados para mi Moodle';
$string['pinblocksexplan'] = 'Cualesquiera ajustes de bloque que configure aquí serán visibles (y no editables) por cualquier usuario de Moodle en su página general de \'Mi Moodle\'';


text:
{% extends "base.html" %}
{% block content %}
<form class="form-inline" action="" method="GET">

   {% for i in g.valid_logs %}
     {% if i in checkbox %}
     {% set checked = 'checked' %}
     {% else %}
     {% set checked = '' %}
     {% endif %}

         <input type="checkbox" name="{{i}}" {{ checked }} value="y">

         {{ i }}

   {% endfor %}

    Filter Text
    <input type="text" name="searchfilter" placeholder="192.168.1.100" class="form-control" aria-describedby="basic-addon1" value="{{ request.args.get('searchfilter') or "" }}">
    Refresh Interval
    <input type="text" value="{{ request.args.get('refresh') or "" }}" name="refresh" placeholder="100" class="form-control" aria-describedby="basic-addon1">
    Lines
    <input type="text" value="{{ request.args.get('lineno') or "" }}" name="lineno" placeholder="10" class="form-control" aria-describedby="basic-addon1">

      <button class="btn btn-default" type="submit">Go!</button>

    reset

</form>

Viewing {{ lines|count }} lines

{%- for line in lines -%}
{{ line }}
{% else %}
No log entries found
{% endfor %}

{% block script %}

{% endblock script %}
{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/water2"
        android:orientation="vertical" >

        <Button
            android:id="@+id/t"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:background="#0099cc"
            android:text="OSMECON 2014"
            android:textColor="#ffffff"
            android:textSize="30sp"
            android:textStyle="bold" >
        </Button>

        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_margin="3dp"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:gravity="center"
                    android:text="@string/home_welcome"
                    android:textColor="#222222"
                    android:textSize="20sp"
                    android:textStyle="bold" >
                </TextView>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:orientation="horizontal" >

                    <ImageView
                        android:layout_width="250dp"
                        android:layout_height="250dp"
                        android:scaleType="fitXY"
                        android:src="@drawable/imag" >
                    </ImageView>
                </LinearLayout>

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:gravity="center"
                    android:text="Scroll below for more"
                    android:textColor="#111111"
                    android:textSize="13sp"
                    android:textStyle="normal" >
                </TextView>

                <Button
                    android:id="@+id/title1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="About Us"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/title2"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Events"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/title5"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Theme"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/titlewa"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Schedule"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/cguestb"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Chief Guest"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/title3"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Register"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                 <Button
                    android:id="@+id/pay"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Payment"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                 <Button
                    android:id="@+id/accb"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Accomodation"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/abutton"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Announcements"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/title4"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="Contact Us"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <Button
                    android:id="@+id/team"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/sel"
                    android:text="The Team"
                    android:textColor="#ffffff"
                    android:textSize="22sp"
                    android:textStyle="italic" >
                </Button>

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:gravity="center"
                    android:text="@string/home_poem"
                    android:textColor="#111111"
                    android:textSize="20sp"
                    android:textStyle="italic" >
                </TextView>

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:gravity="fill_horizontal"
                    android:text="@string/home_note"
                    android:textColor="#111111"
                    android:textSize="20sp"
                    android:textStyle="normal" >
                </TextView>

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:gravity="fill_horizontal"
                    android:text="@string/home_copyright"
                    android:textColor="#111111"
                    android:textSize="12sp"
                    android:textStyle="normal" >
                </TextView>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AH.DLayer.OPD;
using AH.HR.MODEL;
using AH.OPD.MODEL;
using AH.OPD.DAL;
using AH.Shared.MODEL;

namespace AH.OPD.BLL
{
    public class OPDReportBLL
    {
        //Fauzul 28 Jun 2014
        public List<OPDDoctorCallQ> GetsOPDDoctorName()
        {
            return new OpdTicketReportDAL().GetsOPDDoctorName();
        }
        //Fauzul 28 Jun 2014
        public List<OPDTicketRO> GetsOPDDocRoomNo(string RoomNo, string DocID)
        {
            return new OpdTicketReportDAL().GetsOPDDocRoomNo(RoomNo, DocID);
        }
        //Fauzul 28 Jun 2014
        public List<OPDTicketRO> ChangePatientStatus(string TicketNo, string RoomNO, string Doc_ID)
        {
            return new OpdTicketReportDAL().ChangePatientStatus(TicketNo, RoomNO, Doc_ID);
        }
        public List<OPDTicketRO> GetOPDTicketDetails( string ParamDateFrom, string ParamDateTo)
        {
            return new OpdTicketReportDAL().GetOPDTicketDetails( ParamDateFrom,  ParamDateTo);
        }
        public List<OPDTicketRO> GetOPDTicketMR(string TicketNo)
        {
            return new OpdTicketReportDAL().GetOPDTicketMR(TicketNo);
        }
        public List<OPDTicketRO> GetOPDDepartment(string DepartmentName, string ParamDateFrom, string ParamDateTo)
        {
            return new OpdTicketReportDAL().GetOPDDepartment(DepartmentName, ParamDateFrom, ParamDateTo);
        }
        public List<OPDTicketRO> GetOPDMRDoctor(string doctorid, string deapartmentname, string ParamDateFrom, string ParamDateTo)
        {
            return new OpdTicketReportDAL().GetOPDMRDoctor( doctorid,  deapartmentname,  ParamDateFrom,  ParamDateTo);
        }
        public List<OPDTicketRO> GetsOPD()
        {
            return new OpdTicketReportDAL().GetsOPD();
        }
        //public List<OPDTicketRO> GetsOPD(string TicketNo)
        //{
        //    return new OpdTicketReportDAL().GetsOPD(TicketNo);
        //}
        public List<Department> GetsDepartmentName()
        {
            return new OpdTicketReportDAL().GetsDepartmentName();
        }
        public List<Doctor> GetDoctorNames()
        {
            return new OpdTicketReportDAL().GetDoctorNames();
        }
        public List<OPDPrescriptionReportNewRO> GetOPDPrescription(string wherecondition)
        {
            return new OpdPrescriptionReportDAL().GetOPDPrescription(wherecondition);
        }
        //public Medicine SaveMedicine(Medicine oMedicine)
        //{
        //    return new OpdPrescriptionReportDAL().SaveMedicine(oMedicine);
        //}
        public List<PatHistoryTree> GetsTree(string HCN)
        {
            return new OpdTicketReportDAL().GetsTree(HCN);
        }

        public List<OPDTicketRO> GetOPDRefundTicketMR(string TicketNo)
        {
            return new OpdTicketReportDAL().GetOPDRefundTicketMR(TicketNo);
        }

        public List<OPDTicketRO> GetOPDVoucher(string user_id, string ParamDateFrom, string ParamDateTo)
     //  public  List<AccountsPayment> GetOPDVoucher(string user_id, string ParamDateFrom, string ParamDateTo)
        {
            return new OpdTicketReportDAL().GetOPDVoucher(user_id, ParamDateFrom, ParamDateTo);
        }

        public List<OPDTicketRO> GetOPDCollSummary(string ParamDateFrom, string ParamDateTo)
        {
            return new OpdTicketReportDAL().GetOPDCollSummary(ParamDateFrom,ParamDateTo);
        }

        public List<OPDTicketRO> GetOPDVisitedPatList(string dept_id, string unit_id, string doc_id)
        {
            return new OpdTicketReportDAL().GetOPDVisitedPatList(dept_id, unit_id, doc_id);
        }
        public short ChangeTktStatusFrmDoc(string ticketNo, string DocID)
        {
            return new OpdTicketReportDAL().ChangeTktStatusFrmDoc(ticketNo, DocID);
        }

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Parasit. Alg. Pilze Java's (Jakarta) 2: 32 (1900)

#### Original name
Uredo phaji Racib.

### Remarks
null


text:
require "spec_helper"

describe VIPS::Image do
  before :all do
    @image = simg 'wagon.v'
    im = simg 'huge.jpg'
    @image2 = im.extract_area(100, 100, @image.x_size, @image.y_size)
  end

  it "should test for equality between two images" do
    im = @image.equal(@image.fliphor)
    im.should match_sha1('d03aedad4480b4200956b1922462799c4de706b5')
  end

  it "should test for equality between an image and constants" do
    im = @image.equal(200)
    im.should match_sha1('4de2fc653e48bf819fb619fef4e360fc1dc3d214')
  end

  it "should test for inequality between two images" do
    im = @image.notequal(@image.fliphor)
    im.should match_sha1('d2b2d4afdcaaf4567e8853abe6c9c31a5f6aaace')
  end

  it "should test for inequality between an image and constants" do
    im = @image.notequal(200)
    im.should match_sha1('d6cbaefac9aa13ad9bfd8c836977141cd861031a')
  end

  it "should test for pixels greater than others between two images" do
    im = @image.more(@image.fliphor)
    im.should match_sha1('0ee896e058a2a957e807304ecef5a6030950b02b')
  end

  it "should test for pixels greater than constants", :vips_lib_version => "!= 7.20" do
    im = @image.more(200)
    im.should match_sha1('64e5988ce4c6b1d1048a09fe5e624b3dbeeb71d8')
  end

  it "should test for pixels less than others between two images" do
    im = @image.less(@image.fliphor)
    im.should match_sha1('b1ed6ab5802831f2695a61975afe3afccf4ce2ea')
  end

  it "should test for pixels less than constants" do
    im = @image.less(210)
    im.should match_sha1('f19119b1159d4a8c494be9cccfce6039fd64086b')
  end

  it "should test for pixels greater than or equal others between two images" do
    im = @image.moreeq(@image.fliphor)
    im.should match_sha1('5bdb2f8177556a95d94a3ad3b606ee6246611e93')
  end

  it "should test for pixels greater than or equal constants" do
    im = @image.moreeq(200)
    im.should match_sha1('f03796ad26bd2de71f664d74072083e40907669f')
  end

  it "should test for pixels less than or equal others between two images" do
    im = @image.lesseq(@image.fliphor)
    im.should match_sha1('d8bc858ec69258ea68053ac24d68fc16f82a176b')
  end

  it "should test for pixels less than or equal constants" do
    im = @image.lesseq(210)
    im.should match_sha1('69f0beed7c4f648f004bef5ea032658a0c10065f')
  end

  it "should merge two images based on a third image" do
    mask = @image.moreeq(@image.fliphor)
    im = mask.ifthenelse(@image, @image.fliphor)
    im.should match_sha1('961d492112e3fd98ec4ff1ca57071907ab67fdb2')
  end

  it "should blend two images based on a third image" do
    mask = @image.moreeq(@image.fliphor)
    im = mask.blend(@image, @image.fliphor)
    im.should match_sha1('961d492112e3fd98ec4ff1ca57071907ab67fdb2')
  end
end


text:
{% extends "accounts/base.html" %}
{% block title %} Register{% endblock title %}
{% block register %} class="active" {% endblock register %}
{% block content %}

{% if user == 0 %}

Incorrect Username

{% elif pass == 0 %}

Incorrect Password

{% endif %}

Register

  <form class="form-horizontal" method="post" action="{% url 'accounts:registerhandler' %}" role="form">
        {% csrf_token %}

    Name

      <input class="form-control" name="name" placeholder="Name" required>

    Email Id

      <input class="form-control" type="email" name="email" placeholder="Email Id" required>

    Username

      <input class="form-control" name="username" placeholder="Username" required>

    Password

      <input type="password" class="form-control" name="password" placeholder="Password" required>

      <textarea class="form-control col-lg-10" name="address" placeholder="Address" rows="2" required></textarea>

    Employee Type

    <input type="radio" name="position" id="optionsRadios1" value="manager">
    Project Manager

    <input type="radio" name="position" id="optionsRadios2" value="employee">
    Employee

    Phone Number

      <input type="text" class="form-control" name="phone[]" placeholder="Phone Number" required>

  <button type="button" class="btn btn-primary" onclick="adddiv()" id ="add">Add Phone Number</button>
  <button  type="button" class="btn btn-primary" onclick="removediv()" id="remove">Delete Phone Number</button>

      <button type="submit" class="btn btn-default">Register</button>

</form>

Already Registered?

<button type="submit" onclick="login()" class="btn btn-default">Login</button></button>  here!

{% endblock content %}
{% block scripts %}

{% endblock scripts %}


text:
<?php
namespace Campaignmonitor\Transactional;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class TransactionalServiceFactory implements FactoryInterface
{

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new TransactionalService($serviceLocator->get('campaignmonitor_options'));
    }
}


text:
module Aws::LexModelBuildingService

  # When LexModelBuildingService returns an error response, the Ruby SDK constructs and raises an error.
  # These errors all extend Aws::LexModelBuildingService::Errors::ServiceError < {Aws::Errors::ServiceError}
  #
  # You can rescue all LexModelBuildingService errors using ServiceError:
  #
  #     begin
  #       # do stuff
  #     rescue Aws::LexModelBuildingService::Errors::ServiceError
  #       # rescues all LexModelBuildingService API errors
  #     end
  #
  #
  # ## Request Context
  # ServiceError objects have a {Aws::Errors::ServiceError#context #context} method that returns
  # information about the request that generated the error.
  # See {Seahorse::Client::RequestContext} for more information.
  #
  # ## Error Classes
  # * {AccessDeniedException}
  # * {BadRequestException}
  # * {ConflictException}
  # * {InternalFailureException}
  # * {LimitExceededException}
  # * {NotFoundException}
  # * {PreconditionFailedException}
  # * {ResourceInUseException}
  #
  # Additionally, error classes are dynamically generated for service errors based on the error code
  # if they are not defined above.
  module Errors

    extend Aws::Errors::DynamicErrors

    class AccessDeniedException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::AccessDeniedException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class BadRequestException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::BadRequestException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class ConflictException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::ConflictException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class InternalFailureException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::InternalFailureException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class LimitExceededException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::LimitExceededException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def retry_after_seconds
        @data[:retry_after_seconds]
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class NotFoundException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::NotFoundException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class PreconditionFailedException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::PreconditionFailedException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class ResourceInUseException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::LexModelBuildingService::Types::ResourceInUseException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def reference_type
        @data[:reference_type]
      end

      # @return [String]
      def example_reference
        @data[:example_reference]
      end
    end

  end
end


text:
<resources>
    <string name="app_name">Exploratory Search</string>
    <string name="action_settings">Settings</string>
    <string name="action_search">Search</string>
    <string name="drawer_open">Open</string>
    <string name="drawer_close">Close</string>

    <string name="nav_item_home">Home</string>
    <string name="nav_item_favorites">Favorites</string>
    <string name="nav_item_settings">Settings</string>

    <string-array name="nav_drawer_labels">
        <item>@string/nav_item_home</item>
        <item>@string/nav_item_favorites</item>
        <item>@string/nav_item_settings</item>
    </string-array>

    <string name="title_favorites">Favorites</string>
    <string name="title_settings">Setting</string>
    <string name="title_home">Home</string>

    <string-array name="nav_drawer_items">
        <item >Home</item>
        <item >What\'s Hot</item>
        <item >Favorites</item>
        <item >Settings</item>
    </string-array>

    <array name="nav_drawer_icons">
        <item>@drawable/ic_home</item>
        <item>@drawable/ic_whats_hot</item>
        <item>@drawable/ic_favorite</item>
        <item>@drawable/ic_setting</item>
    </array>

    <string name="desc_list_item_icon">Item Icon</string>

    <!--Home Fragment-->
    <string name="search_hint">Search...</string>
    <string name="top_result_label">TOP</string>
    <string name="recommend_result_label">RECOMMEND</string>
    <string name="expolatory_search_label">Expolatory Search</string>
    <string name="expolatory_search_details">The exploratory search is a new way to search the web, not to find what you are searching, but to find what you are not searching, and might be intersting for you ! It allows performing queries in an innovative way and helps you to navigate rich results. As a hub, it proposes redirections to others platforms to make you benefit from your discoveries</string>
    <string name="recommendation_label">Get recommendations on your interests</string>
    <string name="recommendation_details">Want a film recommendation related to actors you like? Want a film recommendation focus to genre you like? Interested by more complex and composite recommendations based on your deepest interests : a actor, a director and a film? Or maybe something simpler ? If you have a thirst for discovery and knowledge, System has answers for you</string>
    <string name="understand_recommend_label">Understand a recommendation</string>
    <string name="understand_details">System gives you recommendations, but also tools to understand why you have these recommendations, because we know that the more important in a recommendation is to know why you get it !</string>

</resources>


text:
using System;
using System.Linq;
using Zirpl.AppEngine.DataService;
using Zirpl.AppEngine.DataService.EntityFramework;
using Zirpl.AppEngine.DataService.EntityFramework.Mapping;
using Zirpl.Examples.CodeGeneration.VS2013.Commerce.Model.Catalog;
using Zirpl.Examples.CodeGeneration.VS2013.Commerce.Model.Metadata.Constants.Catalog;

namespace Zirpl.Examples.CodeGeneration.VS2013.Commerce.DataService.Mapping.Catalog
{
    public partial class DisplayProductMapping : EntityMappingBase<DisplayProduct, int>
    {
		protected override void MapProperties()
        {

			this.Property(o => o.Name).IsRequired(DisplayProductMetadataConstants.Name_IsRequired).HasMaxLength(DisplayProductMetadataConstants.Name_MaxLength, DisplayProductMetadataConstants.Name_IsMaxLength);
			this.Property(o => o.SeoId).IsRequired(DisplayProductMetadataConstants.SeoId_IsRequired).HasMaxLength(DisplayProductMetadataConstants.SeoId_MaxLength, DisplayProductMetadataConstants.SeoId_IsMaxLength);
			this.Property(o => o.Description).IsRequired(DisplayProductMetadataConstants.Description_IsRequired).HasMaxLength(DisplayProductMetadataConstants.Description_MaxLength, DisplayProductMetadataConstants.Description_IsMaxLength);
			this.Property(o => o.Sku).IsRequired(DisplayProductMetadataConstants.Sku_IsRequired).HasMaxLength(DisplayProductMetadataConstants.Sku_MaxLength, DisplayProductMetadataConstants.Sku_IsMaxLength);
			this.Property(o => o.AdminComment).IsRequired(DisplayProductMetadataConstants.AdminComment_IsRequired).HasMaxLength(DisplayProductMetadataConstants.AdminComment_MaxLength, DisplayProductMetadataConstants.AdminComment_IsMaxLength);

			this.MapCustomProperties();

            base.MapProperties();
        }

		partial void MapCustomProperties();

    }
}


text:
package zuo.biao.library.ui;

import java.util.HashMap;
import java.util.List;

import zuo.biao.library.R;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.util.ImageLoaderUtil;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.StringUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**通用网格Adapter(url, name)
 * *适用于gridView
 * @author Lemon
 * @use new GridAdapter(...); 具体参考.DemoAdapter
 */
public class GridAdapter extends BaseAdapter<Entry<String, String>> {
	private static final String TAG = "GridAdapter";

	public GridAdapter(Activity context) {
		this(context, R.layout.grid_item);
	}
	public GridAdapter(Activity context, int layoutRes) {
		super(context);
		setLayoutRes(layoutRes);
	}

	private int layoutRes;//item视图资源
	public void setLayoutRes(int layoutRes) {
		this.layoutRes = layoutRes;
	}
	private boolean hasName = true;//是否显示名字
	public GridAdapter setHasName(boolean hasName) {
		this.hasName = hasName;
		return this;
	}
	private boolean hasCheck = false;//是否使用标记功能
	public GridAdapter setHasCheck(boolean hasCheck) {
		this.hasCheck = hasCheck;
		return this;
	}

	//item标记功能,不需要可以删除<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	private HashMap<Integer, Boolean> hashMap;//实现选中标记的列表,不需要可以删除。这里可用List<Integer> checkedList代替
	public boolean getItemChecked(int position) {
		if (hasCheck == false) {
			Log.e(TAG, "<<< !!! hasCheck == false  >>>>> ");
			return false;
		}
		return hashMap.get(position);
	}
	public void setItemChecked(int position, boolean isChecked) {
		if (hasCheck == false) {
			Log.e(TAG, "<<< !!! hasCheck == false >>>>> ");
			return;
		}
		hashMap.put(position, isChecked);
		notifyDataSetChanged();
	}
	//item标记功能,不需要可以删除>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	public int selectedCount = 0;
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = convertView == null ? null : (ViewHolder) convertView.getTag();
		if (holder == null) {
			convertView = inflater.inflate(layoutRes, parent, false);

			holder = new ViewHolder();
			holder.ivGridItemHead = (ImageView) convertView.findViewById(R.id.ivGridItemHead);
			if (hasName) {
				holder.tvGridItemName = (TextView) convertView.findViewById(R.id.tvGridItemName);
			}
			if (hasCheck) {
				holder.ivGridItemCheck = (ImageView) convertView.findViewById(R.id.ivGridItemCheck);
			}

			convertView.setTag(holder);
		}

		final Entry<String, String> kvb = getItem(position);
		final String name = kvb.getValue();

		ImageLoaderUtil.loadImage(holder.ivGridItemHead, kvb.getKey());

		if (hasName) {
			holder.tvGridItemName.setVisibility(View.VISIBLE);
			holder.tvGridItemName.setText(StringUtil.getTrimedString(name));
		}

		if (hasCheck) {
			holder.ivGridItemCheck.setVisibility(View.VISIBLE);

			holder.ivGridItemCheck.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					setItemChecked(position, !getItemChecked(position));
					Log.i(TAG, (getItemChecked(position) ? "" : "取消") + "选择第 " + position + " 个item name=" + name);
				}
			});
		}

		return convertView;
	}

	static class ViewHolder {
		public ImageView ivGridItemHead;
		public TextView tvGridItemName;
		public ImageView ivGridItemCheck;
	}

	/**刷新列表
	 * @param list
	 */
	@Override
	public synchronized void refresh(List<Entry<String, String>> list) {
		if (list != null && list.size() > 0) {
			initList(list);
		}
		if (hasCheck) {
			selectedCount = 0;
			for (int i = 0; i < this.list.size(); i++) {
				if (getItemChecked(i) == true) {
					selectedCount ++;
				}
			}
		}
		notifyDataSetChanged();
	}

	/**标记List<String>中的值是否已被选中。
	 * 不需要可以删除,但"this.list = list;"这句
	 * 要放到constructor【这个adapter只有ModleAdapter(Context context, List<Object> list)这一个constructor】里去
	 * @param list
	 * @return
	 */
	@SuppressLint("UseSparseArrays")
	private void initList(List<Entry<String, String>> list) {
		this.list = list;
		if (hasCheck) {
			hashMap = new HashMap<Integer, Boolean>();
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					hashMap.put(i, false);
				}
			}
		}
	}

}