text:
namespace operations_research {

namespace {
const int kNoSelection = -1;
const int kMasterPropagatorId = 0;
const int kMaxNumberOfBruteForceItems = 30;
const int kMaxNumberOf64Items = 64;

// Comparator used to sort item in decreasing efficiency order
// (see KnapsackCapacityPropagator).
struct CompareKnapsackItemsInDecreasingEfficiencyOrder {
  explicit CompareKnapsackItemsInDecreasingEfficiencyOrder(int64 _profit_max)
      : profit_max(_profit_max) {}
  bool operator()(const KnapsackItemPtr& item1,
                  const KnapsackItemPtr& item2) const {
    return item1->GetEfficiency(profit_max) > item2->GetEfficiency(profit_max);
  }
  const int64 profit_max;
};

// Comparator used to sort search nodes in the priority queue in order
// to pop first the node with the highest profit upper bound
// (see KnapsackSearchNode). When two nodes have the same upper bound, we
// prefer the one with the highest current profit, ie. usually the one closer
// to a leaf. In practice, the main advantage is to have smaller path.
struct CompareKnapsackSearchNodePtrInDecreasingUpperBoundOrder {
  bool operator()(const KnapsackSearchNode* node_1,
                  const KnapsackSearchNode* node_2) const {
    const int64 profit_upper_bound_1 = node_1->profit_upper_bound();
    const int64 profit_upper_bound_2 = node_2->profit_upper_bound();
    if (profit_upper_bound_1 == profit_upper_bound_2) {
      return node_1->current_profit() < node_2->current_profit();
    }
    return profit_upper_bound_1 < profit_upper_bound_2;
  }
};

typedef std::priority_queue<KnapsackSearchNode*, std::vector<KnapsackSearchNode*>,
                       CompareKnapsackSearchNodePtrInDecreasingUpperBoundOrder>
    SearchQueue;

// Returns true when value_1 * value_2 may overflow int64.
inline bool WillProductOverflow(int64 value_1, int64 value_2) {
  const int MostSignificantBitPosition1 = MostSignificantBitPosition64(value_1);
  const int MostSignificantBitPosition2 = MostSignificantBitPosition64(value_2);
  // The sum should be less than 61 to be safe as we are only considering the
  // most significant bit and dealing with int64 instead of uint64.
  const int kOverflow = 61;
  return MostSignificantBitPosition1 + MostSignificantBitPosition2 > kOverflow;
}

// Returns an upper bound of (numerator_1 * numerator_2) / denominator
int64 UpperBoundOfRatio(int64 numerator_1, int64 numerator_2,
                        int64 denominator) {
  DCHECK_GT(denominator, 0LL);
  if (!WillProductOverflow(numerator_1, numerator_2)) {
    const int64 numerator = numerator_1 * numerator_2;
    // Round to zero.
    const int64 result = numerator / denominator;
    return result;
  } else {
    const double ratio =
        (static_cast<double>(numerator_1) * static_cast<double>(numerator_2)) /
        static_cast<double>(denominator);
    // Round near.
    const int64 result = static_cast<int64>(floor(ratio + 0.5));
    return result;
  }
}

}  // local namespace

// ----- KnapsackSearchNode -----
KnapsackSearchNode::KnapsackSearchNode(const KnapsackSearchNode* const parent,
                                       const KnapsackAssignment& assignment)
    : depth_((parent == NULL) ? 0 : parent->depth() + 1),
      parent_(parent),
      assignment_(assignment),
      current_profit_(0),
      profit_upper_bound_(kint64max),
      next_item_id_(kNoSelection) {}

// ----- KnapsackSearchPath -----
KnapsackSearchPath::KnapsackSearchPath(const KnapsackSearchNode& from,
                                       const KnapsackSearchNode& to)
    : from_(from), via_(NULL), to_(to) {}

void KnapsackSearchPath::Init() {
  const KnapsackSearchNode* node_from = MoveUpToDepth(from_, to_.depth());
  const KnapsackSearchNode* node_to = MoveUpToDepth(to_, from_.depth());
  CHECK_EQ(node_from->depth(), node_to->depth());

  // Find common parent.
  while (node_from != node_to) {
    node_from = node_from->parent();
    node_to = node_to->parent();
  }
  via_ = node_from;
}

const KnapsackSearchNode* KnapsackSearchPath::MoveUpToDepth(
    const KnapsackSearchNode& node, int depth) const {
  const KnapsackSearchNode* current_node = &node;
  while (current_node->depth() > depth) {
    current_node = current_node->parent();
  }
  return current_node;
}

// ----- KnapsackState -----
KnapsackState::KnapsackState() : is_bound_(), is_in_() {}

void KnapsackState::Init(int number_of_items) {
  is_bound_.assign(number_of_items, false);
  is_in_.assign(number_of_items, false);
}

// Returns false when the state is invalid.
bool KnapsackState::UpdateState(bool revert,
                                const KnapsackAssignment& assignment) {
  if (revert) {
    is_bound_[assignment.item_id] = false;
  } else {
    if (is_bound_[assignment.item_id] &&
        is_in_[assignment.item_id] != assignment.is_in) {
      return false;
    }
    is_bound_[assignment.item_id] = true;
    is_in_[assignment.item_id] = assignment.is_in;
  }
  return true;
}

// ----- KnapsackPropagator -----
KnapsackPropagator::KnapsackPropagator(const KnapsackState& state)
    : items_(),
      current_profit_(0),
      profit_lower_bound_(0),
      profit_upper_bound_(kint64max),
      state_(state) {}

KnapsackPropagator::~KnapsackPropagator() { STLDeleteElements(&items_); }

void KnapsackPropagator::Init(const std::vector<int64>& profits,
                              const std::vector<int64>& weights) {
  const int number_of_items = profits.size();
  items_.assign(number_of_items, static_cast<KnapsackItemPtr>(NULL));
  for (int i = 0; i < number_of_items; ++i) {
    items_[i] = new KnapsackItem(i, weights[i], profits[i]);
  }
  current_profit_ = 0;
  profit_lower_bound_ = kint64min;
  profit_upper_bound_ = kint64max;
  InitPropagator();
}

bool KnapsackPropagator::Update(bool revert,
                                const KnapsackAssignment& assignment) {
  if (assignment.is_in) {
    if (revert) {
      current_profit_ -= items_[assignment.item_id]->profit;
    } else {
      current_profit_ += items_[assignment.item_id]->profit;
    }
  }
  return UpdatePropagator(revert, assignment);
}

void KnapsackPropagator::CopyCurrentStateToSolution(
    bool has_one_propagator, std::vector<bool>* solution) const {
  CHECK_NOTNULL(solution);
  for (const KnapsackItem* const item : items_) {
    const int item_id = item->id;
    (*solution)[item_id] = state_.is_bound(item_id) && state_.is_in(item_id);
  }
  if (has_one_propagator) {
    CopyCurrentStateToSolutionPropagator(solution);
  }
}

// ----- KnapsackCapacityPropagator -----
KnapsackCapacityPropagator::KnapsackCapacityPropagator(
    const KnapsackState& state, int64 capacity)
    : KnapsackPropagator(state),
      capacity_(capacity),
      consumed_capacity_(0),
      break_item_id_(kNoSelection),
      sorted_items_(),
      profit_max_(0) {}

KnapsackCapacityPropagator::~KnapsackCapacityPropagator() {}

// TODO(user): Make it more incremental, by saving the break item in a
// search node for instance.
void KnapsackCapacityPropagator::ComputeProfitBounds() {
  set_profit_lower_bound(current_profit());
  break_item_id_ = kNoSelection;

  int64 remaining_capacity = capacity_ - consumed_capacity_;
  int break_sorted_item_id = kNoSelection;
  const int number_of_sorted_items = sorted_items_.size();
  for (int sorted_id = 0; sorted_id < number_of_sorted_items; ++sorted_id) {
    const KnapsackItem* const item = sorted_items_[sorted_id];
    if (!state().is_bound(item->id)) {
      break_item_id_ = item->id;

      if (remaining_capacity >= item->weight) {
        remaining_capacity -= item->weight;
        set_profit_lower_bound(profit_lower_bound() + item->profit);
      } else {
        break_sorted_item_id = sorted_id;
        break;
      }
    }
  }

  set_profit_upper_bound(profit_lower_bound());

  if (break_sorted_item_id != kNoSelection) {
    const int64 additional_profit =
        GetAdditionalProfit(remaining_capacity, break_sorted_item_id);
    set_profit_upper_bound(profit_upper_bound() + additional_profit);
  }
}

void KnapsackCapacityPropagator::InitPropagator() {
  consumed_capacity_ = 0;
  break_item_id_ = kNoSelection;
  sorted_items_ = items();
  profit_max_ = 0;
  for (const KnapsackItem* const item : sorted_items_) {
    profit_max_ = std::max(profit_max_, item->profit);
  }
  ++profit_max_;
  CompareKnapsackItemsInDecreasingEfficiencyOrder compare_object(profit_max_);
  std::sort(sorted_items_.begin(), sorted_items_.end(), compare_object);
}

// Returns false when the propagator fails.
bool KnapsackCapacityPropagator::UpdatePropagator(
    bool revert, const KnapsackAssignment& assignment) {
  if (assignment.is_in) {
    if (revert) {
      consumed_capacity_ -= items()[assignment.item_id]->weight;
    } else {
      consumed_capacity_ += items()[assignment.item_id]->weight;
      if (consumed_capacity_ > capacity_) {
        return false;
      }
    }
  }
  return true;
}

void KnapsackCapacityPropagator::CopyCurrentStateToSolutionPropagator(
    std::vector<bool>* solution) const {
  CHECK_NOTNULL(solution);
  int64 remaining_capacity = capacity_ - consumed_capacity_;
  for (const KnapsackItem* const item : sorted_items_) {
    if (!state().is_bound(item->id)) {
      if (remaining_capacity >= item->weight) {
        remaining_capacity -= item->weight;
        (*solution)[item->id] = true;
      } else {
        return;
      }
    }
  }
}

int64 KnapsackCapacityPropagator::GetAdditionalProfit(int64 remaining_capacity,
                                                      int break_item_id) const {
  const int after_break_item_id = break_item_id + 1;
  int64 additional_profit_when_no_break_item = 0;
  if (after_break_item_id < sorted_items_.size()) {
    // As items are sorted by decreasing profit / weight ratio, and the current
    // weight is non-zero, the next_weight is non-zero too.
    const int64 next_weight = sorted_items_[after_break_item_id]->weight;
    const int64 next_profit = sorted_items_[after_break_item_id]->profit;
    additional_profit_when_no_break_item =
        UpperBoundOfRatio(remaining_capacity, next_profit, next_weight);
  }

  const int before_break_item_id = break_item_id - 1;
  int64 additional_profit_when_break_item = 0;
  if (before_break_item_id >= 0) {
    const int64 previous_weight = sorted_items_[before_break_item_id]->weight;
    // Having previous_weight == 0 means the total capacity is smaller than
    // the weight of the current item. In such a case the item cannot be part
    // of a solution of the local one dimension problem.
    if (previous_weight != 0) {
      const int64 previous_profit = sorted_items_[before_break_item_id]->profit;
      const int64 overused_capacity =
          sorted_items_[break_item_id]->weight - remaining_capacity;
      const int64 ratio = UpperBoundOfRatio(overused_capacity, previous_profit,
                                            previous_weight);
      additional_profit_when_break_item =
          sorted_items_[break_item_id]->profit - ratio;
    }
  }

  const int64 additional_profit = std::max(additional_profit_when_no_break_item,
                                      additional_profit_when_break_item);
  CHECK_GE(additional_profit, 0);
  return additional_profit;
}

// ----- KnapsackGenericSolver -----
KnapsackGenericSolver::KnapsackGenericSolver(const std::string& solver_name)
    : BaseKnapsackSolver(solver_name),
      propagators_(),
      master_propagator_id_(kMasterPropagatorId),
      search_nodes_(),
      state_(),
      best_solution_profit_(0),
      best_solution_() {}

KnapsackGenericSolver::~KnapsackGenericSolver() { Clear(); }

void KnapsackGenericSolver::Init(const std::vector<int64>& profits,
                                 const std::vector<std::vector<int64> >& weights,
                                 const std::vector<int64>& capacities) {
  CHECK_EQ(capacities.size(), weights.size());

  Clear();
  const int number_of_items = profits.size();
  const int number_of_dimensions = weights.size();
  state_.Init(number_of_items);
  best_solution_.assign(number_of_items, false);
  for (int i = 0; i < number_of_dimensions; ++i) {
    CHECK_EQ(number_of_items, weights[i].size());

    KnapsackCapacityPropagator* propagator =
        new KnapsackCapacityPropagator(state_, capacities[i]);
    propagator->Init(profits, weights[i]);
    propagators_.push_back(propagator);
  }
  master_propagator_id_ = kMasterPropagatorId;
}

void KnapsackGenericSolver::GetLowerAndUpperBoundWhenItem(int item_id,
                                                          bool is_item_in,
                                                          int64* lower_bound,
                                                          int64* upper_bound) {
  CHECK_NOTNULL(lower_bound);
  CHECK_NOTNULL(upper_bound);
  KnapsackAssignment assignment(item_id, is_item_in);
  const bool fail = !IncrementalUpdate(false, assignment);
  if (fail) {
    *lower_bound = 0LL;
    *upper_bound = 0LL;
  } else {
    *lower_bound = (HasOnePropagator()) ? propagators_[master_propagator_id_]
                                              ->profit_lower_bound()
                                        : 0LL;
    *upper_bound = GetAggregatedProfitUpperBound();
  }

  const bool fail_revert = !IncrementalUpdate(true, assignment);
  if (fail_revert) {
    *lower_bound = 0LL;
    *upper_bound = 0LL;
  }
}

int64 KnapsackGenericSolver::Solve() {
  best_solution_profit_ = 0LL;

  SearchQueue search_queue;
  const KnapsackAssignment assignment(kNoSelection, true);
  KnapsackSearchNode* root_node = new KnapsackSearchNode(NULL, assignment);
  root_node->set_current_profit(GetCurrentProfit());
  root_node->set_profit_upper_bound(GetAggregatedProfitUpperBound());
  root_node->set_next_item_id(GetNextItemId());
  search_nodes_.push_back(root_node);

  if (MakeNewNode(*root_node, false)) {
    search_queue.push(search_nodes_.back());
  }
  if (MakeNewNode(*root_node, true)) {
    search_queue.push(search_nodes_.back());
  }

  KnapsackSearchNode* current_node = root_node;
  while (!search_queue.empty() &&
         search_queue.top()->profit_upper_bound() > best_solution_profit_) {
    KnapsackSearchNode* const node = search_queue.top();
    search_queue.pop();

    if (node != current_node) {
      KnapsackSearchPath path(*current_node, *node);
      path.Init();
      const bool no_fail = UpdatePropagators(path);
      current_node = node;
      CHECK_EQ(no_fail, true);
    }

    if (MakeNewNode(*node, false)) {
      search_queue.push(search_nodes_.back());
    }
    if (MakeNewNode(*node, true)) {
      search_queue.push(search_nodes_.back());
    }
  }
  return best_solution_profit_;
}

void KnapsackGenericSolver::Clear() {
  STLDeleteElements(&propagators_);
  STLDeleteElements(&search_nodes_);
}

// Returns false when at least one propagator fails.
bool KnapsackGenericSolver::UpdatePropagators(const KnapsackSearchPath& path) {
  bool no_fail = true;
  // Revert previous changes.
  const KnapsackSearchNode* node = &path.from();
  const KnapsackSearchNode* via = &path.via();
  while (node != via) {
    no_fail = IncrementalUpdate(true, node->assignment()) && no_fail;
    node = node->parent();
  }
  // Apply current changes.
  node = &path.to();
  while (node != via) {
    no_fail = IncrementalUpdate(false, node->assignment()) && no_fail;
    node = node->parent();
  }
  return no_fail;
}

int64 KnapsackGenericSolver::GetAggregatedProfitUpperBound() const {
  int64 upper_bound = kint64max;
  for (KnapsackPropagator* const prop : propagators_) {
    prop->ComputeProfitBounds();
    const int64 propagator_upper_bound = prop->profit_upper_bound();
    upper_bound = std::min(upper_bound, propagator_upper_bound);
  }
  return upper_bound;
}

bool KnapsackGenericSolver::MakeNewNode(const KnapsackSearchNode& node,
                                        bool is_in) {
  if (node.next_item_id() == kNoSelection) {
    return false;
  }
  KnapsackAssignment assignment(node.next_item_id(), is_in);
  KnapsackSearchNode new_node(&node, assignment);

  KnapsackSearchPath path(node, new_node);
  path.Init();
  const bool no_fail = UpdatePropagators(path);
  if (no_fail) {
    new_node.set_current_profit(GetCurrentProfit());
    new_node.set_profit_upper_bound(GetAggregatedProfitUpperBound());
    new_node.set_next_item_id(GetNextItemId());
    UpdateBestSolution();
  }

  // Revert to be able to create another node from parent.
  KnapsackSearchPath revert_path(new_node, node);
  revert_path.Init();
  UpdatePropagators(revert_path);

  if (!no_fail || new_node.profit_upper_bound() < best_solution_profit_) {
    return false;
  }

  // The node is relevant.
  KnapsackSearchNode* relevant_node = new KnapsackSearchNode(&node, assignment);
  relevant_node->set_current_profit(new_node.current_profit());
  relevant_node->set_profit_upper_bound(new_node.profit_upper_bound());
  relevant_node->set_next_item_id(new_node.next_item_id());
  search_nodes_.push_back(relevant_node);

  return true;
}

bool KnapsackGenericSolver::IncrementalUpdate(
    bool revert, const KnapsackAssignment& assignment) {
  // Do not stop on a failure: To be able to be incremental on the update,
  // partial solution (state) and propagators must all be in the same state.
  bool no_fail = state_.UpdateState(revert, assignment);
  for (KnapsackPropagator* const prop : propagators_) {
    no_fail = prop->Update(revert, assignment) && no_fail;
  }
  return no_fail;
}

void KnapsackGenericSolver::UpdateBestSolution() {
  const int64 profit_lower_bound =
      (HasOnePropagator())
          ? propagators_[master_propagator_id_]->profit_lower_bound()
          : propagators_[master_propagator_id_]->current_profit();

  if (best_solution_profit_ < profit_lower_bound) {
    best_solution_profit_ = profit_lower_bound;
    propagators_[master_propagator_id_]
        ->CopyCurrentStateToSolution(HasOnePropagator(), &best_solution_);
  }
}

// ----- KnapsackBruteForceSolver -----
// KnapsackBruteForceSolver solves the 0-1 knapsack problem when the number of
// items is less or equal to 30 with brute force, ie. explores all states.
// Experiments show better results than KnapsackGenericSolver when the
// number of items is less than 15.
class KnapsackBruteForceSolver : public BaseKnapsackSolver {
 public:
  explicit KnapsackBruteForceSolver(const std::string& solver_name);

