text:
/*!
 * \file codegen_c.cc
 */
#include "codegen_c.h"

#include <tvm/arith/analyzer.h>

#include <cctype>
#include <iomanip>

#include "../../arith/pattern_match.h"

namespace tvm {
namespace codegen {

using namespace tir;

void CodeGenC::Init(bool output_ssa) { print_ssa_form_ = output_ssa; }

void CodeGenC::InitFuncState(const PrimFunc& f) {
  alloc_storage_scope_.clear();
  handle_data_type_.clear();
  CodeGenSourceBase::ClearFuncState();
}

void CodeGenC::ReserveKeywordsAsUnique() {
  // skip the first underscore, so SSA variable starts from _1
  GetUniqueName("_");
  GetUniqueName("extern");
  GetUniqueName("void");
  GetUniqueName("int");
  GetUniqueName("float");
  GetUniqueName("double");
  GetUniqueName("char");
  GetUniqueName("unsigned");
  GetUniqueName("short");
  GetUniqueName("long");
  GetUniqueName("if");
  GetUniqueName("else");
  GetUniqueName("switch");
  GetUniqueName("case");
  GetUniqueName("default");
  GetUniqueName("for");
  GetUniqueName("do");
  GetUniqueName("while");
  GetUniqueName("goto");
  GetUniqueName("register");
  GetUniqueName("continue");
  GetUniqueName("break");
  GetUniqueName("typedef");
  GetUniqueName("struct");
  GetUniqueName("enum");
  GetUniqueName("union");
  GetUniqueName("return");
}

void CodeGenC::AddFunction(const PrimFunc& f) {
  // clear previous generated state.
  this->InitFuncState(f);
  // reserve keywords
  ReserveKeywordsAsUnique();

  auto global_symbol = f->GetAttr<String>(tvm::attr::kGlobalSymbol);
  ICHECK(global_symbol.defined())
      << "CodeGenC: Expect PrimFunc to have the global_symbol attribute";
  bool no_alias = f->HasNonzeroAttr(tir::attr::kNoAlias);

  this->PrintFuncPrefix();
  this->PrintExtraAttrs(f);
  this->stream << " " << static_cast<std::string>(global_symbol.value()) << "(";

  for (size_t i = 0; i < f->params.size(); ++i) {
    tir::Var v = f->params[i];
    std::string vid = AllocVarID(v.get());
    if (i != 0) stream << ", ";
    if (v.dtype().is_handle()) {
      auto it = alloc_storage_scope_.find(v.get());
      if (it != alloc_storage_scope_.end()) {
        PrintStorageScope(it->second, stream);
      }

      PrintType(GetType(v), stream);
      // Register handle data type
      // TODO(tvm-team): consider simply keep type info in the
      // type annotation(via a normalizing rewriting).
      if (auto* ptr = v->type_annotation.as<PointerTypeNode>()) {
        if (auto* prim = ptr->element_type.as<PrimTypeNode>()) {
          RegisterHandleType(v.get(), prim->dtype);
        }
      }

      if (no_alias) {
        PrintRestrict(v, stream);
      }
    } else {
      PrintType(GetType(v), stream);
    }
    stream << ' ' << vid;
  }
  stream << ") {\n";
  this->PreFunctionBody(f);
  int func_scope = this->BeginScope();
  this->PrintStmt(f->body);
  this->PrintFinalReturn();
  this->EndScope(func_scope);
  this->PrintIndent();
  this->stream << "}\n\n";
}

void CodeGenC::PrintFuncPrefix() { stream << "void"; }

void CodeGenC::PrintExtraAttrs(const PrimFunc& f) {}

void CodeGenC::PrintFinalReturn() {}

std::string CodeGenC::Finish() { return decl_stream.str() + stream.str(); }

void CodeGenC::PrintExpr(const PrimExpr& n, std::ostream& os) {  // NOLINT(*)
  if (print_ssa_form_) {
    std::ostringstream temp;
    VisitExpr(n, temp);
    os << SSAGetID(temp.str(), n.dtype());
  } else {
    VisitExpr(n, os);
  }
}

static bool CheckOutermostBracketMatch(const std::string& s);

void CodeGenC::PrintSSAAssign(const std::string& target, const std::string& src, DataType t) {
  PrintType(t, stream);
  stream << ' ' << target << " = ";
  if (CheckOutermostBracketMatch(src)) {
    stream << src.substr(1, src.length() - 2);
  } else {
    stream << src;
  }
  stream << ";\n";
}

// Print a reference expression to a buffer.
std::string CodeGenC::GetBufferRef(DataType t, const VarNode* buffer, PrimExpr index) {
  std::ostringstream os;
  std::string vid = GetVarID(buffer);
  std::string scope;
  if (alloc_storage_scope_.count(buffer)) {
    scope = alloc_storage_scope_.at(buffer);
  }
  bool is_vol = IsVolatile(buffer);
  if (t.lanes() == 1) {
    if (!HandleTypeMatch(buffer, t) || is_vol) {
      os << "((";
      if (is_vol) {
        os << "volatile ";
      }
      // Scope may not be part of type.
      if (!scope.empty() && IsScopePartOfType()) {
        PrintStorageScope(scope, os);
      }
      PrintType(t, os);
      os << "*)" << vid << ')';
    } else {
      os << vid;
    }
    os << "[(";
    PrintExpr(index, os);
    os << ")";
    if (t.bits() == 4 || (t.bits() == 1 && t.is_int())) {
      os << " / " << (32 / t.bits());
    }
    os << ']';
  } else {
    // Buffer declared as vector type.
    // optimize for case where it is in register,
    if (HandleTypeMatch(buffer, t) && !is_vol) {
      // optimize for constant access
      if (auto* ptr = index.as<tir::IntImmNode>()) {
        int64_t offset = ptr->value;
        ICHECK_EQ(offset % t.lanes(), 0) << "Find unaligned vector load to a vector type";
        os << vid << '[' << (offset / t.lanes()) << ']';
        return os.str();
      }
    }
    os << "((";
    if (is_vol) {
      os << "volatile ";
    }
    if (!scope.empty() && IsScopePartOfType()) {
      PrintStorageScope(scope, os);
    }
    PrintType(t, os);
    os << "*)(";
    if (!HandleTypeMatch(buffer, t.element_of())) {
      os << '(';
      if (!scope.empty() && IsScopePartOfType()) {
        PrintStorageScope(scope, os);
      }
      PrintType(t.element_of(), os);
      os << "*)";
    }
    if (t.bits() == 4 || (t.bits() == 1 && t.is_int())) {
      os << vid << ") + (";
      PrintExpr(index, os);
      os << ")";
      os << " / " << t.lanes();
      os << ")[0]";
    } else {
      os << vid << " + (";
      PrintExpr(index, os);
      os << ")";
      os << "))[0]";
    }
  }
  return os.str();
}

// Print a reference expression to a buffer.
std::string CodeGenC::GetStructRef(DataType t, const PrimExpr& buffer, const PrimExpr& index,
                                   int kind) {
  if (kind < builtin::kArrKindBound_) {
    std::ostringstream os;
    os << "(((DLTensor*)";
    this->PrintExpr(buffer, os);
    os << ")";
    if (kind == builtin::kArrAddr) {
      os << " + ";
      this->PrintExpr(index, os);
      os << ")";
      return os.str();
    }
    os << '[';
    this->PrintExpr(index, os);
    os << "].";
    // other case: get fields.
    switch (kind) {
      case builtin::kArrData:
        os << "data";
        break;
      case builtin::kArrShape:
        os << "shape";
        break;
      case builtin::kArrStrides:
        os << "strides";
        break;
      case builtin::kArrNDim:
        os << "ndim";
        break;
      case builtin::kArrTypeCode:
        os << "dtype.code";
        break;
      case builtin::kArrTypeBits:
        os << "dtype.bits";
        break;
      case builtin::kArrByteOffset:
        os << "byte_offset";
        break;
      case builtin::kArrTypeLanes:
        os << "dtype.lanes";
        break;
      case builtin::kArrDeviceId:
        os << "device.device_id";
        break;
      case builtin::kArrDeviceType:
        os << "device.device_type";
        break;
      default:
        LOG(FATAL) << "unknown field code";
    }
    os << ')';
    return os.str();
  } else {
    ICHECK_LT(kind, builtin::kTVMValueKindBound_);
    std::ostringstream os;
    os << "(((TVMValue*)";
    this->PrintExpr(buffer, os);
    os << ")[" << index << "].";
    if (t.is_handle()) {
      os << "v_handle";
    } else if (t.is_float()) {
      os << "v_float64";
    } else if (t.is_int()) {
      os << "v_int64";
    } else {
      LOG(FATAL) << "Do not know how to handle type" << t;
    }
    os << ")";
    return os.str();
  }
}

bool CodeGenC::HandleTypeMatch(const VarNode* buf_var, DataType t) const {
  auto it = handle_data_type_.find(buf_var);
  if (it == handle_data_type_.end()) return false;
  return it->second == t;
}

void CodeGenC::RegisterHandleType(const VarNode* buf_var, DataType t) {
  auto it = handle_data_type_.find(buf_var);
  if (it == handle_data_type_.end()) {
    handle_data_type_[buf_var] = t;
  } else {
    ICHECK(it->second == t) << "conflicting buf var type";
  }
}

void CodeGenC::PrintVecElemLoad(const std::string& vec, DataType t, int i,
                                std::ostream& os) {  // NOLINT(*)
  os << vec << ".s" << std::hex << i << std::dec;
}

void CodeGenC::PrintVecElemStore(const std::string& vec, DataType t, int i,
                                 const std::string& value) {
  this->PrintIndent();
  stream << vec << ".s" << std::hex << i << " = " << value << ";\n" << std::dec;
}

std::string CodeGenC::GetVecLoad(DataType t, const VarNode* buffer, PrimExpr base) {
  return GetBufferRef(t, buffer, base);
}

void CodeGenC::PrintVecStore(const VarNode* buffer, DataType t, PrimExpr base,
                             const std::string& value) {
  std::string ref = GetBufferRef(t, buffer, base);
  this->PrintIndent();
  stream << ref << " = " << value << ";\n";
}

std::string CodeGenC::CastFromTo(std::string value, DataType from, DataType target) {
  if (from == target) return value;
  std::ostringstream os;
  os << "((";
  this->PrintType(target, os);
  os << ")" << value << ")";
  return os.str();
}

void CodeGenC::BindThreadIndex(const IterVar& iv) { LOG(FATAL) << "not implemented"; }

void CodeGenC::PrintStorageSync(const CallNode* op) {  // NOLINT(*)
}

void CodeGenC::PrintStorageScope(const std::string& scope, std::ostream& os) {  // NOLINT(*)
  ICHECK_EQ(scope, "global");
}

inline void PrintConst(const IntImmNode* op, std::ostream& os, CodeGenC* p) {  // NOLINT(*)
  if (op->dtype == DataType::Int(32)) {
    std::ostringstream temp;
    temp << op->value;
    p->MarkConst(temp.str());
    os << temp.str();
  } else {
    os << "(";
    p->PrintType(op->dtype, os);
    os << ")" << op->value;
  }
}

inline void PrintUIntConst(DataType dtype, uint64_t val, std::ostream& os,
                           CodeGenC* p) {  // NOLINT(*)
  if (dtype == DataType::UInt(32)) {
    std::ostringstream temp;
    temp << val << "U";
    p->MarkConst(temp.str());
    os << temp.str();
  } else {
    os << "(";
    p->PrintType(dtype, os);
    os << ")" << val;
  }
}

inline void PrintConst(const FloatImmNode* op, std::ostream& os, CodeGenC* p) {  // NOLINT(*)
  switch (op->dtype.bits()) {
    case 64:
    case 32: {
      std::ostringstream temp;
      temp << std::scientific << op->value;
      if (op->dtype.bits() == 32) temp << 'f';
      p->MarkConst(temp.str());
      os << temp.str();
      break;
    }
    case 16: {
      os << '(';
      p->PrintType(op->dtype, os);
      os << ')' << std::scientific << op->value << 'f';
      break;
    }
    default:
      LOG(FATAL) << "Bad bit-width for float: " << op->dtype << "\n";
  }
}

void CodeGenC::VisitExpr_(const IntImmNode* op, std::ostream& os) {  // NOLINT(*)
  PrintConst(op, os, this);
}

void CodeGenC::VisitExpr_(const FloatImmNode* op, std::ostream& os) {  // NOLINT(*)
  PrintConst(op, os, this);
}
void CodeGenC::VisitExpr_(const StringImmNode* op, std::ostream& os) {  // NOLINT(*)
  os << "\"" << op->value << "\"";
}

template <typename T>
inline void PrintBinaryExpr(const T* op, const char* opstr,
                            std::ostream& os,  // NOLINT(*)
                            CodeGenC* p) {
  if (op->dtype.lanes() == 1) {
    if (isalpha(opstr[0])) {
      os << opstr << '(';
      p->PrintExpr(op->a, os);
      os << ", ";
      p->PrintExpr(op->b, os);
      os << ')';
    } else {
      os << '(';
      p->PrintExpr(op->a, os);
      os << ' ' << opstr << ' ';
      p->PrintExpr(op->b, os);
      os << ')';
    }
  } else {
    p->PrintVecBinaryOp(opstr, op->dtype, op->a, op->b, os);
  }
}

inline void PrintBinaryIntrinsic(const CallNode* op, const char* opstr,
                                 std::ostream& os,  // NOLINT(*)
                                 CodeGenC* p) {
  if (op->dtype.lanes() == 1) {
    ICHECK_EQ(op->args.size(), 2U);
    os << '(';
    p->PrintExpr(op->args[0], os);
    os << opstr;
    p->PrintExpr(op->args[1], os);
    os << ')';
  } else {
    p->PrintVecBinaryOp(opstr, op->dtype, op->args[0], op->args[1], os);
  }
}
void CodeGenC::VisitExpr_(const CastNode* op, std::ostream& os) {  // NOLINT(*)
  std::stringstream value;
  this->PrintExpr(op->value, value);
  os << CastFromTo(value.str(), op->value.dtype(), op->dtype);
}
void CodeGenC::VisitExpr_(const VarNode* op, std::ostream& os) {  // NOLINT(*)
  os << GetVarID(op);
}
void CodeGenC::VisitExpr_(const AddNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "+", os, this);
}
void CodeGenC::VisitExpr_(const SubNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "-", os, this);
}
void CodeGenC::VisitExpr_(const MulNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "*", os, this);
}
void CodeGenC::VisitExpr_(const DivNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "/", os, this);
}
void CodeGenC::VisitExpr_(const ModNode* op, std::ostream& os) {  // NOLINT(*)
  if (op->dtype.is_int() || op->dtype.is_uint()) {
    PrintBinaryExpr(op, "%", os, this);
  } else {
    ICHECK(op->dtype.is_float()) << "Expected floating point or integer dtype in Mod, but got "
                                 << op->dtype;
    if (op->dtype.bits() == 32) {
      PrintBinaryExpr(op, "fmodf", os, this);
    } else if (op->dtype.bits() == 64) {
      PrintBinaryExpr(op, "fmod", os, this);
    } else {
      ICHECK(false)
          << "Non single or double precision floating point in Mod, expected 32 or 64 bits but got "
          << op->dtype.bits() << " bits.";
    }
  }
}
void CodeGenC::VisitExpr_(const MinNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "min", os, this);
}
void CodeGenC::VisitExpr_(const MaxNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "max", os, this);
}
void CodeGenC::VisitExpr_(const EQNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "==", os, this);
}
void CodeGenC::VisitExpr_(const NENode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "!=", os, this);
}
void CodeGenC::VisitExpr_(const LTNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "<", os, this);
}
void CodeGenC::VisitExpr_(const LENode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "<=", os, this);
}
void CodeGenC::VisitExpr_(const GTNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, ">", os, this);
}
void CodeGenC::VisitExpr_(const GENode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, ">=", os, this);
}
void CodeGenC::VisitExpr_(const AndNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "&&", os, this);
}
void CodeGenC::VisitExpr_(const OrNode* op, std::ostream& os) {  // NOLINT(*)
  PrintBinaryExpr(op, "||", os, this);
}
void CodeGenC::VisitExpr_(const NotNode* op, std::ostream& os) {  // NOLINT(*)
  os << '!';
  PrintExpr(op->a, os);
}