  // Initializes the solver and enters the problem to be solved.
  void Init(const std::vector<int64>& profits, const std::vector<std::vector<int64> >& weights,
            const std::vector<int64>& capacities);

  // Solves the problem and returns the profit of the optimal solution.
  int64 Solve();

  // Returns true if the item 'item_id' is packed in the optimal knapsack.
  bool best_solution(int item_id) const {
    return (best_solution_ & OneBit32(item_id)) != 0U;
  }

 private:
  int num_items_;
  int64 profits_weights_[kMaxNumberOfBruteForceItems * 2];
  int64 capacity_;
  int64 best_solution_profit_;
  uint32 best_solution_;

  DISALLOW_COPY_AND_ASSIGN(KnapsackBruteForceSolver);
};

KnapsackBruteForceSolver::KnapsackBruteForceSolver(const std::string& solver_name)
    : BaseKnapsackSolver(solver_name),
      num_items_(0),
      capacity_(0LL),
      best_solution_profit_(0LL),
      best_solution_(0U) {}

void KnapsackBruteForceSolver::Init(const std::vector<int64>& profits,
                                    const std::vector<std::vector<int64> >& weights,
                                    const std::vector<int64>& capacities) {
  // TODO(user): Implement multi-dimensional brute force solver.
  CHECK_EQ(weights.size(), 1)
      << "Brute force solver only works with one dimension.";
  CHECK_EQ(capacities.size(), weights.size());

  num_items_ = profits.size();
  CHECK_EQ(num_items_, weights.at(0).size());
  CHECK_LE(num_items_, kMaxNumberOfBruteForceItems)
      << "To use KnapsackBruteForceSolver the number of items should be "
      << "less than " << kMaxNumberOfBruteForceItems
      << ". Current value: " << num_items_ << ".";

  for (int i = 0; i < num_items_; ++i) {
    profits_weights_[i * 2] = profits.at(i);
    profits_weights_[i * 2 + 1] = weights.at(0).at(i);
  }
  capacity_ = capacities.at(0);
}

int64 KnapsackBruteForceSolver::Solve() {
  best_solution_profit_ = 0LL;
  best_solution_ = 0U;

  const uint32 num_states = OneBit32(num_items_);
  uint32 prev_state = 0U;
  uint64 sum_profit = 0ULL;
  uint64 sum_weight = 0ULL;
  uint32 diff_state = 0U;
  uint32 local_state = 0U;
  int item_id = 0;
  // This loop starts at 1, because state = 0 was already considered previously,
  // ie. when no items are in, sum_profit = 0.
  for (uint32 state = 1U; state < num_states; ++state, ++prev_state) {
    diff_state = state ^ prev_state;
    local_state = state;
    item_id = 0;
    while (diff_state) {
      if (diff_state & 1U) {     // There is a diff.
        if (local_state & 1U) {  // This item is now in the knapsack.
          sum_profit += profits_weights_[item_id];
          sum_weight += profits_weights_[item_id + 1];
          CHECK_LT(item_id + 1, 2 * num_items_);
        } else {  // This item has been removed of the knapsack.
          sum_profit -= profits_weights_[item_id];
          sum_weight -= profits_weights_[item_id + 1];
          CHECK_LT(item_id + 1, 2 * num_items_);
        }
      }
      item_id += 2;
      local_state = local_state >> 1;
      diff_state = diff_state >> 1;
    }

    if (sum_weight <= capacity_ && best_solution_profit_ < sum_profit) {
      best_solution_profit_ = sum_profit;
      best_solution_ = state;
    }
  }

  return best_solution_profit_;
}

// ----- KnapsackItemWithEfficiency -----
// KnapsackItem is a small struct to pair an item weight with its
// corresponding profit.
// This struct is used by Knapsack64ItemsSolver. As this solver deals only
// with one dimension, that's more efficient to store 'efficiency' than
// computing it on the fly.
struct KnapsackItemWithEfficiency {
  KnapsackItemWithEfficiency(int _id, int64 _profit, int64 _weight,
                             int64 _profit_max)
      : id(_id),
        profit(_profit),
        weight(_weight),
        efficiency((weight > 0) ? static_cast<double>(_profit) /
                                      static_cast<double>(_weight)
                                : static_cast<double>(_profit_max)) {}

  int id;
  int64 profit;
  int64 weight;
  double efficiency;
};

// ----- Knapsack64ItemsSolver -----
// Knapsack64ItemsSolver solves the 0-1 knapsack problem when the number of
// items is less or equal to 64. This implementation is about 4 times faster
// than KnapsackGenericSolver.
class Knapsack64ItemsSolver : public BaseKnapsackSolver {
 public:
  explicit Knapsack64ItemsSolver(const std::string& solver_name);

  // Initializes the solver and enters the problem to be solved.
  void Init(const std::vector<int64>& profits, const std::vector<std::vector<int64> >& weights,
            const std::vector<int64>& capacities);

  // Solves the problem and returns the profit of the optimal solution.
  int64 Solve();

  // Returns true if the item 'item_id' is packed in the optimal knapsack.
  bool best_solution(int item_id) const {
    return (best_solution_ & OneBit64(item_id)) != 0ULL;
  }

 private:
  int GetBreakItemId(int64 capacity) const;
  void GetLowerAndUpperBound(int64* lower_bound, int64* upper_bound) const;
  void GoToNextState(bool has_failed);
  void BuildBestSolution();

  std::vector<KnapsackItemWithEfficiency> sorted_items_;
  std::vector<int64> sum_profits_;
  std::vector<int64> sum_weights_;
  int64 capacity_;
  uint64 state_;
  int state_depth_;

  int64 best_solution_profit_;
  uint64 best_solution_;
  int best_solution_depth_;

  // Sum of weights of included item in state.
  int64 state_weight_;
  // Sum of profits of non included items in state.
  int64 rejected_items_profit_;
  // Sum of weights of non included items in state.
  int64 rejected_items_weight_;
};

// Comparator used to sort item in decreasing efficiency order
bool CompareKnapsackItemWithEfficiencyInDecreasingEfficiencyOrder(
    const KnapsackItemWithEfficiency& item1,
    const KnapsackItemWithEfficiency& item2) {
  return item1.efficiency > item2.efficiency;
}

// ----- Knapsack64ItemsSolver -----
Knapsack64ItemsSolver::Knapsack64ItemsSolver(const std::string& solver_name)
    : BaseKnapsackSolver(solver_name),
      sorted_items_(),
      sum_profits_(),
      sum_weights_(),
      capacity_(0LL),
      state_(0ULL),
      state_depth_(0),
      best_solution_profit_(0LL),
      best_solution_(0ULL),
      best_solution_depth_(0),
      state_weight_(0LL),
      rejected_items_profit_(0LL),
      rejected_items_weight_(0LL) {}

void Knapsack64ItemsSolver::Init(const std::vector<int64>& profits,
                                 const std::vector<std::vector<int64> >& weights,
                                 const std::vector<int64>& capacities) {
  CHECK_EQ(weights.size(), 1)
      << "Brute force solver only works with one dimension.";
  CHECK_EQ(capacities.size(), weights.size());

  sorted_items_.clear();
  sum_profits_.clear();
  sum_weights_.clear();

  capacity_ = capacities[0];
  const int num_items = profits.size();
  CHECK_LE(num_items, kMaxNumberOf64Items)
      << "To use Knapsack64ItemsSolver the number of items should be "
      << "less than " << kMaxNumberOf64Items << ". Current value: " << num_items
      << ".";
  int64 profit_max = *std::max_element(profits.begin(), profits.end());

  for (int i = 0; i < num_items; ++i) {
    sorted_items_.push_back(
        KnapsackItemWithEfficiency(i, profits[i], weights[0][i], profit_max));
  }

  std::sort(sorted_items_.begin(), sorted_items_.end(),
            CompareKnapsackItemWithEfficiencyInDecreasingEfficiencyOrder);

  int64 sum_profit = 0;
  int64 sum_weight = 0;
  sum_profits_.push_back(sum_profit);
  sum_weights_.push_back(sum_weight);
  for (int i = 0; i < num_items; ++i) {
    sum_profit += sorted_items_[i].profit;
    sum_weight += sorted_items_[i].weight;

    sum_profits_.push_back(sum_profit);
    sum_weights_.push_back(sum_weight);
  }
}

int64 Knapsack64ItemsSolver::Solve() {
  const int num_items = sorted_items_.size();
  state_ = 1ULL;
  state_depth_ = 0;
  state_weight_ = sorted_items_[0].weight;
  rejected_items_profit_ = 0LL;
  rejected_items_weight_ = 0LL;
  best_solution_profit_ = 0LL;
  best_solution_ = 0ULL;
  best_solution_depth_ = 0;

  int64 lower_bound = 0LL;
  int64 upper_bound = 0LL;
  bool fail = false;
  while (state_depth_ >= 0) {
    fail = false;
    if (state_weight_ > capacity_ || state_depth_ >= num_items) {
      fail = true;
    } else {
      GetLowerAndUpperBound(&lower_bound, &upper_bound);
      if (best_solution_profit_ < lower_bound) {
        best_solution_profit_ = lower_bound;
        best_solution_ = state_;
        best_solution_depth_ = state_depth_;
      }
    }
    fail = fail || best_solution_profit_ >= upper_bound;
    GoToNextState(fail);
  }

  BuildBestSolution();
  return best_solution_profit_;
}

int Knapsack64ItemsSolver::GetBreakItemId(int64 capacity) const {
  std::vector<int64>::const_iterator binary_search_iterator =
      std::upper_bound(sum_weights_.begin(), sum_weights_.end(), capacity);
  return static_cast<int>(binary_search_iterator - sum_weights_.begin()) - 1;
}

// This method is called for each possible state.
// Lower and upper bounds can be equal from one state to another.
// For instance state 1010???? and state 101011?? have exactly the same
// bounds. So it sounds like a good idea to cache those bounds.
// Unfortunately, experiments show equivalent results with or without this
// code optimization (only 1/7 of calls can be reused).
// In order to simplify the code, this optimization is not implemented.
void Knapsack64ItemsSolver::GetLowerAndUpperBound(int64* lower_bound,
                                                  int64* upper_bound) const {
  const int64 available_capacity = capacity_ + rejected_items_weight_;
  const int break_item_id = GetBreakItemId(available_capacity);
  const int num_items = sorted_items_.size();
  if (break_item_id >= num_items) {
    *lower_bound = sum_profits_[num_items] - rejected_items_profit_;
    *upper_bound = *lower_bound;
    return;
  }

  *lower_bound = sum_profits_[break_item_id] - rejected_items_profit_;
  *upper_bound = *lower_bound;
  const int64 consumed_capacity = sum_weights_[break_item_id];
  const int64 remaining_capacity = available_capacity - consumed_capacity;
  const double efficiency = sorted_items_[break_item_id].efficiency;
  const int64 additional_profit =
      static_cast<int64>(remaining_capacity * efficiency);
  *upper_bound += additional_profit;
}

// As state_depth_ is the position of the most significant bit on state_
// it is possible to remove the loop and so be in O(1) instead of O(depth).
// In such a case rejected_items_profit_ is computed using sum_profits_ array.
// Unfortunately experiments show smaller computation time using the 'while'
// (10% speed-up). That's the reason why the loop version is implemented.
void Knapsack64ItemsSolver::GoToNextState(bool has_failed) {
  uint64 mask = OneBit64(state_depth_);
  if (!has_failed) {  // Go to next item.
    ++state_depth_;
    state_ = state_ | (mask << 1);
    state_weight_ += sorted_items_[state_depth_].weight;
  } else {
    // Backtrack to last item in.
    while ((state_ & mask) == 0ULL && state_depth_ >= 0) {
      const KnapsackItemWithEfficiency& item = sorted_items_[state_depth_];
      rejected_items_profit_ -= item.profit;
      rejected_items_weight_ -= item.weight;
      --state_depth_;
      mask = mask >> 1ULL;
    }

    if (state_ & mask) {  // Item was in, remove it.
      state_ = state_ & ~mask;
      const KnapsackItemWithEfficiency& item = sorted_items_[state_depth_];
      rejected_items_profit_ += item.profit;
      rejected_items_weight_ += item.weight;
      state_weight_ -= item.weight;
    }
  }
}

void Knapsack64ItemsSolver::BuildBestSolution() {
  int64 remaining_capacity = capacity_;
  int64 check_profit = 0LL;

  // Compute remaining capacity at best_solution_depth_ to be able to redo
  // the GetLowerAndUpperBound computation.
  for (int i = 0; i <= best_solution_depth_; ++i) {
    if (best_solution_ & OneBit64(i)) {
      remaining_capacity -= sorted_items_[i].weight;
      check_profit += sorted_items_[i].profit;
    }
  }

  // Add all items till the break item.
  const int num_items = sorted_items_.size();
  for (int i = best_solution_depth_ + 1; i < num_items; ++i) {
    int64 weight = sorted_items_[i].weight;
    if (remaining_capacity >= weight) {
      remaining_capacity -= weight;
      check_profit += sorted_items_[i].profit;
      best_solution_ = best_solution_ | OneBit64(i);
    } else {
      best_solution_ = best_solution_ & ~OneBit64(i);
    }
  }
  CHECK_EQ(best_solution_profit_, check_profit);

  // Items were sorted by efficiency, solution should be unsorted to be
  // in user order.
  // Note that best_solution_ will not be in the same order than other data
  // structures anymore.
  uint64 tmp_solution = 0ULL;
  for (int i = 0; i < num_items; ++i) {
    if (best_solution_ & OneBit64(i)) {
      const int original_id = sorted_items_[i].id;
      tmp_solution = tmp_solution | OneBit64(original_id);
    }
  }

  best_solution_ = tmp_solution;
}

// ----- KnapsackDynamicProgrammingSolver -----
// KnapsackDynamicProgrammingSolver solves the 0-1 knapsack problem
// using dynamic programming. This algorithm is pseudo-polynomial because it
// depends on capacity, ie. the time and space complexity is
// O(capacity * number_of_items).
// The implemented algorithm is 'DP-3' in "Knapsack problems", Hans Kellerer,
// Ulrich Pferschy and David Pisinger, Springer book (ISBN 978-3540402862).
class KnapsackDynamicProgrammingSolver : public BaseKnapsackSolver {
 public:
  explicit KnapsackDynamicProgrammingSolver(const std::string& solver_name);

  // Initializes the solver and enters the problem to be solved.
  void Init(const std::vector<int64>& profits, const std::vector<std::vector<int64> >& weights,
            const std::vector<int64>& capacities);

  // Solves the problem and returns the profit of the optimal solution.
  int64 Solve();

  // Returns true if the item 'item_id' is packed in the optimal knapsack.
  bool best_solution(int item_id) const { return best_solution_.at(item_id); }

 private:
  int64 SolveSubProblem(int64 capacity, int num_items);