void CodeGenC::PrintCallExtern(Type ret_type, String global_symbol, const Array<PrimExpr>& args,
                               bool skip_first_arg, std::ostream& os) {  // NOLINT(*)
  os << global_symbol << "(";
  for (size_t i = static_cast<size_t>(skip_first_arg); i < args.size(); ++i) {
    this->PrintExpr(args[i], os);
    if (i < args.size() - 1) {
      os << ", ";
    }
  }
  os << ")";
}

void CodeGenC::VisitExpr_(const CallNode* op, std::ostream& os) {  // NOLINT(*)
  if (auto* ptr_op = op->op.as<OpNode>()) {
    auto call_op = GetRef<Op>(ptr_op);

    if (op->op.same_as(builtin_call_extern_) || op->op.same_as(builtin_call_pure_extern_)) {
      ICHECK_GE(op->args.size(), 1U);
      auto func = Downcast<StringImm>(op->args[0]);
      this->PrintCallExtern(GetType(GetRef<PrimExpr>(op)), func->value, op->args, true, os);
    } else if (op_attr_global_symbol_.count(call_op)) {
      // call extern if the op itself have a global symbol.
      this->PrintCallExtern(GetType(GetRef<PrimExpr>(op)), op_attr_global_symbol_[call_op],
                            op->args, false, os);
    } else if (op->op.same_as(builtin::bitwise_and())) {
      PrintBinaryIntrinsic(op, " & ", os, this);
    } else if (op->op.same_as(builtin::large_uint_imm())) {
      ICHECK_EQ(op->args.size(), 2U);
      uint64_t low = static_cast<uint64_t>(Downcast<IntImm>(op->args[0])->value);
      uint64_t high = static_cast<uint64_t>(Downcast<IntImm>(op->args[1])->value);
      uint64_t val = (high << 32U) | low;
      PrintUIntConst(op->dtype, val, os, this);
    } else if (op->op.same_as(builtin::bitwise_xor())) {
      PrintBinaryIntrinsic(op, " ^ ", os, this);
    } else if (op->op.same_as(builtin::bitwise_or())) {
      PrintBinaryIntrinsic(op, " | ", os, this);
    } else if (op->op.same_as(builtin::bitwise_not())) {
      ICHECK_EQ(op->args.size(), 1U);
      os << "(~";
      this->PrintExpr(op->args[0], os);
      os << ')';
    } else if (op->op.same_as(builtin::shift_left())) {
      PrintBinaryIntrinsic(op, " << ", os, this);
    } else if (op->op.same_as(builtin::shift_right())) {
      PrintBinaryIntrinsic(op, " >> ", os, this);
    } else if (op->op.same_as(builtin::if_then_else())) {
      os << "(";
      PrintExpr(op->args[0], os);
      os << " ? ";
      PrintExpr(op->args[1], os);
      os << " : ";
      PrintExpr(op->args[2], os);
      os << ")";
    } else if (op->op.same_as(builtin::address_of())) {
      const LoadNode* l = op->args[0].as<LoadNode>();
      ICHECK(op->args.size() == 1 && l);
      os << "((";
      this->PrintType(l->dtype.element_of(), os);
      os << " *)" << this->GetVarID(l->buffer_var.get()) << " + "
         << "(";
      this->PrintExpr(l->index, os);
      if (l->dtype.bits() == 4 || (l->dtype.bits() == 1 && l->dtype.is_int())) {
        os << " / " << (32 / l->dtype.bits());
      }
      os << "))";
    } else if (op->op.same_as(builtin::tvm_struct_get())) {
      ICHECK_EQ(op->args.size(), 3U);
      os << GetStructRef(op->dtype, op->args[0], op->args[1], op->args[2].as<IntImmNode>()->value);
    } else if (op->op.same_as(builtin::isnullptr())) {
      ICHECK_EQ(op->args.size(), 1U);
      os << "(";
      this->PrintExpr(op->args[0], os);
      os << " == NULL)";
    } else if (op->op.same_as(builtin::reinterpret())) {
      int ssa_scope = BeginScope();
      std::string rhs = SSAGetID(PrintExpr(op->args[0]), op->args[0]->dtype);
      os << "(*(";
      this->PrintType(op->dtype, os);
      os << " *)(&(" << rhs << ")))";
      EndScope(ssa_scope);
    } else if (op->op.same_as(builtin::isnan())) {
      os << "(";
      this->PrintExpr(op->args[0], os);
      os << " != ";
      this->PrintExpr(op->args[0], os);
      os << ")";
    } else if (op->op.same_as(builtin::lookup_param())) {
      ICHECK_EQ(op->args.size(), 1);
      const StringImmNode* str = op->args[0].as<StringImmNode>();
      ICHECK(str != nullptr);
      os << "__tvm_param__" << str->value;
    } else {
      LOG(FATAL) << "Unresolved call " << op->op;
    }
  } else {
    ICHECK(op->op.as<GlobalVarNode>());
    LOG(FATAL) << "Do not yet support cross function call";
  }
}

void CodeGenC::PrintVecBinaryOp(const std::string& op, DataType t, PrimExpr lhs, PrimExpr rhs,
                                std::ostream& os) {  // NOLINT(*)
  if (isalpha(op[0])) {
    os << op << "(";
    this->PrintExpr(lhs, os);
    os << ", ";
    this->PrintExpr(rhs, os);
    os << ")";
  } else {
    os << "(";
    this->PrintExpr(lhs, os);
    os << ' ' << op << ' ';
    this->PrintExpr(rhs, os);
    os << ")";
  }
}

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) {  // NOLINT(*)
  int lanes = op->dtype.lanes();
  // delcare type.
  if (op->dtype.lanes() == 1) {
    std::string ref = GetBufferRef(op->dtype, op->buffer_var.get(), op->index);
    HandleVolatileLoads(ref, op, os);
  } else {
    ICHECK(is_one(op->predicate)) << "predicated load is not supported";

    bool can_vector_load = false;
    arith::PVar<PrimExpr> base;
    if (arith::ramp(base, 1, op->dtype.lanes()).Match(op->index)) {
      const RampNode* ramp = op->index.as<RampNode>();
      ICHECK(ramp);
      arith::ModularSet me = arith::Analyzer().modular_set(ramp->base);
      // The condition: {k * coeff + base} divisible by the alignment for any k
      if (me->coeff % op->dtype.lanes() == 0 && me->base % op->dtype.lanes() == 0) {
        can_vector_load = true;
      }
    }

    if (can_vector_load) {
      std::string ref = GetVecLoad(op->dtype, op->buffer_var.get(), base.Eval());
      HandleVolatileLoads(ref, op, os);
    } else {
      std::ostringstream svalue_expr;
      std::string sindex = SSAGetID(PrintExpr(op->index), op->index.dtype());
      std::string vid = GetVarID(op->buffer_var.get());
      DataType elem_type = op->dtype.element_of();
      for (int i = 0; i < lanes; ++i) {
        std::ostringstream value_temp;
        if (!HandleTypeMatch(op->buffer_var.get(), elem_type)) {
          value_temp << "((";
          if (op->buffer_var.get()->dtype.is_handle()) {
            auto it = alloc_storage_scope_.find(op->buffer_var.get());
            if (it != alloc_storage_scope_.end()) {
              PrintStorageScope(it->second, value_temp);
            }
          }
          PrintType(elem_type, value_temp);
          value_temp << "*)" << vid << ')';
        } else {
          value_temp << vid;
        }
        value_temp << '[';
        PrintVecElemLoad(sindex, op->index.dtype(), i, value_temp);
        value_temp << ']';
        PrintVecElemLoadExpr(op->dtype, i, value_temp.str(), svalue_expr);
      }
      os << svalue_expr.str();
    }
  }
}