  std::vector<int64> profits_;
  std::vector<int64> weights_;
  int64 capacity_;
  std::vector<int64> computed_profits_;
  std::vector<int> selected_item_ids_;
  std::vector<bool> best_solution_;
};

// ----- KnapsackDynamicProgrammingSolver -----
KnapsackDynamicProgrammingSolver::KnapsackDynamicProgrammingSolver(
    const std::string& solver_name)
    : BaseKnapsackSolver(solver_name),
      profits_(),
      weights_(),
      capacity_(0),
      computed_profits_(),
      selected_item_ids_(),
      best_solution_() {}

void KnapsackDynamicProgrammingSolver::Init(
    const std::vector<int64>& profits, const std::vector<std::vector<int64> >& weights,
    const std::vector<int64>& capacities) {
  CHECK_EQ(weights.size(), 1)
      << "Current implementation of the dynamic programming solver only deals"
      << " with one dimension.";
  CHECK_EQ(capacities.size(), weights.size());

  profits_ = profits;
  weights_ = weights[0];
  capacity_ = capacities[0];
}

int64 KnapsackDynamicProgrammingSolver::SolveSubProblem(int64 capacity,
                                                        int num_items) {
  const int64 capacity_plus_1 = capacity + 1;
  std::fill_n(selected_item_ids_.begin(), capacity_plus_1, 0);
  std::fill_n(computed_profits_.begin(), capacity_plus_1, 0LL);
  for (int item_id = 0; item_id < num_items; ++item_id) {
    const int64 item_weight = weights_[item_id];
    const int64 item_profit = profits_[item_id];
    for (int64 used_capacity = capacity; used_capacity >= item_weight;
         --used_capacity) {
      if (computed_profits_[used_capacity - item_weight] + item_profit >
          computed_profits_[used_capacity]) {
        computed_profits_[used_capacity] =
            computed_profits_[used_capacity - item_weight] + item_profit;
        selected_item_ids_[used_capacity] = item_id;
      }
    }
  }
  return selected_item_ids_.at(capacity);
}

int64 KnapsackDynamicProgrammingSolver::Solve() {
  const int64 capacity_plus_1 = capacity_ + 1;
  selected_item_ids_.assign(capacity_plus_1, 0);
  computed_profits_.assign(capacity_plus_1, 0LL);

  int64 remaining_capacity = capacity_;
  int num_items = profits_.size();
  best_solution_.assign(num_items, false);

  while (remaining_capacity > 0 && num_items > 0) {
    const int selected_item_id = SolveSubProblem(remaining_capacity, num_items);
    remaining_capacity -= weights_[selected_item_id];
    num_items = selected_item_id;
    if (remaining_capacity >= 0) {
      best_solution_[selected_item_id] = true;
    }
  }

  return computed_profits_[capacity_];
}

// ----- KnapsackMIPSolver -----
class KnapsackMIPSolver : public BaseKnapsackSolver {
 public:
  KnapsackMIPSolver(MPSolver::OptimizationProblemType problem_type,
                    const std::string& solver_name);

  // Initializes the solver and enters the problem to be solved.
  void Init(const std::vector<int64>& profits, const std::vector<std::vector<int64> >& weights,
            const std::vector<int64>& capacities);

  // Solves the problem and returns the profit of the optimal solution.
  int64 Solve();

  // Returns true if the item 'item_id' is packed in the optimal knapsack.
  bool best_solution(int item_id) const { return best_solution_.at(item_id); }

 private:
  MPSolver::OptimizationProblemType problem_type_;
  std::vector<int64> profits_;
  std::vector<std::vector<int64> > weights_;
  std::vector<int64> capacities_;
  std::vector<bool> best_solution_;
};

KnapsackMIPSolver::KnapsackMIPSolver(
    MPSolver::OptimizationProblemType problem_type, const std::string& solver_name)
    : BaseKnapsackSolver(solver_name),
      problem_type_(problem_type),
      profits_(),
      weights_(),
      capacities_(),
      best_solution_() {}

void KnapsackMIPSolver::Init(const std::vector<int64>& profits,
                             const std::vector<std::vector<int64> >& weights,
                             const std::vector<int64>& capacities) {
  profits_ = profits;
  weights_ = weights;
  capacities_ = capacities;
}

int64 KnapsackMIPSolver::Solve() {
  MPSolver solver(GetName(), problem_type_);

  const int num_items = profits_.size();
  std::vector<MPVariable*> variables;
  solver.MakeBoolVarArray(num_items, "x", &variables);

  // Add constraints.
  const int num_dimensions = capacities_.size();
  for (int i = 0; i < num_dimensions; ++i) {
    MPConstraint* const ct = solver.MakeRowConstraint(0LL, capacities_.at(i));
    for (int j = 0; j < num_items; ++j) {
      ct->SetCoefficient(variables.at(j), weights_.at(i).at(j));
    }
  }

  // Define objective to minimize. Minimization is used instead of maximization
  // because of an issue with CBC solver which does not always find the optimal
  // solution on maximization problems.
  MPObjective* const objective = solver.MutableObjective();
  for (int j = 0; j < num_items; ++j) {
    objective->SetCoefficient(variables.at(j), -profits_.at(j));
  }
  objective->SetMinimization();

  solver.SuppressOutput();
  solver.Solve();

  // Store best solution.
  const float kRoundNear = 0.5;
  best_solution_.assign(num_items, false);
  for (int j = 0; j < num_items; ++j) {
    const double value = variables.at(j)->solution_value();
    best_solution_.at(j) = value >= kRoundNear;
  }

  return -objective->Value() + kRoundNear;
}

// ----- KnapsackSolver -----
KnapsackSolver::KnapsackSolver(const std::string& solver_name)
    : solver_(new KnapsackGenericSolver(solver_name)),
      known_value_(),
      best_solution_(),
      mapping_reduced_item_id_(),
      is_problem_solved_(false),
      additional_profit_(0LL),
      use_reduction_(true) {}

KnapsackSolver::KnapsackSolver(SolverType solver_type,
                               const std::string& solver_name)
    : solver_(),
      known_value_(),
      best_solution_(),
      mapping_reduced_item_id_(),
      is_problem_solved_(false),
      additional_profit_(0LL),
      use_reduction_(true) {
  switch (solver_type) {
    case KNAPSACK_BRUTE_FORCE_SOLVER:
      solver_.reset(new KnapsackBruteForceSolver(solver_name));
      break;
    case KNAPSACK_64ITEMS_SOLVER:
      solver_.reset(new Knapsack64ItemsSolver(solver_name));
      break;
    case KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER:
      solver_.reset(new KnapsackDynamicProgrammingSolver(solver_name));
      break;
    case KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER:
      solver_.reset(new KnapsackGenericSolver(solver_name));
      break;
    #if defined(USE_CBC)
    case KNAPSACK_MULTIDIMENSION_CBC_MIP_SOLVER:
      solver_.reset(new KnapsackMIPSolver(
          MPSolver::CBC_MIXED_INTEGER_PROGRAMMING, solver_name));
      break;
    #endif  // USE_CBC
    #if defined(USE_GLPK)
    case KNAPSACK_MULTIDIMENSION_GLPK_MIP_SOLVER:
      solver_.reset(new KnapsackMIPSolver(
          MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING, solver_name));
      break;
    #endif  // USE_GLPK
    default:
      LOG(FATAL) << "Unknown knapsack solver type.";
  }
}

KnapsackSolver::~KnapsackSolver() {}

void KnapsackSolver::Init(const std::vector<int64>& profits,
                          const std::vector<std::vector<int64> >& weights,
                          const std::vector<int64>& capacities) {
  additional_profit_ = 0LL;
  is_problem_solved_ = false;

  solver_->Init(profits, weights, capacities);
  if (use_reduction_) {
    const int num_items = profits.size();
    const int num_reduced_items = ReduceProblem(num_items);

    if (num_reduced_items > 0) {
      ComputeAdditionalProfit(profits);
    }

    if (num_reduced_items > 0 && num_reduced_items < num_items) {
      InitReducedProblem(profits, weights, capacities);
    }
  }
}

int KnapsackSolver::ReduceProblem(int num_items) {
  known_value_.assign(num_items, false);
  best_solution_.assign(num_items, false);
  mapping_reduced_item_id_.assign(num_items, 0);
  additional_profit_ = 0LL;

  for (int item_id = 0; item_id < num_items; ++item_id) {
    mapping_reduced_item_id_[item_id] = item_id;
  }

  int64 best_lower_bound = 0LL;
  std::vector<int64> J0_upper_bounds(num_items, kint64max);
  std::vector<int64> J1_upper_bounds(num_items, kint64max);
  for (int item_id = 0; item_id < num_items; ++item_id) {
    int64 lower_bound = 0LL;
    int64 upper_bound = kint64max;
    solver_->GetLowerAndUpperBoundWhenItem(item_id, false, &lower_bound,
                                           &upper_bound);
    J1_upper_bounds.at(item_id) = upper_bound;
    best_lower_bound = std::max(best_lower_bound, lower_bound);

    solver_->GetLowerAndUpperBoundWhenItem(item_id, true, &lower_bound,
                                           &upper_bound);
    J0_upper_bounds.at(item_id) = upper_bound;
    best_lower_bound = std::max(best_lower_bound, lower_bound);
  }

  int num_reduced_items = 0;
  for (int item_id = 0; item_id < num_items; ++item_id) {
    if (best_lower_bound > J0_upper_bounds[item_id]) {
      known_value_[item_id] = true;
      best_solution_[item_id] = false;
      ++num_reduced_items;
    } else if (best_lower_bound > J1_upper_bounds[item_id]) {
      known_value_[item_id] = true;
      best_solution_[item_id] = true;
      ++num_reduced_items;
    }
  }

  is_problem_solved_ = num_reduced_items == num_items;
  return num_reduced_items;
}

void KnapsackSolver::ComputeAdditionalProfit(const std::vector<int64>& profits) {
  const int num_items = profits.size();
  additional_profit_ = 0LL;
  for (int item_id = 0; item_id < num_items; ++item_id) {
    if (known_value_[item_id] && best_solution_[item_id]) {
      additional_profit_ += profits[item_id];
    }
  }
}

void KnapsackSolver::InitReducedProblem(const std::vector<int64>& profits,
                                        const std::vector<std::vector<int64> >& weights,
                                        const std::vector<int64>& capacities) {
  const int num_items = profits.size();
  const int num_dimensions = capacities.size();

  std::vector<int64> reduced_profits;
  for (int item_id = 0; item_id < num_items; ++item_id) {
    if (!known_value_[item_id]) {
      mapping_reduced_item_id_[item_id] = reduced_profits.size();
      reduced_profits.push_back(profits[item_id]);
    }
  }

  std::vector<std::vector<int64> > reduced_weights;
  std::vector<int64> reduced_capacities = capacities;
  for (int dim = 0; dim < num_dimensions; ++dim) {
    const std::vector<int64>& one_dimension_weights = weights[dim];
    std::vector<int64> one_dimension_reduced_weights;
    for (int item_id = 0; item_id < num_items; ++item_id) {
      if (known_value_[item_id]) {
        if (best_solution_[item_id]) {
          reduced_capacities[dim] -= one_dimension_weights[item_id];
        }
      } else {
        one_dimension_reduced_weights.push_back(one_dimension_weights[item_id]);
      }
    }
    reduced_weights.push_back(one_dimension_reduced_weights);
  }
  solver_->Init(reduced_profits, reduced_weights, reduced_capacities);
}

int64 KnapsackSolver::Solve() {
  return additional_profit_ + ((is_problem_solved_) ? 0 : solver_->Solve());
}

bool KnapsackSolver::BestSolutionContains(int item_id) const {
  const int mapped_item_id =
      (use_reduction_) ? mapping_reduced_item_id_[item_id] : item_id;
  return (use_reduction_ && known_value_[item_id])
             ? best_solution_[item_id]
             : solver_->best_solution(mapped_item_id);
}

std::string KnapsackSolver::GetName() const { return solver_->GetName(); }

// ----- BaseKnapsackSolver -----
void BaseKnapsackSolver::GetLowerAndUpperBoundWhenItem(int item_id,
                                                       bool is_item_in,
                                                       int64* lower_bound,
                                                       int64* upper_bound) {
  CHECK_NOTNULL(lower_bound);
  CHECK_NOTNULL(upper_bound);
  *lower_bound = 0LL;
  *upper_bound = kint64max;
}

}  // namespace operations_research


text:
//
//  UFConversation.h
//  XMPPDemo
//
//  Created by cyyun on 14-11-13.
//  Copyright (c) 2014年 cyyun. All rights reserved.
//

#import <Foundation/Foundation.h>
@class UFMessage;

@interface UFConversation : NSObject

/*!
 @property
 @brief 会话对方的用户名. 如果是群聊, 则是群组的id
 */
@property (nonatomic, strong) NSString *chatter;