void CodeGenC::VisitStmt_(const StoreNode* op) {
  DataType t = op->value.dtype();
  if (t.lanes() == 1) {
    std::string value = this->PrintExpr(op->value);
    std::string ref = this->GetBufferRef(t, op->buffer_var.get(), op->index);
    this->PrintIndent();
    stream << ref << " = " << value << ";\n";
  } else {
    ICHECK(is_one(op->predicate)) << "Predicated store is not supported";
    arith::PVar<PrimExpr> base;

    if (arith::ramp(base, 1, t.lanes()).Match(op->index)) {
      std::string value = this->PrintExpr(op->value);
      this->PrintVecStore(op->buffer_var.get(), t, base.Eval(), value);
    } else {
      // The assignment below introduces side-effect, and the resulting value cannot
      // be reused across multiple expression, thus a new scope is needed
      int vec_scope = BeginScope();

      // store elements seperately
      std::string index = SSAGetID(PrintExpr(op->index), op->index.dtype());
      std::string value = SSAGetID(PrintExpr(op->value), op->value.dtype());
      std::string vid = GetVarID(op->buffer_var.get());
      for (int i = 0; i < t.lanes(); ++i) {
        this->PrintIndent();
        DataType elem_type = t.element_of();
        if (!HandleTypeMatch(op->buffer_var.get(), elem_type)) {
          stream << "((";
          if (op->buffer_var.get()->dtype.is_handle()) {
            auto it = alloc_storage_scope_.find(op->buffer_var.get());
            if (it != alloc_storage_scope_.end()) {
              PrintStorageScope(it->second, stream);
            }
          }
          PrintType(elem_type, stream);
          stream << "*)" << vid << ')';
        } else {
          stream << vid;
        }
        stream << '[';
        PrintVecElemLoad(index, op->index.dtype(), i, stream);
        stream << "] = ";
        PrintVecElemLoad(value, op->value.dtype(), i, stream);
        stream << ";\n";
      }
      EndScope(vec_scope);
    }
  }
}

void CodeGenC::VisitExpr_(const LetNode* op, std::ostream& os) {  // NOLINT(*)
  auto it = let_binding_.find(op->var);
  if (it != let_binding_.end()) {
    ICHECK(deep_equal_(it->second->value, op->value))
        << "Let cannot bind the same var to two different values";
  } else {
    let_binding_[op->var] = op;
  }
  std::string value = PrintExpr(op->value);
  var_idmap_[op->var.get()] = value;
  os << PrintExpr(op->body);
}

void CodeGenC::VisitExpr_(const RampNode* op, std::ostream& os) {  // NOLINT(*)
  // constraint of current logic
  ICHECK_EQ(op->base.dtype(), DataType::Int(32));
  os << "((int" << op->lanes << ")(";
  for (int i = 0; i < op->lanes; i++) {
    os << "(" << PrintExpr(op->base) << ")"
       << "+(" << PrintExpr(op->stride) << "*" << i << ")";
    if (i != op->lanes - 1) os << ", ";
  }
  os << "))";
}

void CodeGenC::VisitExpr_(const ShuffleNode* op, std::ostream& os) {
  LOG(FATAL) << "Shuffle: not supported ";
}

void CodeGenC::VisitExpr_(const BroadcastNode* op, std::ostream& os) {  // NOLINT(*)
  LOG(FATAL) << "Broadcast: not supported ";
}

void CodeGenC::VisitExpr_(const SelectNode* op, std::ostream& os) {  // NOLINT(*)
  os << "(";
  PrintExpr(op->condition, os);
  os << " ? ";
  PrintExpr(op->true_value, os);
  os << " : ";
  PrintExpr(op->false_value, os);
  os << ")";
}

void CodeGenC::VisitStmt_(const LetStmtNode* op) {
  std::string value = PrintExpr(op->value);
  if (print_ssa_form_) {
    ICHECK(!var_idmap_.count(op->var.get()));
    var_idmap_[op->var.get()] = value;
  } else {
    PrintIndent();
    if (op->var.dtype() == DataType::Handle() && handle_data_type_.count(op->var.get())) {
      PrintType(handle_data_type_.at(op->var.get()), stream);
      stream << "* " << AllocVarID(op->var.get()) << " = (";
      PrintType(handle_data_type_.at(op->var.get()), stream);
      stream << "*)" << value << ";\n";
    } else {
      PrintType(op->var.dtype(), this->stream);
      this->stream << ' ' << AllocVarID(op->var.get()) << " = " << value << ";\n";
    }
  }
  PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const AllocateNode* op) {
  ICHECK(!is_zero(op->condition));
  std::string vid = AllocVarID(op->buffer_var.get());

  this->PrintIndent();
  int32_t constant_size = op->constant_allocation_size();
  ICHECK_GT(constant_size, 0) << "Can only handle constant size stack allocation for now";

  auto scope = GetPtrStorageScope(op->buffer_var);
  alloc_storage_scope_[op->buffer_var.get()] = scope;
  PrintStorageScope(scope, stream);

  PrintType(op->dtype, stream);
  stream << ' ' << vid << '[' << constant_size << "];\n";

  RegisterHandleType(op->buffer_var.get(), op->dtype);
  this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const AttrStmtNode* op) {
  if (op->attr_key == tir::attr::thread_extent) {
    IterVar iv = Downcast<IterVar>(op->node);
    if (iv->thread_tag.length() != 0) {
      if (!var_idmap_.count(iv->var.get())) {
        BindThreadIndex(iv);
      }
    }
  } else if (op->attr_key == tir::attr::volatile_scope) {
    const VarNode* v = op->node.as<VarNode>();
    ICHECK(v);
    volatile_buf_.insert(v);
  } else if (op->attr_key == tir::attr::pragma_import_c) {
    const StringImmNode* value = op->value.as<StringImmNode>();
    ICHECK(value != nullptr);
    decl_stream << value->value;
  }
  this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const AssertStmtNode* op) {
  std::string cond = PrintExpr(op->condition);
  PrintIndent();
  if (const auto* str = op->message.as<StringImmNode>()) {
    // GLOG style check
    stream << "ICHECK(" << cond << ") << \"" << str->value << "\";\n";
  } else {
    stream << "assert(" << cond << ");\n";
  }
  this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const ForNode* op) {
  std::string extent = PrintExpr(op->extent);
  PrintIndent();
  std::string vid = AllocVarID(op->loop_var.get());
  ICHECK(is_zero(op->min));
  stream << "for (";
  PrintType(op->loop_var.dtype(), stream);
  stream << ' ' << vid << " = 0; " << vid << " < " << extent << "; ++" << vid << ") {\n";
  int for_scope = BeginScope();
  PrintStmt(op->body);
  this->EndScope(for_scope);
  PrintIndent();
  stream << "}\n";
}

void CodeGenC::VisitStmt_(const WhileNode* op) {
  PrintIndent();
  stream << "while (" << PrintExpr(op->condition) << ") {\n";
  int while_scope = BeginScope();
  PrintStmt(op->body);
  this->EndScope(while_scope);
  PrintIndent();
  stream << "}\n";
}

void CodeGenC::VisitStmt_(const IfThenElseNode* op) {
  std::string cond = PrintExpr(op->condition);
  PrintIndent();
  if (cond[0] == '(' && cond[cond.length() - 1] == ')') {
    stream << "if " << cond << " {\n";
  } else {
    stream << "if (" << cond << ") {\n";
  }
  int then_scope = BeginScope();
  PrintStmt(op->then_case);
  this->EndScope(then_scope);

  if (op->else_case.defined()) {
    PrintIndent();
    stream << "} else {\n";
    int else_scope = BeginScope();
    PrintStmt(op->else_case);
    this->EndScope(else_scope);
  }
  PrintIndent();
  stream << "}\n";
}

void CodeGenC::VisitStmt_(const SeqStmtNode* op) {
  for (Stmt stmt : op->seq) {
    PrintStmt(stmt);
  }
}

void CodeGenC::VisitStmt_(const EvaluateNode* op) {
  if (is_const_int(op->value)) return;
  const CallNode* call = op->value.as<CallNode>();
  if (call) {
    if (call->op.same_as(builtin::tvm_storage_sync())) {
      this->PrintStorageSync(call);
      return;
    } else if (call->op.same_as(builtin::tvm_struct_set())) {
      ICHECK_EQ(call->args.size(), 4);
      int kind = call->args[2].as<IntImmNode>()->value;
      std::string ref = GetStructRef(call->args[3].dtype(), call->args[0], call->args[1], kind);
      std::string value = PrintExpr(call->args[3]);
      std::string cast;
      if (kind == builtin::kArrStrides) {
        // cast void* to int64_t*
        cast = call->args[3]->dtype.is_handle() ? "(int64_t*)" : "";
      } else if (kind == builtin::kArrDeviceType) {
        // cast int to enum
        cast = "(DLDeviceType)";
      }
      this->PrintIndent();
      this->stream << ref << " = " << cast << value << ";\n";
      return;
    }
  }
  std::string vid = this->PrintExpr(op->value);
  if (vid != "") {
    this->PrintIndent();
    this->stream << "(void)" << vid << ";\n";
  }
}

void CodeGenC::PrintVecElemLoadExpr(DataType t, int i, const std::string& value, std::ostream& os) {
  ICHECK_GT(t.lanes(), 1);
  if (t.bits() == 8 && (t.is_int() || t.is_uint())) {
    if (i != 0) {
      os << "|";
    }
    os << "((0x000000ff << " << i * 8 << ") & (" << value << " << " << i * 8 << "))";
    return;
  }

  if (i == 0) {
    os << "((";
    PrintType(t, os);
    os << ")(";
  }
  os << value;
  if (i != t.lanes() - 1) {
    os << ",";
  } else {
    os << "))";
  }
  return;
}

void CodeGenC::PrintRestrict(const Var& v, std::ostream& os) {
  if (restrict_keyword_.length() != 0) {
    os << ' ' << restrict_keyword_;
  }
}

static bool CheckOutermostBracketMatch(const std::string& s) {
  if (!s.empty() && s.front() == '(' && s.back() == ')') {
    size_t len = s.size();
    int n_unmatched = 0;
    for (size_t i = 0; i < len; ++i) {
      if (s[i] == '(') {
        n_unmatched++;
      } else if (s[i] == ')') {
        n_unmatched--;
      }
      if (n_unmatched == 0) {
        return i == len - 1;
      }
    }
  }
  return false;
}

}  // namespace codegen
}  // namespace tvm


text:
//
//  AKBeatenPlate.h
//  AudioKit
//
//  Auto-generated on 1/3/15.
//  Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//

#import "AKAudio.h"
#import "AKParameter+Operation.h"

/** A model of beaten plate consisting of two parallel delay-lines and two first-order lowpass filters.

 This  is a model of beaten plate consisting of two parallel delay-lines and two first-order lowpass filters. The two feedback lines are mixed and sent to the delay again each cycle.
 */

NS_ASSUME_NONNULL_BEGIN
@interface AKBeatenPlate : AKAudio
/// Instantiates the beaten plate with all values
/// @param input The excitation noise.
/// @param frequency1 The inverse of delay time for the first of two parallel delay lines. [Default Value: 5000]
/// @param frequency2 The inverse of delay time for the second of two parallel delay lines. [Default Value: 2000]
/// @param cutoffFrequency1 The filter cutoff frequency in Hz for the first low-pass filter. Updated at Control-rate. [Default Value: 3000]
/// @param cutoffFrequency2 The filter cutoff frequency in Hz for the second low-pass filter. Updated at Control-rate. [Default Value: 1500]
/// @param feedback1 The feedback factor for the first effects loop. Updated at Control-rate. [Default Value: 0.25]
/// @param feedback2 The feedback factor for the second effects loop. Updated at Control-rate. [Default Value: 0.25]
- (instancetype)initWithInput:(AKParameter *)input
                   frequency1:(AKParameter *)frequency1
                   frequency2:(AKParameter *)frequency2
             cutoffFrequency1:(AKParameter *)cutoffFrequency1
             cutoffFrequency2:(AKParameter *)cutoffFrequency2
                    feedback1:(AKParameter *)feedback1
                    feedback2:(AKParameter *)feedback2;

/// Instantiates the beaten plate with default values
/// @param input The excitation noise.
- (instancetype)initWithInput:(AKParameter *)input;

/// Instantiates the beaten plate with default values
/// @param input The excitation noise.
+ (instancetype)beatenPlateWithInput:(AKParameter *)input;

/// The inverse of delay time for the first of two parallel delay lines. [Default Value: 5000]
@property AKParameter *frequency1;

/// Set an optional frequency1
/// @param frequency1 The inverse of delay time for the first of two parallel delay lines. [Default Value: 5000]
- (void)setOptionalFrequency1:(AKParameter *)frequency1;

/// The inverse of delay time for the second of two parallel delay lines. [Default Value: 2000]
@property AKParameter *frequency2;

/// Set an optional frequency2
/// @param frequency2 The inverse of delay time for the second of two parallel delay lines. [Default Value: 2000]
- (void)setOptionalFrequency2:(AKParameter *)frequency2;

/// The filter cutoff frequency in Hz for the first low-pass filter. [Default Value: 3000]
@property AKParameter *cutoffFrequency1;

/// Set an optional cutoff frequency1
/// @param cutoffFrequency1 The filter cutoff frequency in Hz for the first low-pass filter. Updated at Control-rate. [Default Value: 3000]
- (void)setOptionalCutoffFrequency1:(AKParameter *)cutoffFrequency1;

/// The filter cutoff frequency in Hz for the second low-pass filter. [Default Value: 1500]
@property AKParameter *cutoffFrequency2;

/// Set an optional cutoff frequency2
/// @param cutoffFrequency2 The filter cutoff frequency in Hz for the second low-pass filter. Updated at Control-rate. [Default Value: 1500]
- (void)setOptionalCutoffFrequency2:(AKParameter *)cutoffFrequency2;

/// The feedback factor for the first effects loop. [Default Value: 0.25]
@property AKParameter *feedback1;

/// Set an optional feedback1
/// @param feedback1 The feedback factor for the first effects loop. Updated at Control-rate. [Default Value: 0.25]
- (void)setOptionalFeedback1:(AKParameter *)feedback1;

/// The feedback factor for the second effects loop. [Default Value: 0.25]
@property AKParameter *feedback2;

/// Set an optional feedback2
/// @param feedback2 The feedback factor for the second effects loop. Updated at Control-rate. [Default Value: 0.25]
- (void)setOptionalFeedback2:(AKParameter *)feedback2;

@end
NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
require 'whois/record/parser/whois.domainregistry.ie.rb'

describe Whois::Record::Parser::WhoisDomainregistryIe, "property_contacts_not_matching_id.expected" do

  subject do
    file = fixture("responses", "whois.domainregistry.ie/ie/property_contacts_not_matching_id.txt")
    part = Whois::Record::Part.new(body: File.read(file))
    described_class.new(part)
  end

  describe "#technical_contacts" do
    it do
      expect(subject.technical_contacts).to be_a(Array)
      expect(subject.technical_contacts.size).to eq(1)
      expect(subject.technical_contacts[0]).to be_a(Whois::Record::Contact)
      expect(subject.technical_contacts[0].type).to eq(Whois::Record::Contact::TYPE_TECHNICAL)
      expect(subject.technical_contacts[0].id).to eq("KG37-IEDR")
      expect(subject.technical_contacts[0].name).to eq("Michael McGovern")
    end
  end
end


text:
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from socket import socket, AF_INET, SOCK_DGRAM
import string, random
from time import time

from mbed_settings import CLIENT_ADDRESS

ECHO_PORT = 7

LEN_PACKET = 127
N_PACKETS = 5000
TOT_BITS = float(LEN_PACKET * N_PACKETS * 8) * 2
MEGA = float(1024 * 1024)
UPDATE_STEP = (N_PACKETS // 10)

class UDP_EchoClient(object):
    s = socket(AF_INET, SOCK_DGRAM)

    def __init__(self, host):
        self.host = host
        self.packet = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(LEN_PACKET))

    def __packet(self):
        # Comment out the checks when measuring the throughput
        # packet = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(LEN_PACKET))
        UDP_EchoClient.s.sendto(packet, (self.host, ECHO_PORT))
        data = UDP_EchoClient.s.recv(LEN_PACKET)
        # assert packet == data, "packet error:\n%s\n%s\n" % (packet, data)

    def test(self):
        start = time()
        for i in range(N_PACKETS):
            if (i % UPDATE_STEP) == 0: print('%.2f%%' % ((float(i)/float(N_PACKETS)) * 100.))
            self.__packet()
        t = time() - start
        print('Throughput: (%.2f)Mbits/s' % ((TOT_BITS / t)/MEGA))

while True:
    e = UDP_EchoClient(CLIENT_ADDRESS)
    e.test()


text:
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestCase.Core.Command;
using TestCase.Model.Locking;
using TestCase.Repository.Locking.Contracts;
using TestCase.Service.Locking.Events.Contracts;
using TestCase.Service.Locking.Lookups.Contract;

namespace TestCase.Service.Locking.Events.Aspects
{
    /// <summary>
    /// Post lock event command handler decorator.
    /// </summary>
    /// <typeparam name="TCommand">The type of the command.</typeparam>
    /// <seealso cref="TestCase.Core.Command.ICommandHandler{TCommand}" />
    public class PostLockEventCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand> where TCommand : IPostLockEventModel
    {
        private readonly ILockEventRepository lockEventRepository;
        private readonly ILockEventTypeLookup eventTypeLookup;
        private readonly ICommandHandler<TCommand> commandHandler;
        private readonly IMapper mapper;

        /// <summary>
        /// Initializes a new instance of the <see cref="PostEventCommandHandlerDecorator{TCommand}" /> class.
        /// </summary>
        /// <param name="lockEventRepository">The lock event repository.</param>
        /// <param name="commandHandler">The command handler.</param>
        public PostLockEventCommandHandlerDecorator(
            ILockEventRepository lockEventRepository,
            ILockEventTypeLookup eventTypeLookup,
            ICommandHandler<TCommand> commandHandler,
            IMapper mapper)
        {
            this.lockEventRepository = lockEventRepository;
            this.eventTypeLookup = eventTypeLookup;
            this.commandHandler = commandHandler;
            this.mapper = mapper;
        }