/*!
 @property
 @brief 是否是群聊
 */
@property (nonatomic, assign) BOOL isGroup;

/*!
 @property
 @brief 此会话中的消息列表
 */
@property (nonatomic, copy) NSMutableArray *messages;

/*!
 @method
 @brief 获取conversation最新一条消息
 @result EMMessage最新一条消息
 */
- (UFMessage *)latestMessage;

@end

redpajama_set_name: RedPajamaGithub


text:
<?php
	class IconsUtil{

		const ICON_SALVAR = "glyphicon-floppy-disk";
		const ICON_ALERT = "glyphicon glyphicon-alert";
		const ICON_SEND = "glyphicon-send";
		const ICON_PARERCLIP = "glyphicon-paperclip";
		const ICON_WRECH = "glyphicon-wrench";
		const ICON_GLOBE = "glyphicon-globe";
		const ICON_EXCLAMTION_SING = "glyphicon-exclamation-sign";
		const ICON_EXCLAMTION_LIST = "glyphicon-list";
		const ICON_OK = "glyphicon-ok";
		const ICON_REMOVE = "glyphicon-remove";
		const ICON_COG = "glyphicon-cog";
		const ICON_TRASH = "glyphicon-trash";
		const ICON_USER = "glyphicon-user";
		const ICON_PENCIL = "glyphicon-pencil";
		const ICON_MINUS = "glyphicon-minus";
		const ICON_PLUS = "glyphicon-plus";
		const ICON_FILE = "glyphicon-file";
		const ICON_TH = "glyphicon-th";
		const ICON_TH_LIST = "glyphicon-th-list";
		const ICON_OFF = "glyphicon-off";
		const ICON_INFO_SING = "glyphicon-info-sign";
		const ICON_PLUS_SING = "glyphicon-plus-sign";
		const ICON_MINUS_SING	= "glyphicon-minus-sign";
		const ICON_SEARCH = "glyphicon-search";
		const ICON_GLASS = "glyphicon-glass";
		const ICON_USD = "glyphicon-usd";
                const ICON_UPLOAD = "glyphicon-upload";
                const ICON_DOWNLOAD = "glyphicon-download";

		public static function getIcone($type){
			return '';
		}

	}


text:
title:  MALEMY FANAHY SY TSY MIAVONA AM-PO
date:   26/05/2022
---

### Takaro

`Rehefa tapitra ny herinandro andinihana ity toko ity, dia inona avy ireo lesona maharesy lahatra anao manokana ny hampihatra azy eo amin'ny fiainanao?`

`Inona avy ireo lesona ilainao ampiharina ao amin'ny sekoly mísy anao, ny fianakavianao, ny toeram-piasanao, ary ny fiangonana misy anao?`

`Avereno jerena ilay andininy nianaranao tsianjery. Ahoana no hampiharanao izany eo amin'ny fiainanao mandritra ity herinandro ity?`

Araka ny tsy isaintsainanao an'i Kristy sy ny fitiavany tsy manam-paharoa, no tsy ifanarahanao amin'ny endriny, ary ahitanao ny tenanao ho tsara, sy hahatonga anao hatoky tena sy hahazo aina. Ny fahalalana an'i Kristy araka ny tokony ho izy, ny fibanjinana mandrakariva llay Tompo sy Mpanefa ny finoantsika no hananantsika fomba fijery izay ahafahantsika manombana marina ny fiainantsika sy ny toetrantsika eo anatrehan'llay Ohatra lehibe. (...).

Mandritra ny fiainana no hianaranao hanao tsara ny asanao. Tolona sy ezaka mafy isan'andro izany, ifanandrinana amin'ny fahazarana sy ny fironana ary ny tarazo. (...)

"Mianara amiko", hoy i Kristy, "fa malemy fanahy sady tsy miavona am-po Aho; dia hahita fitsaharana ho an'ny fanahinareo hianareo". Hampianatra izay rehetra manatona Azy mba hahazó fahalalana ny Tompo. Marobe ireo mpampianatra sandoka eto amin'izao tontolo izao (jereo ny 2 Tim. 4:3). (...) Ireny no nampitandreman'i Kristy antsika hoe: "Mitandrema hianareo, fandrao ho voafitaky ny mpaminany sandoka, izay mankao aminareo amin'ny fitafian'ny ondry, fa ao anatiny dia amboadia mitoha izy. Ny voany no hahafantaranareo azy."

Tonga hitady sy hamonjy ny very llay Mpiandry tsara. Nasehony tamin'ny asany ny fitiavany ny ondriny. Ny mpiandry ondry rehetra eo ambanin'ny fahefan'llay Mpiandry ondry lehibe dia hanana ireto toetra ireto: ho malemy fanahy sy tsy miavona am-po izy ireo. Ny finoana toy ny an'ny zaza dia manome fitsaharania sy miasa amin'ny fitiavana ary mihevitra ny hafa mandrakariva. (...)-TFC, b. 4. tt. 375-377.

` `


text:
var fs = require('fs');

console.log('Vou ler', Date.now());
console.time('leitura');

// var file = fs.readFileSync('file.mp4');

fs.readFile('file.mp4', function(data){
    console.log(data);
})

console.timeEnd('leitura');
console.log('Ja li', Date.now());


text:
import config from '../config.js';
import gulp from 'gulp';
import util from 'gulp-util';

gulp.task('data:dev', () => {
  return gulp.src(config.paths.src.data)
    .pipe(gulp.dest(config.paths.builds.dev.data))
    .on('error', util.log);
});


text:
package com.zlikun.spring.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Slf4j
@Aspect
public class LogAspect {

    @Before("servicePointcut()")
    public void before() {
        log.info("==before==");
    }

    @After("servicePointcut()")
    public void after() {
        log.info("==after==");
    }

    @Pointcut("execution(* com.zlikun.spring.service..*.*(..))")
    private void servicePointcut() {

    }

}


text:
package edu.gemini.shared.util;

import java.io.Serializable;
import java.util.Date;

/**
 * An (immutable) class for representing a range of dates specified by a
 * start date and an end date.
 */
public class DateRange implements Serializable, Comparable<DateRange> {

    private Date _startDate;

    private Date _endDate;

    /**
     * Constructs with the given starting and ending dates.
     */
    public DateRange(Date startDate, Date endDate) {
        // Want this object to be immutable, so make copies of these dates
        // so the client can't change them.
        _startDate = (Date) startDate.clone();
        _endDate = (Date) endDate.clone();
    }

    /**
     * Constructs with the given starting and ending dates.
     */
    public DateRange(DateRange dr) {
        // Want this object to be immutable, so make copies of these dates
        // so the client can't change them.
        _startDate = (Date) dr._startDate.clone();
        _endDate = (Date) dr._endDate.clone();
    }

    /**
     *      * Hibernate requires a no args constructor.
     */
    public DateRange() { }

    /**
     * Override the protected clone() method to make it public.
     */
    public Object clone() {
        return this;  // since this is immutable
    }

    /**
     * This method supports sorting in collections, implements Comparable.
     */
    @Override
    public int compareTo(DateRange dr) {
        if (getStartDate().getTime() < dr.getStartDate().getTime())
            return -1;
        if (getStartDate().getTime() > dr.getStartDate().getTime())
            return 1;
        if (getEndDate().getTime() < dr.getEndDate().getTime())
            return -1;
        if (getEndDate().getTime() > dr.getEndDate().getTime())
            return 1;
        return 0;
    }

    /**
     * Gets a "normalized" DateRange, which is the same as this date range
     * but guaranteed to have a start date that is before or the same as the
     * end date.
     *
     * @return this if the DateRange is already normalized, otherwise a new
     * DateRange with the start and end dates swapped
     */
    // Programmer's note - this method was originally called normalize(),
    // but that name collided with DiscreteRange::normalize().
    // It's not clean for subclasses to force changes in the parent,
    // but this class had no clients at the time.
    public DateRange normalizeRange() {
        DateRange dr = this;
        if (_startDate.after(_endDate)) {
            dr = new DateRange(_endDate, _startDate);
        }
        return dr;
    }

    /**
     * Gets the starting date for the range.
     * @return A copy of the starting date.
     */
    public Date getStartDate() {
        return (Date) _startDate.clone();
    }

    /**
     * Gets the ending date for the range.
     * @return A copy of the ending date.
     */
    public Date getEndDate() {
        return (Date) _endDate.clone();
    }

    /**
     * Gets the starting date for the range through the argument.
     */
    public Date getStartDate(Date output) {
        output.setTime(_startDate.getTime());
        return output;
    }

    /**
     * Gets the ending date for the range through the argument.
     */
    public Date getEndDate(Date output) {
        output.setTime(_endDate.getTime());
        return output;
    }

    /**
     * Overrides to return true if and only if the object is a DateRange
     * and the start date and end dates match.
     */
    public boolean equals(Object o) {
        if (!(o instanceof DateRange)) {
            return false;
        }
        DateRange dr = (DateRange) o;
        return _startDate.equals(dr.getStartDate()) && _endDate.equals(dr.getEndDate());
    }

    /**
     * Returns true if this DateRange contains the specified object.
     * DateRange contains() supports argument types of Calendar or Date.
     * Returns false if object is not in range or object class is not supported.
     */
    public boolean contains(Object o) {
        if (!(o instanceof Date))
            return false;
        Date d = (Date) o;
        return (!d.before(getStartDate()) && (!d.after(getEndDate())));
    }

    /**
     * Returns true if this range's start is equal or after the argument range end
     *

     *
     *      arg             this
     * *-----------*  *---------------*
     *
     *

     */
    public boolean after(DateRange dr) {
        return (_startDate.getTime() >= dr._endDate.getTime());
    }

    /**
     * Returns true if this range's end is equal or before the argument range start
     *

     *
     *      this            arg
     * *-----------*  *---------------*
     *
     *

     */
    public boolean before(DateRange dr) {
        return (_endDate.getTime() <= dr._startDate.getTime());
    }

    /**
     * Returns true if this range contains at least one unit that is also
     * contained in the argument range.
     *

     *
     *                           this
     *                    *---------------*
     *          *------------------*
     *                   arg
     *
     *                   this
     *     *---------------------------------*
     *          *------------------*
     *                   arg
     *
     *

     */
    public boolean intersects(DateRange dr) {
        return (_endDate.getTime() >= dr._startDate.getTime() && _startDate.getTime() <= dr._endDate.getTime());
    }

    /**
     * Returns the intersection of the ranges, i.e. the range consisting
     * of the units contained in both ranges.
     * Returns null if the ranges do not intersect.
     *

     *
     *           arg             this
     *     *---------------*---------------*
     *
     *              returns
     *
     *                     *
     *
     *
     *
     *                           this
     *                    *---------------*
     *          *------------------*
     *                   arg
     *
     *              returns
     *
     *                    *--------*
     *
     *

     */
    public DateRange intersection(DateRange dr) {
        if (!intersects(dr))
            return null;
        // There is at least one point in common.
        // Pick out the latest start date and earliest end date.
        Date start = (_startDate.getTime() > dr._startDate.getTime()) ? _startDate : dr._startDate;
        Date end = (_endDate.getTime() < dr._endDate.getTime()) ? _endDate : dr._endDate;
        return new DateRange(start, end);
    }

    /**
     * Overrides to match the definition of equals.
     */
    public int hashCode() {
        int result = _startDate.hashCode();
        return 37 * result + _endDate.hashCode();
    }

    /**
     * Overrides to display a human-readable representation of the start and
     * end dates.
     */
    public String toString() {
        return getClass().getName() + " [startDate=" + _startDate + ", endDate=" + _endDate + "]";
    }

}


text:
require "resource"