        /// <summary>
        /// Asynchronously handles the command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public async Task HandleAsync(TCommand command)
        {
            await this.commandHandler.HandleAsync(command);

            var lockEvent = this.mapper.Map<LockEvent>(command);
            lockEvent.LockEventTypeId = (await this.eventTypeLookup.GetAsync(command.LockEventType)).Id;
            lockEvent.Id = Guid.NewGuid();

            await this.lockEventRepository.InsertAsync(lockEvent);
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.sql.models;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/** Defines values for AutomaticTuningMode. */
public enum AutomaticTuningMode {
    /** Enum value Inherit. */
    INHERIT("Inherit"),

    /** Enum value Custom. */
    CUSTOM("Custom"),

    /** Enum value Auto. */
    AUTO("Auto"),

    /** Enum value Unspecified. */
    UNSPECIFIED("Unspecified");

    /** The actual serialized value for a AutomaticTuningMode instance. */
    private final String value;

    AutomaticTuningMode(String value) {
        this.value = value;
    }

    /**
     * Parses a serialized value to a AutomaticTuningMode instance.
     *
     * @param value the serialized value to parse.
     * @return the parsed AutomaticTuningMode object, or null if unable to parse.
     */
    @JsonCreator
    public static AutomaticTuningMode fromString(String value) {
        AutomaticTuningMode[] items = AutomaticTuningMode.values();
        for (AutomaticTuningMode item : items) {
            if (item.toString().equalsIgnoreCase(value)) {
                return item;
            }
        }
        return null;
    }

    @JsonValue
    @Override
    public String toString() {
        return this.value;
    }
}


text:
export function fetchComponents() {
  return dispatch => {
    dispatch({ type: 'COMPONENTS_FETCH_LOADING' });
    fetch('manifest.json', { credentials: 'same-origin' })
      .then(res => res.json())
      .then(res => dispatch(updateComponents(res)))
      .catch(err => dispatch(errorComponents(err)));
  };
}

function updateComponents(response) {
  return {
    type: 'COMPONENTS_FETCH_SUCCESS',
    components: response.components
  };
}

function errorComponents(err) {
  return {
    type: 'COMPONENTS_FETCH_ERROR',
    error: err
  };
}

export function toggleDrawer() {
  return {
    type: 'DRAWER_TOGGLE'
  };
}

export function componentView(component) {
  return {
    type: 'COMPONENT_VIEW',
    component
  };
}

export function toggleInfo() {
  return {
    type: 'INFO_TOGGLE'
  };
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>ACE Editor Example</title>
	<link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/extjs-4.1.1-gpl/resources/css/ext-all.css" />
</head>
<body>
	<script type="text/javascript" src="http://extjs.cachefly.net/extjs-4.1.1-gpl/bootstrap.js"></script>
	<script type="text/javascript" src="../../ux/aceeditor/ace-0.2.0/src/ace.js" charset="utf-8"></script>
    <script type="text/javascript" src="simple.js"></script>
</body>
</html>


text:
package photos

import (
	"gopkg.in/masci/flickr.v2"
)

type PhotoInfo struct {
	Id             string `xml:"id,attr"`
	Secret         string `xml:"secret,attr"`
	Server         string `xml:"server,attr"`
	Farm           string `xml:"farm,attr"`
	DateUploaded   string `xml:"dateuploaded,attr"`
	IsFavorite     bool   `xml:"isfavorite,attr"`
	License        string `xml:"license,attr"`
	// NOTE: one less than safety level set on upload (ie, here 0 = safe, 1 = moderate, 2 = restricted)
	//       while on upload, 1 = safe, 2 = moderate, 3 = restricted
	SafetyLevel    int    `xml:"safety_level,attr"`
	Rotation       int    `xml:"rotation,attr"`
	OriginalSecret string `xml:"originalsecret,attr"`
	OriginalFormat string `xml:"originalformat,attr"`
	Views          int    `xml:"views,attr"`
	Media          string `xml:"media,attr"`
	Title          string `xml:"title"`
	Description    string `xml:"description"`
	Visibility     struct {
		IsPublic bool `xml:"ispublic,attr"`
		IsFriend bool `xml:"isfriend,attr"`
		IsFamily bool `xml:"isfamily,attr"`
	} `xml:"visibility"`
	Dates struct {
		Posted           string `xml:"posted,attr"`
		Taken            string `xml:"taken,attr"`
		TakenGranularity string `xml:"takengranularity,attr"`
		TakenUnknown     string `xml:"takenunknown,attr"`
		LastUpdate       string `xml:"lastupdate,attr"`
	} `xml:"dates"`
	Permissions struct {
		PermComment string `xml:"permcomment,attr"`
		PermAdMeta  string `xml:"permadmeta,attr"`
	} `xml:"permissions"`
	Editability struct {
		CanComment string `xml:"cancomment,attr"`
		CanAddMeta string `xml:"canaddmeta,attr"`
	} `xml:"editability"`
	PublicEditability struct {
		CanComment string `xml:"cancomment,attr"`
		CanAddMeta string `xml:"canaddmeta,attr"`
	} `xml:"publiceditability"`
	Usage struct {
		CanDownload string `xml:"candownload,attr"`
		CanBlog     string `xml:"canblog,attr"`
		CanPrint    string `xml:"canprint,attr"`
		CanShare    string `xml:"canshare,attr"`
	} `xml:"usage"`
	Comments int `xml:"comments"`
	// Notes XXX: not handled yet
	// People XXX: not handled yet
	// Tags XXX: not handled yet
	// Urls XXX: not handled yet
}

type PhotoInfoResponse struct {
	flickr.BasicResponse
	Photo PhotoInfo `xml:"photo"`
}

// Delete a photo from Flickr
// This method requires authentication with 'delete' permission.
func Delete(client *flickr.FlickrClient, id string) (*flickr.BasicResponse, error) {
	client.Init()
	client.EndpointUrl = flickr.API_ENDPOINT
	client.HTTPVerb = "POST"
	client.Args.Set("method", "flickr.photos.delete")
	client.Args.Set("photo_id", id)
	client.OAuthSign()

	response := &flickr.BasicResponse{}
	err := flickr.DoPost(client, response)
	return response, err
}

// Get information about a Flickr photo
func GetInfo(client *flickr.FlickrClient, id string, secret string) (*PhotoInfoResponse, error) {
	client.Init()
	client.EndpointUrl = flickr.API_ENDPOINT
	client.HTTPVerb = "POST"
	client.Args.Set("method", "flickr.photos.getInfo")
	client.Args.Set("photo_id", id)
	if secret != "" {
		client.Args.Set("secret", secret)
	}
	client.OAuthSign()

	response := &PhotoInfoResponse{}
	err := flickr.DoPost(client, response)
	return response, err
}

// Set date posted and date taken on a Flickr photo
// datePosted and dateTaken are optional and may be set to ""
func SetDates(client *flickr.FlickrClient, id string, datePosted string, dateTaken string) (*flickr.BasicResponse, error) {
	client.Init()
	client.EndpointUrl = flickr.API_ENDPOINT
	client.HTTPVerb = "POST"
	client.Args.Set("method", "flickr.photos.setDates")
	client.Args.Set("photo_id", id)
	if datePosted != "" {
		client.Args.Set("date_posted", datePosted)
	}
	if dateTaken != "" {
		client.Args.Set("date_taken", dateTaken)
	}
	client.OAuthSign()

	response := &flickr.BasicResponse{}
	err := flickr.DoPost(client, response)
	return response, err
}


text:
<?php

namespace ActiveCollab\JobQueue\Command;

use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Exception;

/**
 * @package ActiveCollab\JobQueue\Command
 */
class JobsQueue extends Command
{
    /**
     * Configure command
     */
    protected function configure()
    {
        parent::configure();

        $this->setName('jobs_queue')
             ->setDescription('List all jobs queues grouped by type');
    }

    /**
     * @param  InputInterface  $input
     * @param  OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $type_rows = $this->dispatcher->getQueue()->countJobsByType();

            if (count($type_rows)) {
                $table = new Table($output);
                $table->setHeaders(['Event Type', 'Jobs Count']);

                foreach ($type_rows as $type => $queued_jobs_count) {
                    $table->addRow([$type, $queued_jobs_count]);
                }

                $table->render();
                $output->writeln('');

                return 0;
            } else {
                return $this->success('No jobs in the queue', $input, $output);
            }
        } catch (Exception $e) {
            return $this->abortDueToException($e, $input, $output);
        }
    }
}


text:
<?php

/**
 * @file EmailNotVerifiedException.php
 * @brief This file contains the EmailNotVerifiedException class.
 * @details
 * @author Filippo F. Fadda
 */

namespace ReIndex\Exception;

/**
 * @brief Exception thrown when the e-mail hasn't been verified by the user.
 */
class EmailNotVerifiedException extends \RuntimeException {}


text:
//
//  XMGTabBar.m
//  BuDeJie
//
//  Created by xiaomage on 16/3/12.
//  Copyright © 2016年 小码哥. All rights reserved.
//

#import "XMGTabBar.h"
#import "UIView+Frame.h"
@interface XMGTabBar ()

@property (nonatomic, weak) UIButton *plusButton;

/** 上一次点击的按钮 */
@property (nonatomic, weak) UIControl *previousClickedTabBarButton;
@end

@implementation XMGTabBar

- (UIButton *)plusButton
{
    if (_plusButton == nil) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [btn sizeToFit];
        [self addSubview:btn];

        _plusButton = btn;
    }
    return _plusButton;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    // 跳转tabBarButton位置
    NSInteger count = self.items.count;

    CGFloat btnW = self.xmg_width / (count + 1);
    CGFloat btnH = self.xmg_height;
    CGFloat x = 0;
    int i = 0;
    // 私有类:打印出来有个类,但是敲出来没有,说明这个类是系统私有类
    // 遍历子控件 调整布局
    for (UIControl *tabBarButton in self.subviews) {

        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            // 设置previousClickedTabBarButton默认值为最前面的按钮
            if (i == 0 && self.previousClickedTabBarButton == nil) {
                self.previousClickedTabBarButton = tabBarButton;
            }

            if (i == 2) {
                i += 1;
            }

            x = i * btnW;

            tabBarButton.frame = CGRectMake(x, 0, btnW, btnH);

            i++;

            // UIControlEventTouchDownRepeat : 在短时间内连续点击按钮

            // 监听点击
            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }

    // 调整发布按钮位置
    self.plusButton.center = CGPointMake(self.xmg_width * 0.5, self.xmg_height * 0.5);

}

/**
 *  tabBarButton的点击
 */
- (void)tabBarButtonClick:(UIControl *)tabBarButton
{
    if (self.previousClickedTabBarButton == tabBarButton) {
        // 发出通知,告知外界tabBarButton被重复点击了
        [[NSNotificationCenter defaultCenter] postNotificationName:XMGTabBarButtonDidRepeatClickNotification object:nil];
        NSLog(@". ...  .. .重复点击了 tabBaritem");
    }

    self.previousClickedTabBarButton = tabBarButton;
}

@end


text:
/**
 *
 */
package org.olat.lms.commons.i18n;

/**
 * @author patrick
 *
 */
public class TestI18nManagerInitializer {

    private I18nManager i18nManager;

    public TestI18nManagerInitializer(I18nManagerStaticDependenciesWrapper staticDependencies) {
        i18nManager = new I18nManager(staticDependencies);
    }

}


text: scheduler_rs_run_recipe "uox3::do_shard_backup"


text:
package org.apache.ignite.examples.ml.preprocessing;

import java.io.Serializable;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.examples.ml.util.DatasetHelper;
import org.apache.ignite.ml.dataset.DatasetFactory;
import org.apache.ignite.ml.dataset.feature.extractor.Vectorizer;
import org.apache.ignite.ml.dataset.feature.extractor.impl.DummyVectorizer;
import org.apache.ignite.ml.dataset.primitive.SimpleDataset;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.math.primitives.vector.impl.DenseVector;
import org.apache.ignite.ml.preprocessing.Preprocessor;
import org.apache.ignite.ml.preprocessing.normalization.NormalizationTrainer;

/**
 * Example that shows how to use normalization preprocessor to normalize each vector in the given data.
 *

 * Code in this example launches Ignite grid and fills the cache with simple test data.

 *

 * After that it defines preprocessors that extract features from an upstream data and normalize their values.

 *

 * Finally, it creates the dataset based on the processed data and uses Dataset API to find and output
 * various statistical metrics of the data.

 *

 * You can change the test data used in this example and re-run it to explore this functionality further.

 */
public class NormalizationExample {
    /** Run example. */
    public static void main(String[] args) throws Exception {
        try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
            System.out.println(">>> Normalization example started.");

            IgniteCache<Integer, Vector> data = null;
            try {
                data = createCache(ignite);

                Vectorizer<Integer, Vector, Integer, Double> vectorizer
                    = new DummyVectorizer<>(1, 2);

                // Defines second preprocessor that normalizes features.
                Preprocessor<Integer, Vector> preprocessor = new NormalizationTrainer<Integer, Vector>()
                    .withP(1)
                    .fit(ignite, data, vectorizer);

                // Creates a cache based simple dataset containing features and providing standard dataset API.
                try (SimpleDataset<?> dataset = DatasetFactory.createSimpleDataset(ignite, data, preprocessor)) {
                    new DatasetHelper(dataset).describe();
                }

                System.out.println(">>> Normalization example completed.");
            } finally {
                data.destroy();
            }
        } finally {
            System.out.flush();
        }
    }

    /** */
    private static IgniteCache<Integer, Vector> createCache(Ignite ignite) {
        CacheConfiguration<Integer, Vector> cacheConfiguration = new CacheConfiguration<>();

        cacheConfiguration.setName("PERSONS");
        cacheConfiguration.setAffinity(new RendezvousAffinityFunction(false, 2));

        IgniteCache<Integer, Vector> persons = ignite.createCache(cacheConfiguration);

        persons.put(1, new DenseVector(new Serializable[]{"Mike", 10, 20}));
        persons.put(2, new DenseVector(new Serializable[]{"John", 20, 10}));
        persons.put(3, new DenseVector(new Serializable[]{"George", 30, 0}));
        persons.put(4, new DenseVector(new Serializable[]{"Karl", 25, 15}));

        return persons;
    }
}


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

var smallDiff = function(){
	file = "football.csv";
	var smallestDifference = 0;
	var team = "";

	fs.readFile(file, "utf-8", function(err, data){
		if (err) {
			console.log(err);
			return;
		}

		var temp = data.toString();
		var line = temp.split('\n');

		for (var i = 1; i < line.length; i++){
			var value = line[i].split(',');
			var diff = Math.abs(value[5] - value[6]);

			if ( i === 1) smallestDifference = diff;

			if (diff < smallestDifference) {
				smallestDifference = diff;
				team = value[0];
			}
		}
		console.log(team);
	});
	//return team;
	return;
}

//console.log(smallDiff());
smallDiff();


text:
package org.mule.mvel2.ast;

import org.mule.mvel2.DataTypes;
import org.mule.mvel2.Operator;
import org.mule.mvel2.ParserContext;
import org.mule.mvel2.integration.VariableResolver;
import org.mule.mvel2.integration.VariableResolverFactory;
import org.mule.mvel2.math.MathProcessor;

/**
 * @author Christopher Brock
 */
public class PreFixIncNode extends ASTNode {
  private String name;

  public PreFixIncNode(String name, ParserContext pCtx) {
    super(pCtx);
    this.name = name;
    if (pCtx != null) {
      this.egressType = pCtx.getVarOrInputType(name);
    }
  }

  public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
    VariableResolver vResolver = factory.getVariableResolver(name);
    vResolver.setValue(ctx = MathProcessor.doOperations(vResolver.getValue(), Operator.ADD, DataTypes.INTEGER, 1));
    return ctx;
  }

  public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
    return getReducedValueAccelerated(ctx, thisValue, factory);
  }
}


text:
package org.pimslims.servlet.tag;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.pimslims.dao.AbstractModel;
import org.pimslims.dao.ModelImpl;
import org.pimslims.dao.WritableVersion;
import org.pimslims.metamodel.ModelObject;
import org.pimslims.model.people.Organisation;
import org.pimslims.presentation.ModelObjectShortBean;
import org.pimslims.presentation.mock.MockPageContext;

/**
 * ViewButtonTest
 *
 */
@Deprecated
// obsolete
public class RecordLinkTest extends TestCase {

    private final AbstractModel model;

    /**
     * @param methodName
     */
    public RecordLinkTest(final String methodName) {
        super(methodName);
        this.model = ModelImpl.getModel();
    }

    /**
     */
    public final void testDoStartTag() throws Exception {
        final WritableVersion version =
            this.model.getTestVersion();
        try {
            final RecordLink tag = new RecordLink();
            final MockPageContext mockPageContext = new MockPageContext();
            tag.setPageContext(mockPageContext);
            final ModelObject modelObject = new Organisation(version, "test" + System.currentTimeMillis());
            tag.setBean(new ModelObjectShortBean(modelObject));
            tag.doStartTag();
            final String output = mockPageContext.getOutput();
            Assert.assertTrue(output.contains(modelObject.get_Name() + "</a>"));
            Assert.assertTrue(output, output.contains("pims/View/" + modelObject.get_Hook()));
            // LATER more tests
        } finally {
            version.abort(); // not testing persistence
        }
    }

    /**
     */
    public final void testEscape() throws Exception {
        final WritableVersion version =
            this.model.getTestVersion();
        try {
            final RecordLink tag = new RecordLink();
            final MockPageContext mockPageContext = new MockPageContext();
            tag.setPageContext(mockPageContext);
            final ModelObject modelObject = new Organisation(version, "<test>" + System.currentTimeMillis());
            tag.setBean(new ModelObjectShortBean(modelObject));
            tag.doStartTag();
            final String output = mockPageContext.getOutput();
            Assert.assertFalse(output, output.contains(modelObject.get_Name()));
            Assert.assertTrue(output, output.contains("pims/View/" + modelObject.get_Hook()));
            // LATER more tests
        } finally {
            version.abort(); // not testing persistence
        }
    }

}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as TextUtils from '../../models/text_utils/text_utils.js';
import * as DataGrid from '../../ui/legacy/components/data_grid/data_grid.js';
import type * as Platform from '../../core/platform/platform.js';
import * as SourceFrame from '../../ui/legacy/components/source_frame/source_frame.js';
import * as UI from '../../ui/legacy/legacy.js';

import {DOMStorage} from './DOMStorageModel.js';
import {StorageItemsView} from './StorageItemsView.js';

const UIStrings = {
  /**
  *@description Text in DOMStorage Items View of the Application panel
  */
  domStorage: 'DOM Storage',
  /**
  *@description Text in DOMStorage Items View of the Application panel
  */
  key: 'Key',
  /**
  *@description Text for the value of something
  */
  value: 'Value',
  /**
  *@description Name for the "DOM Storage Items" table that shows the content of the DOM Storage.
  */
  domStorageItems: 'DOM Storage Items',
  /**
   *@description Text for announcing that the "DOM Storage Items" table was cleared, that is, all
   * entries were deleted.
   */
  domStorageItemsCleared: 'DOM Storage Items cleared',
  /**
  *@description Text in DOMStorage Items View of the Application panel
  */
  selectAValueToPreview: 'Select a value to preview',
  /**
   *@description Text for announcing a DOM Storage key/value item has been deleted
   */
  domStorageItemDeleted: 'The storage item was deleted.',
  /**
   *@description Text for announcing number of entries after filtering
   *@example {5} PH1
   */
  domStorageNumberEntries: 'Number of entries shown in table: {PH1}',
};
const str_ = i18n.i18n.registerUIStrings('panels/application/DOMStorageItemsView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class DOMStorageItemsView extends StorageItemsView {
  private domStorage: DOMStorage;
  private dataGrid: DataGrid.DataGrid.DataGridImpl<unknown>;
  private readonly splitWidget: UI.SplitWidget.SplitWidget;
  private readonly previewPanel: UI.Widget.VBox;
  private preview: UI.Widget.Widget|null;
  private previewValue: string|null;
  private eventListeners: Common.EventTarget.EventDescriptor[];

  constructor(domStorage: DOMStorage) {
    super(i18nString(UIStrings.domStorage), 'domStoragePanel');

    this.domStorage = domStorage;

    this.element.classList.add('storage-view', 'table');

    const columns = ([
      {id: 'key', title: i18nString(UIStrings.key), sortable: false, editable: true, longText: true, weight: 50},
      {id: 'value', title: i18nString(UIStrings.value), sortable: false, editable: true, longText: true, weight: 50},
    ] as DataGrid.DataGrid.ColumnDescriptor[]);
    this.dataGrid = new DataGrid.DataGrid.DataGridImpl({
      displayName: i18nString(UIStrings.domStorageItems),
      columns,
      editCallback: this.editingCallback.bind(this),
      deleteCallback: this.deleteCallback.bind(this),
      refreshCallback: this.refreshItems.bind(this),
    });
    this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, event => {
      void this.previewEntry(event.data);
    });
    this.dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode, () => {
      void this.previewEntry(null);
    });
    this.dataGrid.setStriped(true);
    this.dataGrid.setName('DOMStorageItemsView');

    this.splitWidget = new UI.SplitWidget.SplitWidget(
        /* isVertical: */ false, /* secondIsSidebar: */ true, 'domStorageSplitViewState');
    this.splitWidget.show(this.element);

    this.previewPanel = new UI.Widget.VBox();
    this.previewPanel.setMinimumSize(0, 50);
    const resizer = this.previewPanel.element.createChild('div', 'preview-panel-resizer');
    const dataGridWidget = this.dataGrid.asWidget();
    dataGridWidget.setMinimumSize(0, 50);
    this.splitWidget.setMainWidget(dataGridWidget);
    this.splitWidget.setSidebarWidget(this.previewPanel);
    this.splitWidget.installResizer(resizer);

    this.preview = null;
    this.previewValue = null;

    this.showPreview(null, null);

    this.eventListeners = [];
    this.setStorage(domStorage);
  }

  setStorage(domStorage: DOMStorage): void {
    Common.EventTarget.removeEventListeners(this.eventListeners);
    this.domStorage = domStorage;
    this.eventListeners = [
      this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemsCleared, this.domStorageItemsCleared, this),
      this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemRemoved, this.domStorageItemRemoved, this),
      this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemAdded, this.domStorageItemAdded, this),
      this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemUpdated, this.domStorageItemUpdated, this),
    ];
    this.refreshItems();
  }

  private domStorageItemsCleared(): void {
    if (!this.isShowing() || !this.dataGrid) {
      return;
    }

    this.dataGrid.rootNode().removeChildren();
    this.dataGrid.addCreationNode(false);
    UI.ARIAUtils.alert(i18nString(UIStrings.domStorageItemsCleared));
    this.setCanDeleteSelected(false);
  }

  private domStorageItemRemoved(event: Common.EventTarget.EventTargetEvent<DOMStorage.DOMStorageItemRemovedEvent>):
      void {
    if (!this.isShowing() || !this.dataGrid) {
      return;
    }

    const storageData = event.data;
    const rootNode = this.dataGrid.rootNode();
    const children = rootNode.children;

    for (let i = 0; i < children.length; ++i) {
      const childNode = children[i];
      if (childNode.data.key === storageData.key) {
        rootNode.removeChild(childNode);
        this.setCanDeleteSelected(children.length > 1);
        return;
      }
    }
  }

  private domStorageItemAdded(event: Common.EventTarget.EventTargetEvent<DOMStorage.DOMStorageItemAddedEvent>): void {
    if (!this.isShowing() || !this.dataGrid) {
      return;
    }

    const storageData = event.data;
    const rootNode = this.dataGrid.rootNode();
    const children = rootNode.children;

    for (let i = 0; i < children.length; ++i) {
      if (children[i].data.key === storageData.key) {
        return;
      }
    }

    const childNode = new DataGrid.DataGrid.DataGridNode({key: storageData.key, value: storageData.value}, false);
    rootNode.insertChild(childNode, children.length - 1);
  }

  private domStorageItemUpdated(event: Common.EventTarget.EventTargetEvent<DOMStorage.DOMStorageItemUpdatedEvent>):
      void {
    if (!this.isShowing() || !this.dataGrid) {
      return;
    }

    const storageData = event.data;
    const childNode = this.dataGrid.rootNode().children.find(
        (child: DataGrid.DataGrid.DataGridNode<unknown>) => child.data.key === storageData.key);
    if (!childNode || childNode.data.value === storageData.value) {
      return;
    }

    childNode.data.value = storageData.value;
    childNode.refresh();
    if (!childNode.selected) {
      return;
    }
    void this.previewEntry(childNode);
    this.setCanDeleteSelected(true);
  }

  private showDOMStorageItems(items: string[][]): void {
    const rootNode = this.dataGrid.rootNode();
    let selectedKey: null = null;
    for (const node of rootNode.children) {
      if (!node.selected) {
        continue;
      }
      selectedKey = node.data.key;
      break;
    }
    rootNode.removeChildren();
    let selectedNode: DataGrid.DataGrid.DataGridNode<unknown>|null = null;
    const filteredItems = (item: string[]): string => `${item[0]} ${item[1]}`;
    const filteredList = this.filter(items, filteredItems);
    for (const item of filteredList) {
      const key = item[0];
      const value = item[1];
      const node = new DataGrid.DataGrid.DataGridNode({key: key, value: value}, false);
      node.selectable = true;
      rootNode.appendChild(node);
      if (!selectedNode || key === selectedKey) {
        selectedNode = node;
      }
    }
    if (selectedNode) {
      selectedNode.selected = true;
    }
    this.dataGrid.addCreationNode(false);
    this.setCanDeleteSelected(Boolean(selectedNode));
    UI.ARIAUtils.alert(i18nString(UIStrings.domStorageNumberEntries, {PH1: filteredList.length}));
  }

  deleteSelectedItem(): void {
    if (!this.dataGrid || !this.dataGrid.selectedNode) {
      return;
    }

    this.deleteCallback(this.dataGrid.selectedNode);
  }

  refreshItems(): void {
    void this.domStorage.getItems().then(items => items && this.showDOMStorageItems(items));
  }

  deleteAllItems(): void {
    this.domStorage.clear();
    // explicitly clear the view because the event won't be fired when it has no items
    this.domStorageItemsCleared();
  }

  private editingCallback(
      editingNode: DataGrid.DataGrid.DataGridNode<unknown>, columnIdentifier: string, oldText: string,
      newText: string): void {
    const domStorage = this.domStorage;
    if (columnIdentifier === 'key') {
      if (typeof oldText === 'string') {
        domStorage.removeItem(oldText);
      }
      domStorage.setItem(newText, editingNode.data.value || '');
      this.removeDupes(editingNode);
    } else {
      domStorage.setItem(editingNode.data.key || '', newText);
    }
  }

  private removeDupes(masterNode: DataGrid.DataGrid.DataGridNode<unknown>): void {
    const rootNode = this.dataGrid.rootNode();
    const children = rootNode.children;
    for (let i = children.length - 1; i >= 0; --i) {
      const childNode = children[i];
      if ((childNode.data.key === masterNode.data.key) && (masterNode !== childNode)) {
        rootNode.removeChild(childNode);
      }
    }
  }

  private deleteCallback(node: DataGrid.DataGrid.DataGridNode<unknown>): void {
    if (!node || node.isCreationNode) {
      return;
    }

    if (this.domStorage) {
      this.domStorage.removeItem(node.data.key);
    }

    UI.ARIAUtils.alert(i18nString(UIStrings.domStorageItemDeleted));
  }

  private showPreview(preview: UI.Widget.Widget|null, value: string|null): void {
    if (this.preview && this.previewValue === value) {
      return;
    }
    if (this.preview) {
      this.preview.detach();
    }
    if (!preview) {
      preview = new UI.EmptyWidget.EmptyWidget(i18nString(UIStrings.selectAValueToPreview));
    }
    this.previewValue = value;
    this.preview = preview;
    preview.show(this.previewPanel.contentElement);
  }

  private async previewEntry(entry: DataGrid.DataGrid.DataGridNode<unknown>|null): Promise<void> {
    const value = entry && entry.data && entry.data.value;
    if (entry && entry.data && entry.data.value) {
      const protocol = this.domStorage.isLocalStorage ? 'localstorage' : 'sessionstorage';
      const url = `${protocol}://${entry.key}` as Platform.DevToolsPath.UrlString;
      const provider = TextUtils.StaticContentProvider.StaticContentProvider.fromString(
          url, Common.ResourceType.resourceTypes.XHR, (value as string));
      const preview = await SourceFrame.PreviewFactory.PreviewFactory.createPreview(provider, 'text/plain');
      // Selection could've changed while the preview was loaded
      if (entry.selected) {
        this.showPreview(preview, value);
      }
    } else {
      this.showPreview(null, value);
    }
  }
}