module Language
  module Go
    # Given a set of resources, stages them to a gopath for
    # building go software.
    # The resource names should be the import name of the package,
    # e.g. `resource "github.com/foo/bar"`
    def self.stage_deps resources, target
      godeps = resources.grep(Resource::Go)
      godeps.each {|resource| resource.stage target}
    end
  end
end


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18034
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/core/components/customisable/conditions.py")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/core/components/customisable/effects.py")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/core/components/customisable/__init__.py")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/core/components/__init__.py")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/core/__init__.py")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/dataparser/__init__.py")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("lib/python/interpreter.py")]


text:
using System.Collections.Generic;

namespace Internal.TypeSystem
{
    /// <summary>
    /// Type with metadata available that is equivalent to a TypeDef record in an ECMA 335 metadata stream.
    /// A class, an interface, or a value type.
    /// </summary>
    public abstract partial class MetadataType : DefType
    {
        public override bool HasStaticConstructor
        {
            get
            {
                return GetStaticConstructor() != null;
            }
        }

        public override bool HasFinalizer
        {
            get
            {
                return GetFinalizer() != null;
            }
        }

        /// <summary>
        /// Gets the name of the type as represented in the metadata.
        /// </summary>
        public abstract string Name { get; }

        /// <summary>
        /// Gets the namespace of the type.
        /// </summary>
        public abstract string Namespace { get; }

        /// <summary>
        /// Gets metadata that controls instance layout of this type.
        /// </summary>
        public abstract ClassLayoutMetadata GetClassLayout();

        /// <summary>
        /// If true, the type layout is dictated by the explicit layout rules provided.
        /// Corresponds to the definition of explicitlayout semantic defined in the ECMA-335 specification.
        /// </summary>
        public abstract bool IsExplicitLayout { get; }

        /// <summary>
        /// If true, the order of the fields needs to be preserved. Corresponds to the definition
        /// of sequentiallayout semantic defined in the ECMA-335 specification.
        /// </summary>
        public abstract bool IsSequentialLayout { get; }

        /// <summary>
        /// If true, the type initializer of this type has a relaxed semantic. Corresponds
        /// to the definition of beforefieldinit semantic defined in the ECMA-335 specification.
        /// </summary>
        public abstract bool IsBeforeFieldInit { get; }

        /// <summary>
        /// If true, this is the special <Module> type that contains the definitions
        /// of global fields and methods in the module.
        /// </summary>
        public bool IsModuleType
        {
            get
            {
                return Module.GetGlobalModuleType() == this;
            }
        }

        /// <summary>
        /// Gets the module that defines this type.
        /// </summary>
        public abstract ModuleDesc Module { get; }

        /// <summary>
        /// Same as <see cref="TypeDesc.BaseType"/>, but the result is a MetadataType (avoids casting).
        /// </summary>
        public abstract MetadataType MetadataBaseType { get; }

        /// <summary>
        /// If true, the type cannot be used as a base type of any other type.
        /// </summary>
        public abstract bool IsSealed { get; }

        /// <summary>
        /// Returns true if the type has given custom attribute.
        /// </summary>
        public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName);

        /// <summary>
        /// Gets the containing type of this type or null if the type is not nested.
        /// </summary>
        public abstract MetadataType ContainingType { get; }

        /// <summary>
        /// Get all of the types nested in this type.
        /// </summary>
        public abstract IEnumerable<MetadataType> GetNestedTypes();

        /// <summary>
        /// Get a specific type nested in this type. Returns null if the type
        /// doesn't exist.
        /// </summary>
        public abstract MetadataType GetNestedType(string name);
    }

    public struct ClassLayoutMetadata
    {
        public int PackingSize;
        public int Size;
        public FieldAndOffset[] Offsets;
    }

    public struct FieldAndOffset
    {
        public const int InvalidOffset = -1;

        public readonly FieldDesc Field;
        public readonly int Offset;
        public FieldAndOffset(FieldDesc field, int offset)
        {
            Field = field;
            Offset = offset;
        }
    }
}


text:
export default crypto;
export const isCryptoKey = (key) => key instanceof CryptoKey;


text:
package org.apache.tomcat.util.descriptor.web;

import java.util.EnumSet;

import javax.servlet.SessionTrackingMode;

/**
 * Representation of a session configuration element for a web application,
 * as represented in a <session-config> element in the
 * deployment descriptor.
 */
public class SessionConfig {
    private Integer sessionTimeout;
    private String cookieName;
    private String cookieDomain;
    private String cookiePath;
    private String cookieComment;
    private Boolean cookieHttpOnly;
    private Boolean cookieSecure;
    private Integer cookieMaxAge;
    private final EnumSet<SessionTrackingMode> sessionTrackingModes =
        EnumSet.noneOf(SessionTrackingMode.class);

    public Integer getSessionTimeout() {
        return sessionTimeout;
    }
    public void setSessionTimeout(String sessionTimeout) {
        this.sessionTimeout = Integer.valueOf(sessionTimeout);
    }

    public String getCookieName() {
        return cookieName;
    }
    public void setCookieName(String cookieName) {
        this.cookieName = cookieName;
    }

    public String getCookieDomain() {
        return cookieDomain;
    }
    public void setCookieDomain(String cookieDomain) {
        this.cookieDomain = cookieDomain;
    }

    public String getCookiePath() {
        return cookiePath;
    }
    public void setCookiePath(String cookiePath) {
        this.cookiePath = cookiePath;
    }

    public String getCookieComment() {
        return cookieComment;
    }
    public void setCookieComment(String cookieComment) {
        this.cookieComment = cookieComment;
    }

    public Boolean getCookieHttpOnly() {
        return cookieHttpOnly;
    }
    public void setCookieHttpOnly(String cookieHttpOnly) {
        this.cookieHttpOnly = Boolean.valueOf(cookieHttpOnly);
    }

    public Boolean getCookieSecure() {
        return cookieSecure;
    }
    public void setCookieSecure(String cookieSecure) {
        this.cookieSecure = Boolean.valueOf(cookieSecure);
    }

    public Integer getCookieMaxAge() {
        return cookieMaxAge;
    }
    public void setCookieMaxAge(String cookieMaxAge) {
        this.cookieMaxAge = Integer.valueOf(cookieMaxAge);
    }

    public EnumSet<SessionTrackingMode> getSessionTrackingModes() {
        return sessionTrackingModes;
    }
    public void addSessionTrackingMode(String sessionTrackingMode) {
        sessionTrackingModes.add(
                SessionTrackingMode.valueOf(sessionTrackingMode));
    }

}


text:
package org.sakuli.services.forwarder.icinga2.model;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * POJO for the response
 *
 * @author tschneck
 *         Date: 2/23/16
 */
public class Icinga2Result {

    private List<Map<String, String>> results;

    public List<Map<String, String>> getResults() {
        return results;
    }

    public void setResults(List<Map<String, String>> results) {
        this.results = results;
    }

    public Optional<String> getStatusOfFirstElement() {
        if (results != null) {
            return results.stream().filter(Objects::nonNull).findFirst().map(e -> e.get("status"));
        }
        return Optional.empty();
    }

    public Optional<Integer> getCodeOfFirstElement() {
        if (results != null) {
            return results.stream()
                    .filter(Objects::nonNull)
                    .findFirst()
                    .map(e -> e.get("code"))
                    .map(s -> Integer.valueOf(StringUtils.substringBefore(s, ".")));
        }
        return Optional.empty();
    }

    public boolean isSuccess() {
        return getCodeOfFirstElement().filter(c -> c == 200).isPresent()
                && getStatusOfFirstElement().filter(s -> s.toLowerCase().startsWith("successful")).isPresent();
    }

    public String getFirstElementAsString() {
        return String.format("[%s] - %s",
                getCodeOfFirstElement().isPresent() ? getCodeOfFirstElement().get() : "NULL",
                getStatusOfFirstElement().isPresent() ? getStatusOfFirstElement().get() : "EMPTY MESSAGE");
    }
}


text:
<TableLayout
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"
		android:layout_marginRight="2px"
	>
		<TextView android:id="@+id/TextViewNumMove"
			android:textColor="@color/textColor"
			android:padding="8px"
			android:layout_width="wrap_content" android:layout_height="wrap_content"/>
		<TextView android:id="@+id/TextViewMove"
			android:textColor="@color/textColor"
			android:padding="8px"
			android:layout_width="wrap_content" android:layout_height="wrap_content"/>

	</TableRow>
</TableLayout>


text:
package com.strime.applogger.tools;

import com.strime.applogger.model.Event;

import java.util.ArrayList;

/**
 * Created by gsa13442 on 05/04/2017.
 */

public class TimeManager {
    private final ArrayList<Event> events;

    public TimeManager(ArrayList<Event> events) {
        this.events = events;

    }
}


text:
namespace CGAL {

template<class Edge>
class In_place_edge_list {
private:
  typedef typename Edge::first_type          Face_handle;
  typedef typename Face_handle::value_type   Face;

private:
  Edge _front;
  unsigned int _size;

private:
  inline void increase_size() {
    _size++;
  }

  inline void decrease_size() {
    _size--;
  }

public:
  bool is_valid() const { return true; }

  inline unsigned int size() const {
    return _size;
  }

  inline void push_first(const Edge& e) {
    _front = e;
    set_next(e, e);
    set_previous(e, e);
    increase_size();
  }

  inline Edge next(const Edge& e) const {
    CGAL_precondition( is_in_list(e) );
    return e.first->next(e.second);
  }

  inline Edge previous(const Edge& e) const {
    CGAL_precondition( is_in_list(e) );
    return e.first->previous(e.second);
  }

  inline void set_next(const Edge& e, const Edge& next) {
    Edge _next(next.first, next.second);
    e.first->set_next(e.second, _next);
  }

  inline void set_previous(const Edge& e, const Edge& prev) {
    Edge _prev(prev.first, prev.second);
    e.first->set_previous(e.second, _prev);
  }

  inline bool is_first(const Edge& e) const {
    return ( (e.first == _front.first &&
	      e.second == _front.second) );
  }

public:
  inline bool is_singleton() const {
    CGAL_precondition( !is_empty() );
    return (size() == 1);
  }

public:
  In_place_edge_list(const Edge& e = Edge(Face_handle(),-1) )
    : _size(0) {
    _front = e;
  }

  inline Edge front() const {
    CGAL_precondition( !is_empty() );
    return _front;
  }

  inline Edge back() const {
    CGAL_precondition( !is_empty() );
    return previous(_front);
  }

  inline bool is_empty() const {
    return ( _front.first == Face_handle() );
  }

  inline void pop() {
    CGAL_precondition( !is_empty() );
    remove(front()); // it is important here that I do not pass the
    // variable _front but rather a copy of it...
  }

  inline void push_front(const Edge& e) {
    CGAL_precondition( !is_in_list(e) );
    push(e);
    _front = e;
  }

  inline void push_back(const Edge& e) {
    push(e);
  }

  void push(const Edge& e) {
    CGAL_precondition( !is_in_list(e) );

    if ( is_empty() ) {
      push_first(e);
      return;
    }
    Edge last_edge = back();
    set_next(last_edge, e);
    set_next(e, _front);
    set_previous(e, last_edge);
    set_previous(_front, e);

    increase_size();
  }

  inline void insert_after(const Edge& e, const Edge& new_e) {
    CGAL_precondition( is_in_list(e) );
    Edge old_front = _front;
    _front = next(e);
    push_front(new_e);
    _front = old_front;
  }

  inline void insert_before(const Edge& e, const Edge& new_e) {
    CGAL_precondition( is_in_list(e) );
    Edge old_front = _front;
    _front = e;
    push(new_e);
    _front = old_front;
  }

  inline void replace(const Edge& e, const Edge& new_e) {
    insert_before(e, new_e);
    remove(e);
  }

  void remove(const Edge& e) {
    CGAL_precondition( is_in_list(e) );
    static Edge SENTINEL_QUEUE_EDGE = Edge(Face_handle(), -1);

    if ( is_singleton() ) {
      _front = SENTINEL_QUEUE_EDGE;
      set_next(e, SENTINEL_QUEUE_EDGE);
      set_previous(e, SENTINEL_QUEUE_EDGE);
      decrease_size();
      return;
    }

    Edge _next = next(e);
    Edge _prev = previous(e);

    if ( is_first(e) ) {
      _front = _next;
    }

    set_next(e, SENTINEL_QUEUE_EDGE);
    set_previous(e, SENTINEL_QUEUE_EDGE);

    set_next(_prev, _next);
    set_previous(_next, _prev);
    decrease_size();
  }

  bool is_in_list(const Edge& e) const {
    return e.first->is_in_list(e.second);
  }

  void clear() {
    while ( !is_empty() ) {
      pop();
    }
  }
};

} //namespace CGAL

#endif // CGAL_IN_EDGE_PLACE_LIST_H


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Other Classes: Class  WMLNoopElementImpl
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.wml.dom

Class  WMLNoopElementImpl

java.lang.Object
  |
  +--org.apache.xerces.dom.NodeImpl
        |
        +--org.apache.xerces.dom.ChildNode
              |
              +--org.apache.xerces.dom.ParentNode
                    |
                    +--org.apache.xerces.dom.ElementImpl
                          |
                          +--org.apache.wml.dom.WMLElementImpl
                                |
                                +--org.apache.wml.dom.WMLNoopElementImpl

All Implemented Interfaces:
java.lang.Cloneable, org.w3c.dom.Element, org.w3c.dom.ElementTraversal, org.w3c.dom.events.EventTarget, org.w3c.dom.Node, org.w3c.dom.NodeList, java.io.Serializable, org.w3c.dom.TypeInfo, WMLElement, WMLNoopElement

public class WMLNoopElementImpl
extends WMLElementImpl
implements WMLNoopElement

INTERNAL:

Usage of this class is not supported. It may be altered or removed at any time.

Version:
$Id: WMLNoopElementImpl.java 661560 2008-05-30 03:22:25Z mrglavas $

Author:
David Li

See Also:
Serialized Form

Fields inherited from class org.apache.xerces.dom.ElementImpl

attributes, name

Fields inherited from class org.apache.xerces.dom.ParentNode

firstChild, fNodeListCache, ownerDocument

Fields inherited from class org.apache.xerces.dom.ChildNode

nextSibling, previousSibling

Fields inherited from class org.apache.xerces.dom.NodeImpl

DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_IS_CONTAINED, DOCUMENT_POSITION_PRECEDING, ELEMENT_DEFINITION_NODE, FIRSTCHILD, flags, HASSTRING, ID, IGNORABLEWS, NORMALIZED, OWNED, ownerNode, READONLY, SPECIFIED, SYNCCHILDREN, SYNCDATA, TREE_POSITION_ANCESTOR, TREE_POSITION_DESCENDANT, TREE_POSITION_DISCONNECTED, TREE_POSITION_EQUIVALENT, TREE_POSITION_FOLLOWING, TREE_POSITION_PRECEDING, TREE_POSITION_SAME_NODE

Fields inherited from interface org.w3c.dom.Node

ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE

Fields inherited from interface org.w3c.dom.TypeInfo

DERIVATION_EXTENSION, DERIVATION_LIST, DERIVATION_RESTRICTION, DERIVATION_UNION

Constructor Summary

WMLNoopElementImpl(WMLDocumentImpl owner,
                   java.lang.String tagName)

Method Summary

 java.lang.String
getClassName()

 java.lang.String
getId()

 void
setClassName(java.lang.String newValue)

          The 'class' attribute of a element that affiliates an elements
 with one or more elements.

 void
setId(java.lang.String newValue)

          The element's identifier which is unique in a single deck.

Methods inherited from class org.apache.wml.dom.WMLElementImpl

getXmlLang, setXmlLang

Methods inherited from class org.apache.xerces.dom.ElementImpl

cloneNode, getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getAttributes, getBaseURI, getChildElementCount, getDefaultAttributes, getElementsByTagName, getElementsByTagNameNS, getFirstElementChild, getLastElementChild, getNextElementSibling, getNodeName, getNodeType, getPreviousElementSibling, getSchemaTypeInfo, getTagName, getTypeName, getTypeNamespace, getXercesAttribute, getXMLBaseAttribute, hasAttribute, hasAttributeNS, hasAttributes, isDerivedFrom, isEqualNode, normalize, reconcileDefaultAttributes, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS, setIdAttribute, setIdAttributeNode, setIdAttributeNS, setOwnerDocument, setReadOnly, setupDefaultAttributes, setXercesAttributeNode, synchronizeData

Methods inherited from class org.apache.xerces.dom.ParentNode

getChildNodes, getChildNodesUnoptimized, getFirstChild, getLastChild, getLength, getOwnerDocument, getTextContent, hasChildNodes, insertBefore, item, removeChild, replaceChild, setTextContent, synchronizeChildren

Methods inherited from class org.apache.xerces.dom.ChildNode

getNextSibling, getParentNode, getPreviousSibling

Methods inherited from class org.apache.xerces.dom.NodeImpl

addEventListener, appendChild, changed, changes, compareDocumentPosition, compareTreePosition, dispatchEvent, getContainer, getFeature, getLocalName, getNamespaceURI, getNodeNumber, getNodeValue, getPrefix, getReadOnly, getUserData, getUserData, getUserDataRecord, isDefaultNamespace, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, needsSyncChildren, removeEventListener, setNodeValue, setPrefix, setUserData, setUserData, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface org.w3c.dom.Element

getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getSchemaTypeInfo, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS, setIdAttribute, setIdAttributeNode, setIdAttributeNS

Methods inherited from interface org.w3c.dom.Node

appendChild, cloneNode, compareDocumentPosition, getAttributes, getBaseURI, getChildNodes, getFeature, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, getTextContent, getUserData, hasAttributes, hasChildNodes, insertBefore, isDefaultNamespace, isEqualNode, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, normalize, removeChild, replaceChild, setNodeValue, setPrefix, setTextContent, setUserData

Constructor Detail

WMLNoopElementImpl

public WMLNoopElementImpl(WMLDocumentImpl owner,
                          java.lang.String tagName)

Method Detail

setClassName

public void setClassName(java.lang.String newValue)

Description copied from interface: WMLElement

The 'class' attribute of a element that affiliates an elements
 with one or more elements.
 (Section 8.9, WAP WML Version 16-Jun-1999)

Specified by:
setClassName in interface WMLElement
Overrides:
setClassName in class WMLElementImpl

getClassName

public java.lang.String getClassName()

Specified by:
getClassName in interface WMLElement
Overrides:
getClassName in class WMLElementImpl

setId

public void setId(java.lang.String newValue)

Description copied from interface: WMLElement

The element's identifier which is unique in a single deck.
 (Section 8.9, WAP WML Version 16-Jun-1999)

Specified by:
setId in interface WMLElement
Overrides:
setId in class WMLElementImpl

getId

public java.lang.String getId()

Specified by:
getId in interface WMLElement
Overrides:
getId in class WMLElementImpl

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
package com.weinyc.sa.app.model;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.Column;

import org.springframework.jdbc.core.RowMapper;

import com.weinyc.sa.core.reflect.ReflectUtils;
import java.sql.Time;

/**
 *
 * @author L5M
 * @param <T>
 */