text:
package com.twitter.finagle.scribe

import com.twitter.conversions.DurationOps._
import com.twitter.finagle.stats.InMemoryStatsReceiver
import com.twitter.finagle.thrift.scribe.thriftscala.LogEntry
import com.twitter.finagle.thrift.scribe.thriftscala.ResultCode
import com.twitter.finagle.thrift.scribe.thriftscala.Scribe
import com.twitter.finagle.ChannelWriteException
import com.twitter.finagle.Service
import com.twitter.util.Await
import com.twitter.util.Awaitable
import com.twitter.util.Future
import java.nio.charset.{StandardCharsets => JChar}
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.when
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.concurrent.Eventually

private object PublisherTest {
  val TestArrayBytes: Array[Byte] = "Hello, world".getBytes(JChar.UTF_8)
  val TestLogEntries: Seq[LogEntry] = Seq(
    LogEntry(
      category = "scribe",
      message = "Hello, world\n"
    ))

  class ScribeClient extends Scribe.MethodPerEndpoint {
    var messages: Seq[LogEntry] = Seq.empty[LogEntry]
    var response: Future[ResultCode] = Future.value(ResultCode.Ok)
    def log(msgs: scala.collection.Seq[LogEntry]): Future[ResultCode] = {
      messages ++= msgs
      response
    }
  }
}

class PublisherTest extends AnyFunSuite with MockitoSugar with Eventually {
  import PublisherTest._

  private def await[A](a: Awaitable[A]): A = Await.result(a, 2.seconds)

  test("exhaustively retries TryLater responses -- log entries") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val alwaysTryLaterSvc = Service.const(Future.value(ResultCode.TryLater))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(alwaysTryLaterSvc))
        .build(category = "category", label = "foo-publisher")
    await(publisher.write(TestLogEntries))

    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 3)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)

    eventually {
      assert(
        inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(2))
      assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
      assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
      assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
      assert(
        inMemoryStatsReceiver.counter(
          "clnt",
          "foo-publisher",
          "logical",
          "failures",
          "com.twitter.finagle.service.ResponseClassificationSyntheticException")() == 1)
    }
  }

  test("exhaustively retries TryLater responses -- array bytes") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val alwaysTryLaterSvc = Service.const(Future.value(ResultCode.TryLater))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(alwaysTryLaterSvc))
        .build(category = "category", label = "foo-publisher")
    await(publisher.write(TestArrayBytes))

    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 3)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(2))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "com.twitter.finagle.service.ResponseClassificationSyntheticException")() == 1)
  }

  test("marks unknown result code as non-retryable failures -- log entries") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val unknownResultCodeSvc = Service.const(Future.value(ResultCode.EnumUnknownResultCode(100)))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(unknownResultCodeSvc))
        .build(category = "category", label = "foo-publisher")
    await(publisher.write(TestLogEntries))

    assert(
      inMemoryStatsReceiver
        .counter("foo-publisher", "scribe", "error", "EnumUnknownResultCode100")() == 1)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 0)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(0))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "com.twitter.finagle.service.ResponseClassificationSyntheticException")() == 1)
  }

  test("marks unknown result code as non-retryable failures -- array bytes") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val unknownResultCodeSvc = Service.const(Future.value(ResultCode.EnumUnknownResultCode(100)))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(unknownResultCodeSvc))
        .build(category = "category", label = "foo-publisher")
    await(publisher.write(TestArrayBytes))

    assert(
      inMemoryStatsReceiver
        .counter("foo-publisher", "scribe", "error", "EnumUnknownResultCode100")() == 1)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 0)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(0))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "com.twitter.finagle.service.ResponseClassificationSyntheticException")() == 1)
  }

  test("does not retry failures handled by the RequeueFilter -- log entries") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val failingLogSvc = Service.const(Future.exception(new ChannelWriteException(None)))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(failingLogSvc))
        .build(category = "category", label = "foo-publisher")
    intercept[ChannelWriteException] {
      await(publisher.write(TestLogEntries))
    }

    assert(
      inMemoryStatsReceiver.counter(
        "foo-publisher",
        "scribe",
        "error",
        "com.twitter.finagle.ChannelWriteException")() == 1)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 0)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(0))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "com.twitter.finagle.ChannelWriteException")() == 1)
  }

  test("does not retry failures handled by the RequeueFilter -- array bytes") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val failingLogSvc = Service.const(Future.exception(new ChannelWriteException(None)))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(failingLogSvc))
        .build(category = "category", label = "foo-publisher")
    intercept[ChannelWriteException] {
      await(publisher.write(TestArrayBytes))
    }

    assert(
      inMemoryStatsReceiver.counter(
        "foo-publisher",
        "scribe",
        "error",
        "com.twitter.finagle.ChannelWriteException")() == 1)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 0)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(0))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "com.twitter.finagle.ChannelWriteException")() == 1)
  }

  test("reports correct metrics after a successful retry -- log entries") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val tryLaterThenOkSvc = mock[Service[Scribe.Log.Args, ResultCode]]
    when(tryLaterThenOkSvc.apply(any[Scribe.Log.Args]))
      .thenReturn(Future.value(ResultCode.TryLater))
      .thenReturn(Future.value(ResultCode.Ok))

    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(tryLaterThenOkSvc))
        .build(category = "category", label = "foo-publisher")
    await(publisher.write(TestLogEntries))

    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 1)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 1)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(1))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 1)
  }

  test("reports correct metrics after a successful retry -- array bytes") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val tryLaterThenOkSvc = mock[Service[Scribe.Log.Args, ResultCode]]
    when(tryLaterThenOkSvc.apply(any[Scribe.Log.Args]))
      .thenReturn(Future.value(ResultCode.TryLater))
      .thenReturn(Future.value(ResultCode.Ok))

    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(tryLaterThenOkSvc))
        .build(category = "category", label = "foo-publisher")
    await(publisher.write(TestArrayBytes))

    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 1)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 1)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(1))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 1)
  }

  test("reports errors -- log entries") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val failingLogSvc = Service.const(Future.exception(new IllegalArgumentException))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(failingLogSvc))
        .build(category = "category", label = "foo-publisher")
    intercept[IllegalArgumentException] {
      await(publisher.write(TestLogEntries))
    }

    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 0)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)
    assert(
      inMemoryStatsReceiver
        .counter("foo-publisher", "scribe", "error", "java.lang.IllegalArgumentException")() == 1)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(0))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "java.lang.IllegalArgumentException")() == 1)
  }

  test("reports errors -- array bytes") {
    val inMemoryStatsReceiver = new InMemoryStatsReceiver()
    val failingLogSvc = Service.const(Future.exception(new IllegalArgumentException))
    val publisher =
      Publisher.builder
        .withDest("inet!localhost:1234")
        .withStatsReceiver(inMemoryStatsReceiver)
        .withLogServiceOverride(Some(failingLogSvc))
        .build(category = "category", label = "foo-publisher")
    intercept[IllegalArgumentException] {
      await(publisher.write(TestArrayBytes))
    }

    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "try_later")() == 0)
    assert(inMemoryStatsReceiver.counter("foo-publisher", "scribe", "ok")() == 0)
    assert(
      inMemoryStatsReceiver
        .counter("foo-publisher", "scribe", "error", "java.lang.IllegalArgumentException")() == 1)

    assert(inMemoryStatsReceiver.stat("clnt", "foo-publisher", "retries")().map(_.toInt) == Seq(0))
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "requests")() == 1)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "success")() == 0)
    assert(inMemoryStatsReceiver.counter("clnt", "foo-publisher", "logical", "failures")() == 1)
    assert(
      inMemoryStatsReceiver.counter(
        "clnt",
        "foo-publisher",
        "logical",
        "failures",
        "java.lang.IllegalArgumentException")() == 1)
  }

  test("formulate scribe log message correctly from array bytes") {
    val scribe = new ScribeClient
    val publisher = new Publisher("scribe", ScribeStats.Empty, scribe)

    val message: Array[Byte] = "Hello, world".getBytes(JChar.UTF_8)
    val expected = LogEntry(
      category = "scribe",
      message = "Hello, world\n"
    )

    publisher.write(message)
    assert(scribe.messages == Seq(expected))
  }
}


text:
package com.visural.common;

import com.visural.common.apacherepack.FastDateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * Date utilities
 *
 * @version $Id: DateUtil.java 96 2010-10-13 09:45:27Z tibes80@gmail.com $
 * @author Richard Nichols
 */
public class DateUtil {

    /**
     * Makes a copy of the given Date. nulls are passed through.
     * @param date
     * @return
     */
    public static Date copy(Date date) {
        return (date == null ? null : new Date(date.getTime()));
    }

    /**
     * Formats a date according to the SimpleDateFormat format string provided
     * @param date the date to display
     * @param sFormat the format string according to the SimpleDateFormat class specs
     * @return the resulting formatted string
     */
    public static String format(Date date, String format) {
        return date == null ? null : FastDateFormat.getInstance(format).format(date);
    }

    public static String format(Date d, String format, TimeZone timeZone) {
        return d == null ? null : FastDateFormat.getInstance(format, timeZone).format(d);
    }

    /**
     * Returns a date in the format used by the XML standard (ISO format)
     *
     * @param date
     * @return
     */
    public static String formatXmlIsoDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        calendar.setTime(date);
        StringBuilder buffer = new StringBuilder();
        buffer.append(calendar.get(Calendar.YEAR));
        buffer.append("-");
        buffer.append(twoDigit(calendar.get(Calendar.MONTH) + 1));
        buffer.append("-");
        buffer.append(twoDigit(calendar.get(Calendar.DAY_OF_MONTH)));
        buffer.append("T");
        buffer.append(twoDigit(calendar.get(Calendar.HOUR_OF_DAY)));
        buffer.append(":");
        buffer.append(twoDigit(calendar.get(Calendar.MINUTE)));
        buffer.append(":");
        buffer.append(twoDigit(calendar.get(Calendar.SECOND)));
        buffer.append(".");
        buffer.append(twoDigit(calendar.get(Calendar.MILLISECOND) / 10));
        buffer.append("Z");
        return buffer.toString();
    }

    private static String twoDigit(int i) {
        if (i >= 0 && i < 10) {
            return "0" + String.valueOf(i);
        }
        return String.valueOf(i);
    }

    /**
     * Pattern for RFC1123 (http date header)
     */
    public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

    /**
     * Return a date formatted to RFC1123 suitable for Http header
     * @param date
     * @return
     */
    public static String formatHttpDate(Date date) {
        return format(date, PATTERN_RFC1123);
    }

    /**
     * Return a date formatted to RFC1123 suitable for Http header
     * @param millis
     * @return
     */
    public static String formatHttpDate(long millis) {
        return formatHttpDate(new Date(millis));
    }

    /**
     * Parses a string into Date using the SimpleDateFormat format string provided.
     * @param dateStr
     * @param format
     * @return
     */
    public static Date parseDate(String dateStr, String... formats) {
        return parseDate(dateStr, null, formats);
    }

    /**
     * Parses a string into Date using the SimpleDateFormat format string provided.
     * @param dateStr
     * @param format
     * @return
     */
    public static Date parseDate(String dateStr, TimeZone timeZone, String... formats) {
        if (dateStr == null) {
            return null;
        }
        for (String format : formats) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            if (timeZone != null) {
                sdf.setTimeZone(timeZone);
            }
            Date result = sdf.parse(dateStr, new ParsePosition(0));
            if (result != null) {
                return result;
            }
        }
        return null;
    }

    /**
     * Converts a date to a SQL timestamp
     * @param d
     * @return
     */
    public static java.sql.Timestamp dateToTimestamp(java.util.Date d) {
        if (d == null) {
            return null;
        }
        java.sql.Timestamp ts;
        ts = new java.sql.Timestamp(d.getTime());
        return ts;
    }

    /**
     * Convers a SQL timestamp to a Date
     * @param ts
     * @return
     */
    public static java.util.Date timestampToDate(java.sql.Timestamp ts) {
        if (ts == null) {
            return null;
        }
        Date d = new Date(ts.getTime());
        return d;
    }
}


text:
"use strict"

let request = require('request'),
  FileCookieStore = require('tough-cookie-filestore'),
  j = request.jar(new FileCookieStore('./cookies.json')),
  _ = require('lodash'),
  fs = require ('fs')

request = request.defaults({jar: j})

let requestCount = 0,
  lastUrl = ''

let myOptions = {
  headers: {
    'User-Agent': 'Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
    //'Upgrade-Insecure-Requests': 1,
    //'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    //'Accept-Encoding': 'gzip, deflate, sdch, br',
    //'Accept-Language': 'en-US,en;q=0.8,af;q=0.6,id;q=0.4,ms;q=0.2',
    //'Connection': 'keep-alive',
    //'Cache-Control': 'max-age=0'
  }
}

let myIp = '',
  username = 'YUNUSIND1125',
  password = '753159'

let LETS_DEBUG = true

function promised(method, url, options) {

  if (lastUrl)
    myOptions.headers.Referer = lastUrl

  lastUrl = url

  return new Promise((resolve, reject) => {
    request[method](url, options, (e, r, b) => {
      // saving request
      if (LETS_DEBUG) {
        let fs = require('fs')
        let fn = `bca-request-${++requestCount}`
        fs.writeFile(`${fn}.txt`, JSON.stringify(r, null, 2), () => {
          console.log(`${fn} was saved!`)
        })
      }

      // return result..
      if (e) return reject(e)
      resolve(b)
    })
  })
}

// 1. retrieve the ip
return promised('get', 'http://myjsonip.appspot.com', {json: true})
  .then((res) => {
    return myIp = res.ip
  })
  // 2. open login page
  .then(() => {
    return promised('get', 'https://m.klikbca.com/login.jsp', myOptions)
  })
  // 3. post login
  .then(() => {
    // myOptions.headers.Origin = 'https://m.klikbca.com'
    myOptions.form = {
      'value(user_id)': username,
      'value(pswd)': password,
      'value(Submit)': 'LOGIN',
      'value(actions)': 'login',
      'value(user_ip)': myIp,
      'user_ip': myIp,
      'value(mobile)': 'true',
      'mobile': 'true',
    }

    return promised('post', 'https://m.klikbca.com/authentication.do', myOptions)
  })
  // 4. open menu
  .then(() => {
    delete myOptions.form
    return promised('post', 'https://m.klikbca.com/accountstmt.do?value(actions)=menu', myOptions)
  })
  // 5. balance inquiry
  .then(() => {
    return promised('post', 'https://m.klikbca.com/balanceinquiry.do', myOptions)
  })
  // parse the balance..
  .then(balancePage => {
    let fs = require('fs')
    let fn = `bca-balance`
    fs.writeFile(`${fn}.html`, balancePage, () => {
      console.log(`${fn} was saved!`)
    })
  })
  // 6. re-open menu
  .then(() => {
    return promised('post', 'https://m.klikbca.com/accountstmt.do?value(actions)=menu', myOptions)
  })
  // 7. transactions inquiry
  .then(() => {
    return promised('post', 'https://m.klikbca.com/accountstmt.do?value(actions)=acct_stmt', myOptions)
  })
  // 8. posting inquiry
  .then(() => {
    let moment = require('moment'),
      endDate = moment().utcOffset(7),
      startDate = endDate.subtract(3, 'days'),
      beginDate = {
        d: startDate.format('DD'),
        m: startDate.format('MM'),
        y: startDate.format('YYYY')
      },
      finDate = {
        d: endDate.format('DD'),
        m: endDate.format('MM'),
        y: endDate.format('YYYY')
      }

    myOptions.form = {
      r1: 1,
      'value(D1)': 0,
      'value(startDt)': beginDate.d,
      'value(startMt)': beginDate.m,
      'value(startYr)': beginDate.y,
      'value(endDt)': finDate.d,
      'value(endMt)': finDate.m,
      'value(endYr)': finDate.y,
    }
    return promised('post', 'https://m.klikbca.com/accountstmt.do?value(actions)=acctstmtview', myOptions)
  })
  // parse the transactions..
  .then(transactionPage => {
    delete myOptions.form
    let fs = require('fs')
    let fn = `bca-transactions`
    fs.writeFile(`${fn}.html`, transactionPage, () => {
      console.log(`${fn} was saved!`)
    })
  })
  // Final: Logout
  .then(() => {
    // last url should be the menu?..
    // lastUrl = 'https://m.klikbca.com/accountstmt.do?value(actions)=menu'
    return promised('post', 'https://m.klikbca.com//authentication.do?value(actions)=logout', myOptions)
  })
  .catch((e) => {
    console.log('Errorrrrrrrr!', e)
  })


text:
/**
 * Created by Andrey Khalzov
 * 21.12.2008 23:07:44
 */
package org.wannatrak.client;

public interface Command {

    void execute();
}


text:
'use strict';

class ServerErrorException extends Error {
    constructor(message) {
        super(message);

        this.name = this.constructor.name;
        this.code = 500;
        this.message = message;

        if (typeof Error.captureStackTrace === 'function')
            Error.captureStackTrace(this, this.constructor);
        else
            this.stack = (new Error(message)).stack;
    }
}

module.exports = ServerErrorException;


text:
'use strict';

angular.module('MLDS').controller('ApplicationSummaryModalController',
		['$scope', '$log', '$modalInstance', 'application', 'audits',
		 function($scope, $log,  $modalInstance, application, audits) {

	$scope.application = application;
	$scope.audits = audits;

	$scope.submitAttempted = false;
	$scope.submitting = false;
	$scope.alerts = [];

	$log.log('audits', audits);
}]);


text:
module Hermes
  module Model
    ##
    # Model used for storing messages that have to be sent to a user.
    #
    class Message < Sequel::Model
      plugin :timestamps, :created => :created_at

      ##
      # Validates the instance before creating or saving a record.
      #
      #
      def validate
        validates_presence([:nick, :receiver_nick, :message, :channel])
      end
    end # Quote
  end # Model
end # Hermes


text:
module Flare
  module Util
    class KeyResolver
      class Modular
        def initialize params
          @partition_size = params[:partition_size] || 1024
          @virtual = params[:virtual] || 4096
          @hint = params[:hint] || 1
          @map = Array.new(@partition_size+1).map!{Array.new(@virtual, -1)}
          @next_calculate = 0
          calculate 1
        end

        def calculate psize
          return if psize < @next_calculate
          (@next_calculate..psize).each do |i|
            if i == 0
              (0...@virtual).each do |j|
                @map[i][j] = 0
              end
            else
              counter = Array.new(psize, 0)
              (0...@virtual).each do |j|
                if i <= @hint
                  @map[i][j] = j % i
                else
                  k = @map[i-1][j]
                  counter[k] += 1
                  if (counter[k] % i) == (i - 1)
                    @map[i][j] = i - 1
                  else
                    @map[i][j] = @map[i-1][j]
                  end
                end
              end
            end
          end
          @next_calculate = psize+1
        end

        def resolve key_hash_value, partition_size
          calculate partition_size
          @map[partition_size][key_hash_value % @virtual]
        end

        def map partition_size, virtual
          calculate partition_size
          @map[partition_size][virtual]
        end
      end

      def initialize(type = :modular, options = {})
        @resolver = Modular.new options
      end

      def resolve key_hash_value, partition_size
        @resolver.resolve key_hash_value, partition_size
      end
    end
  end
end


text:
KEYWORDS_USMILITARY="\bdod\b|Department(| )of(| )Defense|(U(|\.)S(|\.)|United(| )States)(| )military"
KEYWORDS_USMC="(U(|\.)S(|\.)|United(| )States)(| )Marine(|s)(| )(|Corps)|USMC"
KEYWORDS_USARMY="(U(|\.)S(|\.)|United(| )States)(| )Army"
KEYWORDS_USAIRFORCE="(U(|\.)S(|\.)|United(| )States)(| )(|ch)Air(| )Force|USAF\b"
KEYWORDS_USNAVY="(U(|\.)S(|\.)|United(| )States)(| )Navy|\bUSN\b"
KEYWORDS_USCG="(U(|\.)S(|\.)|United(| )States)(| )Coast(| )Guard|USCG"
KEYWORDS_USMILITARY_EXCLUDE="$KEYWORDS_USMC|$KEYWORDS_USARMY|$KEYWORDS_USAIRFORCE|$KEYWORDS_USNAVY|$KEYWORDS_USCG|Lott Dod"
KEYWORDS_USMILITARY_ALL="$KEYWORDS_USMILITARY|$KEYWORDS_USMC|$KEYWORDS_USARMY|$KEYWORDS_USAIRFORCE|$KEYWORDS_USNAVY|$KEYWORDS_USCG"

if [ "$1" == "" ]; #Normal operation
then

  debug_start "US military"

  USMC=$(egrep -i "$KEYWORDS_USMC" "$NEWPAGES")
  USARMY=$(egrep -i "$KEYWORDS_USARMY" "$NEWPAGES")
  USAF=$(egrep -i "$KEYWORDS_USAIRFORCE" "$NEWPAGES")
  USNAVY=$(egrep -i "$KEYWORDS_USNAVY" "$NEWPAGES")
  USCG=$(egrep -i "$KEYWORDS_USCG" "$NEWPAGES")
  USMILITARY=$(egrep -i "$KEYWORDS_USMILITARY" "$NEWPAGES" | egrep -iv "$KEYWORDS_USMILITARY_EXCLUDE")

  categorize "USMC" "United States Marine Corps"
  categorize "USARMY" "United States Army"
  categorize "USAF" "United States Air Force"
  categorize "USNAVY" "United States Navy"
  categorize "USCG" "United States Coast Guard"
  categorize "USMILITARY" "US military"

  debug_end "US military"

fi