public class ModelMeta<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    protected Map<String, Field> columnFields;
    protected Map<String, Method> field2Setter, field2Getter;

    public Map<String, Field> getColumnFields() {
        return columnFields;
    }

    public Map<String, Method> getField2Setter() {
        return field2Setter;
    }

    public Map<String, Method> getField2Getter() {
        return field2Getter;
    }

    protected Class<T> clazz;

    protected RowMapper<T> rowMapper;

    public ModelMeta(Class<T> clazz) {
        this.clazz = clazz;
        this.columnFields = new HashMap<>();
        this.field2Setter = new HashMap<>();
        this.field2Getter = new HashMap<>();
        Map<String, PropertyDescriptor> fieldName2PropertyDescriptor = ReflectUtils.findFieldName2PropertyDescriptor(clazz);

        List<Field> cf = ReflectUtils.getDeclaredFields((List<Field>) null, clazz, false);
        for (Field field : cf) {
            if (field.isAnnotationPresent(Column.class)) {
                Column annotation = (Column) field.getAnnotation(Column.class) ;
                String cname;
                if (annotation != null && org.apache.commons.lang.StringUtils.isNotEmpty(annotation.name())) {
                    cname = annotation.name();
                    cname = cname.replaceAll("[\\[\\]]", "`");
                } else {
                    cname = field.getName();
                }
                this.columnFields.put(cname, field);
                this.field2Getter.put(field.getName(), ReflectUtils.findGetter(this.clazz, field,
                        fieldName2PropertyDescriptor, null));

                this.field2Setter.put(field.getName(), ReflectUtils.findSetter(this.clazz, field,
                        fieldName2PropertyDescriptor, null));
            }
        }
    }

    public static Object get(ResultSet rs, String cname, Class<?> type) throws SQLException{
        if(type != null && type.equals(java.util.Date.class)){
            type = java.sql.Date.class;
        }
        try{
             return rs.getObject(cname, type);
        }catch(Exception e){
            //System.out.println(e);
           // Logger.getLogger(ModelMeta.class.getName()).log(Level.WARNING, null, e);
            try {
                if(type == null){
                    return rs.getObject(cname);
                }
                if(type.equals(String.class) ){
                    return rs.getString(cname);
                }
                if(type.equals(Integer.class) || type.equals(Integer.TYPE) ){
                    return rs.getInt(cname);
                }
                if(type.equals(Long.class) || type.equals(Long.TYPE) ){
                    return rs.getLong(cname);
                }
                if(type.equals(Boolean.class) || type.equals( Boolean.TYPE)){
                    return rs.getBoolean(cname);
                }
                if(type.equals(Short.class) || type.equals(Short.TYPE) ){
                    return rs.getShort(cname);
                }
                if(type.equals(Byte.class) || type.equals(Byte.TYPE) ){
                    return rs.getByte(cname);
                }
                if(type.equals(Character.class) || type.equals(Character.TYPE) ){
                    return rs.getInt(cname);
                }
                if(type.equals(Double.class) || type.equals(Double.TYPE)){
                    return rs.getDouble(cname);
                }
                if(type.equals(Float.class) || type.equals(Float.TYPE)){
                    return rs.getFloat(cname);
                }

                if(type.equals(java.sql.Date.class) ){
                    return rs.getDate(cname);
                }
                if(type.equals(Time.class) ){
                    return rs.getTime(cname);
                }

                return rs.getObject(cname);

                /*
                 clazz.isPrimitive() || clazz.equals(String.class)
				|| clazz.equals(Boolean.class) || clazz.equals(Byte.class)
				|| clazz.equals(Character.class) || clazz.equals(Double.class)
				|| clazz.equals(Float.class) || clazz.equals(Integer.class)
				|| clazz.equals(Long.class) || clazz.equals(Short.class)  || clazz.equals(Date.class)
				|| clazz.equals(InternetAddress.class) ;
                */

            }catch (Exception ex) {
                Logger.getLogger(ModelMeta.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }

    public RowMapper<T> getRowMapper() {
        if (this.rowMapper == null) {
            this.rowMapper = new RowMapper<T>() {
                @Override
                public T mapRow(ResultSet rs, int rowNum) throws SQLException {
                    T bean = null;
                    try {
                        bean = clazz.newInstance();
                        for (Map.Entry<String, Field> entry : columnFields.entrySet()) {
                            String cname = entry.getKey().replaceAll("`", "");
                            Method setter = field2Setter.get(entry.getValue().getName());
                            Class<?> t = ReflectUtils.findPropertyType(entry.getValue(), setter);
                            ReflectUtils.updateFieldValue(bean, entry.getValue(), setter, get(rs, cname, t));
                        }
                    }
                    catch (InvocationTargetException | IllegalArgumentException | InstantiationException | IllegalAccessException ex) {
                        Logger.getLogger(ModelMeta.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    return bean;
                }
            };

        }
        return this.rowMapper;
    }
}


text:
Source Code Repository for learning python, based on My IST256 Python course at Syracuse University!

This code is free for use by other instructors and self-directed learners alike. If you want to teach Python programming or learn it you've come to the right place!

## Important

If you're enrolled in IST256 at Syracuse University, you should NOT use this Repository. Instead you will use our hosted JupyterHub programming environment.

## Setup

The programming environment uses Jupyter Notebooks and runs in a docker container. You must have Docker installed on your computer to run the container. To get docker visit: [https://docs.docker.com/get-docker/](https://docs.docker.com/get-docker/).

Once docker is setup you can bring up the notebook using Docker Compose from the command line:

`docker-compose up`

You will see a link to the Jupyter application in the logs. click on it to open Jupyter!

When you need to shut down Jupyter, go back to the logs and press `CTRL` + `C` to stop. Then from the command line type:

`docker-compose down`

Assigned readings, lecture videos, lab walk through, and homework advice can be found on the course website [https://ist256.com](https://ist256.com)

Happy Programming!

Best,
Michael


text:
    <colgroup>
    loop:0:start<col>loop:0:end
    testsrv=[[hostname]] <col><col> [[hostname]]=testsrv
    </colgroup>

        Metric
        Graduated
        Incubating
        Sandbox
        testsrv=[[hostname]] CNCF	 [[hostname]]=testsrv
        testsrv=[[skip]] Other	 [[skip]]=testsrv
        Metric

        Kubernetes
        Prometheus
        Envoy
        CoreDNS
        OpenTracing
        Fluentd
        gRPC
        containerd
        rkt
        CNI
        Jaeger
        Notary
        TUF
        Vitess
        NATS
        Linkerd
        Helm
        Rook
        Harbor
        etcd
        OPA
        SPIFFE
        SPIRE
        CloudEvents
        Telepresence
        OpenMetrics
        TiKV
        Cortex
        Buildpacks
        Falco
        Dragonfly
        Virtual Kubelet
        testsrv=[[hostname]] CNCF	 [[hostname]]=testsrv
        testsrv=[[skip]] OCI	 [[skip]]=testsrv
        testsrv=[[skip]] Istio	 [[skip]]=testsrv
        testsrv=[[skip]] Spinnaker	 [[skip]]=testsrv
        testsrv=[[skip]] Knative	 [[skip]]=testsrv

        testsrv=[[hostname]] 	 [[hostname]]=testsrv
        testsrv=[[skip]] 	 [[skip]]=testsrv
        testsrv=[[skip]] 	 [[skip]]=testsrv
        testsrv=[[skip]] 	 [[skip]]=testsrv
        testsrv=[[skip]] 	 [[skip]]=testsrv

    loop:1:start

        metrics:series:phealthkubernetes:loop:1:i:1
        metrics:series:phealthkubernetes:loop:1:i:2
        metrics:series:phealthprometheus:loop:1:i:2
        metrics:series:phealthenvoy:loop:1:i:2
        metrics:series:phealthcoredns:loop:1:i:2
        metrics:series:phealthopentracing:loop:1:i:2
        metrics:series:phealthfluentd:loop:1:i:2
        metrics:series:phealthgrpc:loop:1:i:2
        metrics:series:phealthcontainerd:loop:1:i:2
        metrics:series:phealthrkt:loop:1:i:2
        metrics:series:phealthcni:loop:1:i:2
        metrics:series:phealthjaeger:loop:1:i:2
        metrics:series:phealthnotary:loop:1:i:2
        metrics:series:phealthtuf:loop:1:i:2
        metrics:series:phealthvitess:loop:1:i:2
        metrics:series:phealthnats:loop:1:i:2
        metrics:series:phealthlinkerd:loop:1:i:2
        metrics:series:phealthhelm:loop:1:i:2
        metrics:series:phealthrook:loop:1:i:2
        metrics:series:phealthharbor:loop:1:i:2
        metrics:series:phealthetcd:loop:1:i:2
        metrics:series:phealthopa:loop:1:i:2
        metrics:series:phealthspiffe:loop:1:i:2
        metrics:series:phealthspire:loop:1:i:2
        metrics:series:phealthcloudevents:loop:1:i:2
        metrics:series:phealthtelepresence:loop:1:i:2
        metrics:series:phealthopenmetrics:loop:1:i:2
        metrics:series:phealthtikv:loop:1:i:2
        metrics:series:phealthcortex:loop:1:i:2
        metrics:series:phealthbuildpacks:loop:1:i:2
        metrics:series:phealthfalco:loop:1:i:2
        metrics:series:phealthdragonfly:loop:1:i:2
        metrics:series:phealthvirtualkubelet:loop:1:i:2
        testsrv=[[hostname]] metrics:series:phealthcncf:loop:1:i:2	 [[hostname]]=testsrv
        testsrv=[[skip]] metrics:series:phealthopencontainers:loop:1:i:2	 [[skip]]=testsrv
        testsrv=[[skip]] metrics:series:phealthistio:loop:1:i:2	 [[skip]]=testsrv
        testsrv=[[skip]] metrics:series:phealthspinnaker:loop:1:i:2	 [[skip]]=testsrv
        testsrv=[[skip]] metrics:series:phealthknative:loop:1:i:2	 [[skip]]=testsrv
        metrics:series:phealthkubernetes:loop:1:i:1

    loop:1:end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>SQL Conformance</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.10 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Appendixes"
HREF="appendixes.html"><LINK
REL="PREVIOUS"
TITLE="SQL Key Words"
HREF="sql-keywords-appendix.html"><LINK
REL="NEXT"
TITLE="Supported Features"
HREF="features-sql-standard.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2012-09-19T22:08:45">

PostgreSQL 9.0.10 Documentation

Prev	Up		Next

Appendix D. SQL Conformance

Table of Contents

D.1. Supported Features

D.2. Unsupported Features

  This section attempts to outline to what extent
  PostgreSQL conforms to the current SQL
  standard.  The following information is not a full statement of
  conformance, but it presents the main topics in as much detail as is
  both reasonable and useful for users.

  The formal name of the SQL standard is ISO/IEC 9075 "Database
  Language SQL".  A revised version of the standard is released
  from time to time; the most recent update appearing in 2008.
  The 2008 version is referred to as ISO/IEC 9075:2008, or simply as SQL:2008.
  The versions prior to that were SQL:2003, SQL:1999, and SQL-92.  Each version
  replaces the previous one, so claims of conformance to earlier
  versions have no official merit.
  PostgreSQL development aims for
  conformance with the latest official version of the standard where
  such conformance does not contradict traditional features or common
  sense.  The PostgreSQL project is not represented in the ISO/IEC
  9075 Working Group during the preparation of the SQL standard
  releases, but even so, many of the features required by the SQL
  standard are supported, though sometimes with slightly differing
  syntax or function.  Further moves towards conformance can be
  expected over time.

  <ACRONYM
CLASS="ACRONYM"
>SQL-92</ACRONYM
> defined three feature sets for
  conformance: Entry, Intermediate, and Full.  Most database
  management systems claiming <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> standard
  conformance were conforming at only the Entry level, since the
  entire set of features in the Intermediate and Full levels was
  either too voluminous or in conflict with legacy behaviors.

  Starting with <ACRONYM
CLASS="ACRONYM"
>SQL:1999</ACRONYM
>, the SQL standard defines
  a large set of individual features rather than the ineffectively
  broad three levels found in <ACRONYM
CLASS="ACRONYM"
>SQL-92</ACRONYM
>.  A large
  subset of these features represents the "Core"
  features, which every conforming SQL implementation must supply.
  The rest of the features are purely optional.  Some optional
  features are grouped together to form "packages", which
  SQL implementations can claim conformance to, thus claiming
  conformance to particular groups of features.

  The <ACRONYM
CLASS="ACRONYM"
>SQL:2008</ACRONYM
> and <ACRONYM
CLASS="ACRONYM"
>SQL:2003</ACRONYM
>
  standard versions are also split into a number
  of parts.  Each is known by a shorthand name.  Note that these parts
  are not consecutively numbered.

ISO/IEC 9075-1 Framework (SQL/Framework)

ISO/IEC 9075-2 Foundation (SQL/Foundation)

ISO/IEC 9075-3 Call Level Interface (SQL/CLI)

ISO/IEC 9075-4 Persistent Stored Modules (SQL/PSM)

ISO/IEC 9075-9 Management of External Data (SQL/MED)

ISO/IEC 9075-10 Object Language Bindings (SQL/OLB)

ISO/IEC 9075-11 Information and Definition Schemas (SQL/Schemata)

ISO/IEC 9075-13 Routines and Types using the Java Language (SQL/JRT)

ISO/IEC 9075-14 XML-related specifications (SQL/XML)

  The PostgreSQL core covers parts 1, 2, 9,
  11, and 14.  Part 3 is covered by the ODBC driver, and part 13 is
  covered by the PL/Java plug-in, but exact conformance is currently
  not being verified for these components.  There are currently no
  implementations of parts 4 and 10
  for PostgreSQL.

  PostgreSQL supports most of the major features of SQL:2008.  Out of
  179 mandatory features required for full Core conformance,
  PostgreSQL conforms to at least 160.  In addition, there is a long
  list of supported optional features.  It might be worth noting that at
  the time of writing, no current version of any database management
  system claims full conformance to Core SQL:2008.

  In the following two sections, we provide a list of those features
  that PostgreSQL supports, followed by a
  list of the features defined in <ACRONYM
CLASS="ACRONYM"
>SQL:2008</ACRONYM
> which
  are not yet supported in PostgreSQL.
  Both of these lists are approximate: There might be minor details that
  are nonconforming for a feature that is listed as supported, and
  large parts of an unsupported feature might in fact be implemented.
  The main body of the documentation always contains the most accurate
  information about what does and does not work.

Note:    Feature codes containing a hyphen are subfeatures.  Therefore, if a
   particular subfeature is not supported, the main feature is listed
   as unsupported even if some other subfeatures are supported.

Prev	Home	Next

<ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Key Words	Up	Supported Features


text:
<?php

/**
 * Represents an upgrade operation to upgrade Ad.url.
 * @package    Google_Api_Ads_AdWords_v201605
 * @subpackage v201605
 */
class AdUrlUpgrade
{

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
    const XSI_TYPE = "AdUrlUpgrade";

    /**
     * @access public
     * @var integer
     */
    public $adId;

    /**
     * @access public
     * @var string
     */
    public $finalUrl;

    /**
     * @access public
     * @var string
     */
    public $finalMobileUrl;

    /**
     * @access public
     * @var string
     */
    public $trackingUrlTemplate;

    /**
     * Gets the namesapce of this class
     * @return string the namespace of this class
     */
    public function getNamespace()
    {
        return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return string the xsi:type name of this class
     */
    public function getXsiTypeName()
    {
        return self::XSI_TYPE;
    }

    public function __construct($adId = null, $finalUrl = null, $finalMobileUrl = null, $trackingUrlTemplate = null)
    {
        $this->adId = $adId;
        $this->finalUrl = $finalUrl;
        $this->finalMobileUrl = $finalMobileUrl;
        $this->trackingUrlTemplate = $trackingUrlTemplate;
    }

}