问:
Get cpu cycles of LLVM IR using CostModel
Since LLVM 3.0, there is CostModel.cpp under Analysis directory. Referring to its doc, it says

This file defines the cost model analysis. It provides a very basic cost estimation for LLVM-IR. This analysis uses the services of the codegen to approximate the cost of any IR instruction when lowered to machine instructions. The cost results are unit-less and the cost number represents the throughput of the machine assuming that all loads hit the cache, all branches are predicted, etc. The cost numbers can be added in order to compare two or more transformation alternatives.

I am wondering how should I compile and use this pass on IR files. A concrete example with appropriate commands would be perfect.

答:
Below is the sample which is working for me :

Main Function File to test

```<code>#include <iostream>
#include <string>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/ErrorOr.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Analysis/CostModelDummy.h>
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"

using namespace llvm;

int main(int argc, char *argv[]) {
    StringRef filename = "FILE_NAME";
    LLVMContext context;

    ErrorOr<std::unique_ptr<MemoryBuffer>> fileOrErr =
        MemoryBuffer::getFileOrSTDIN(filename);
    if (std::error_code ec = fileOrErr.getError()) {
        std::cerr << " Error opening input file: " + ec.message() << std::endl;
        return 2;
    }
    Expected<std::unique_ptr<Module>> moduleOrErr =
        parseBitcodeFile(fileOrErr.get()->getMemBufferRef(), context);
    if (std::error_code ec = fileOrErr.getError()) {
        std::cerr << "Error reading Moduule: " + ec.message() << std::endl;
        return 3;
    }

    llvm::SMDiagnostic Err;
    llvm::LLVMContext Context;
    std::unique_ptr<llvm::Module> m(parseIRFile(filename, Err, Context));
    if (!m)
      return 4;

    std::cout << "Successfully read Module:" << std::endl;
    std::cout << " Name: " << m->getName().str() << std::endl;
    std::cout << " Target triple: " << m->getTargetTriple() << std::endl;

    for (auto iter1 = m->getFunctionList().begin(); iter1 != m->getFunctionList().end(); iter1++) {
        Function &f = *iter1;

        CostModelAnalysisDummy obj;
        std::cout << " STEP: 1 Function: " << f.getName().str() << std::endl;
        obj.runOnFunction(f);

        std::cout << " STEP: 2 Function: " << f.getName().str() << std::endl;
        for (auto iter2 = f.getBasicBlockList().begin(); iter2 != f.getBasicBlockList().end(); iter2++) {
            BasicBlock &bb = *iter2;
            std::cout << "  BasicBlock: " << bb.getName().str() << std::endl;
            for (auto iter3 = bb.begin(); iter3 != bb.end(); iter3++) {
                Instruction &inst = *iter3;

                std::cout << std::endl << " Number of Cycles" << obj.getInstructionCost(&inst) << std::endl;

                std::cout << "   Instruction " << &inst << " : " << inst.getOpcodeName();

                unsigned int  i = 0;
                unsigned int opnt_cnt = inst.getNumOperands();
                for (; i < opnt_cnt; ++i)
                {
                    Value *opnd = inst.getOperand(i);
                    std::string o;
                    //          raw_string_ostream os(o);
                    //         opnd->print(os);
                    //opnd->printAsOperand(os, true, m);
                    if (opnd->hasName()) {
                        o = opnd->getName();
                        std::cout << " " << o << ",";
                    }
                    else {
                        std::cout << " ptr" << opnd << ",";
                    }
                }
                std::cout << std::endl;
            }
        }
    }
    return 0;
}
</code>```

Source File

```<code>//===- CostModel.cpp ------ Cost Model Analysis ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the cost model analysis. It provides a very basic cost
// estimation for LLVM-IR. This analysis uses the services of the codegen
// to approximate the cost of any IR instruction when lowered to machine
// instructions. The cost results are unit-less and the cost number represents
// the throughput of the machine assuming that all loads hit the cache, all
// branches are predicted, etc. The cost numbers can be added in order to
// compare two or more transformation alternatives.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/CostModelDummy.h"

using namespace llvm;

// Register this pass.
char CostModelAnalysisDummy::ID = 0;
static const char cm_name[] = "Cost Model Analysis";
INITIALIZE_PASS_BEGIN(CostModelAnalysisDummy, CM_NAME, cm_name, false, true)
INITIALIZE_PASS_END(CostModelAnalysisDummy, CM_NAME, cm_name, false, true)

static cl::opt<bool> EnableReduxCost("costmodel-reduxcost-Dummy", cl::init(false),
    cl::Hidden,
    cl::desc("Recognize reduction patterns."));

FunctionPass *createCostModelAnalysisDummyPass() {
  return new CostModelAnalysisDummy();
}

void
CostModelAnalysisDummy::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
}

bool
CostModelAnalysisDummy::runOnFunction(Function &F) {
 this->F = &F;
 PMDataManager *DM = getAsPMDataManager();
 AnalysisResolver *AR = new AnalysisResolver(*DM);
 setResolver(AR);
 setTopLevelManager(new CostModelAnalysisDummy());

 recordAvailableAnalysis(new TargetTransformInfoWrapperPass());
 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
 TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;

 return false;
}

static bool isReverseVectorMask(ArrayRef<int> Mask) {
  for (unsigned i = 0, MaskSize = Mask.size(); i < MaskSize; ++i)
    if (Mask[i] >= 0 && Mask[i] != (int)(MaskSize - 1 - i))
      return false;
  return true;
}

static bool isSingleSourceVectorMask(ArrayRef<int> Mask) {
  bool Vec0 = false;
  bool Vec1 = false;
  for (unsigned i = 0, NumVecElts = Mask.size(); i < NumVecElts; ++i) {
    if (Mask[i] >= 0) {
      if ((unsigned)Mask[i] >= NumVecElts)
        Vec1 = true;
      else
        Vec0 = true;
    }
  }
  return !(Vec0 && Vec1);
}

static bool isZeroEltBroadcastVectorMask(ArrayRef<int> Mask) {
  for (unsigned i = 0; i < Mask.size(); ++i)
    if (Mask[i] > 0)
      return false;
  return true;
}

static bool isAlternateVectorMask(ArrayRef<int> Mask) {
  bool isAlternate = true;
  unsigned MaskSize = Mask.size();

  // Example: shufflevector A, B, <0,5,2,7>
  for (unsigned i = 0; i < MaskSize && isAlternate; ++i) {
    if (Mask[i] < 0)
      continue;
    isAlternate = Mask[i] == (int)((i & 1) ? MaskSize + i : i);
  }

  if (isAlternate)
    return true;

  isAlternate = true;
  // Example: shufflevector A, B, <4,1,6,3>
  for (unsigned i = 0; i < MaskSize && isAlternate; ++i) {
    if (Mask[i] < 0)
      continue;
    isAlternate = Mask[i] == (int)((i & 1) ? i : MaskSize + i);
  }

  return isAlternate;
}

static TargetTransformInfo::OperandValueKind getOperandInfo(Value *V) {
  TargetTransformInfo::OperandValueKind OpInfo =
      TargetTransformInfo::OK_AnyValue;

  // Check for a splat of a constant or for a non uniform vector of constants.
  if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
    OpInfo = TargetTransformInfo::OK_NonUniformConstantValue;
    if (cast<Constant>(V)->getSplatValue() != nullptr)
      OpInfo = TargetTransformInfo::OK_UniformConstantValue;
  }

  // Check for a splat of a uniform value. This is not loop aware, so return
  // true only for the obviously uniform cases (argument, globalvalue)
  const Value *Splat = getSplatValue(V);
  if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat)))
    OpInfo = TargetTransformInfo::OK_UniformValue;

  return OpInfo;
}

static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft,
                                     unsigned Level) {
  // We don't need a shuffle if we just want to have element 0 in position 0 of
  // the vector.
  if (!SI && Level == 0 && IsLeft)
    return true;
  else if (!SI)
    return false;

  SmallVector<int, 32> Mask(SI->getType()->getVectorNumElements(), -1);

  // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
  // we look at the left or right side.
  for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
    Mask[i] = val;

  SmallVector<int, 16> ActualMask = SI->getShuffleMask();
  return Mask == ActualMask;
}

static bool matchPairwiseReductionAtLevel(const BinaryOperator *BinOp,
                                          unsigned Level, unsigned NumLevels) {
  // Match one level of pairwise operations.
  // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
  // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
  // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
  if (BinOp == nullptr)
    return false;

  assert(BinOp->getType()->isVectorTy() && "Expecting a vector type");

  unsigned Opcode = BinOp->getOpcode();
  Value *L = BinOp->getOperand(0);
  Value *R = BinOp->getOperand(1);

  ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(L);
  if (!LS && Level)
    return false;
  ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(R);
  if (!RS && Level)
    return false;

  // On level 0 we can omit one shufflevector instruction.
  if (!Level && !RS && !LS)
    return false;

  // Shuffle inputs must match.
  Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
  Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
  Value *NextLevelOp = nullptr;
  if (NextLevelOpR && NextLevelOpL) {
    // If we have two shuffles their operands must match.
    if (NextLevelOpL != NextLevelOpR)
      return false;

    NextLevelOp = NextLevelOpL;
  } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
    // On the first level we can omit the shufflevector <0, undef,...>. So the
    // input to the other shufflevector <1, undef> must match with one of the
    // inputs to the current binary operation.
    // Example:
    //  %NextLevelOpL = shufflevector %R, <1, undef ...>
    //  %BinOp        = fadd          %NextLevelOpL, %R
    if (NextLevelOpL && NextLevelOpL != R)
      return false;
    else if (NextLevelOpR && NextLevelOpR != L)
      return false;

    NextLevelOp = NextLevelOpL ? R : L;
  } else
    return false;

  // Check that the next levels binary operation exists and matches with the
  // current one.
  BinaryOperator *NextLevelBinOp = nullptr;
  if (Level + 1 != NumLevels) {
    if (!(NextLevelBinOp = dyn_cast<BinaryOperator>(NextLevelOp)))
      return false;
    else if (NextLevelBinOp->getOpcode() != Opcode)
      return false;
  }

  // Shuffle mask for pairwise operation must match.
  if (matchPairwiseShuffleMask(LS, true, Level)) {
    if (!matchPairwiseShuffleMask(RS, false, Level))
      return false;
  } else if (matchPairwiseShuffleMask(RS, true, Level)) {
    if (!matchPairwiseShuffleMask(LS, false, Level))
      return false;
  } else
    return false;

  if (++Level == NumLevels)
    return true;

  // Match next level.
  return matchPairwiseReductionAtLevel(NextLevelBinOp, Level, NumLevels);
}

static bool matchPairwiseReduction(const ExtractElementInst *ReduxRoot,
                                   unsigned &Opcode, Type *&Ty) {
  if (!EnableReduxCost)
    return false;

  // Need to extract the first element.
  ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
  unsigned Idx = ~0u;
  if (CI)
    Idx = CI->getZExtValue();
  if (Idx != 0)
    return false;

  BinaryOperator *RdxStart = dyn_cast<BinaryOperator>(ReduxRoot->getOperand(0));
  if (!RdxStart)
    return false;

  Type *VecTy = ReduxRoot->getOperand(0)->getType();
  unsigned NumVecElems = VecTy->getVectorNumElements();
  if (!isPowerOf2_32(NumVecElems))
    return false;

  // We look for a sequence of shuffle,shuffle,add triples like the following
  // that builds a pairwise reduction tree.
  //
  //  (X0, X1, X2, X3)
  //   (X0 + X1, X2 + X3, undef, undef)
  //    ((X0 + X1) + (X2 + X3), undef, undef, undef)
  //
  // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
  // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
  // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
  // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
  //       <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
  // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
  //       <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
  // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
  // %r = extractelement <4 x float> %bin.rdx8, i32 0
  if (!matchPairwiseReductionAtLevel(RdxStart, 0,  Log2_32(NumVecElems)))
    return false;

  Opcode = RdxStart->getOpcode();
  Ty = VecTy;

  return true;
}

static std::pair<Value *, ShuffleVectorInst *>
getShuffleAndOtherOprd(BinaryOperator *B) {

  Value *L = B->getOperand(0);
  Value *R = B->getOperand(1);
  ShuffleVectorInst *S = nullptr;

  if ((S = dyn_cast<ShuffleVectorInst>(L)))
    return std::make_pair(R, S);

  S = dyn_cast<ShuffleVectorInst>(R);
  return std::make_pair(L, S);
}

static bool matchVectorSplittingReduction(const ExtractElementInst *ReduxRoot,
                                          unsigned &Opcode, Type *&Ty) {
  if (!EnableReduxCost)
    return false;

  // Need to extract the first element.
  ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
  unsigned Idx = ~0u;
  if (CI)
    Idx = CI->getZExtValue();
  if (Idx != 0)
    return false;

  BinaryOperator *RdxStart = dyn_cast<BinaryOperator>(ReduxRoot->getOperand(0));
  if (!RdxStart)
    return false;
  unsigned RdxOpcode = RdxStart->getOpcode();

  Type *VecTy = ReduxRoot->getOperand(0)->getType();
  unsigned NumVecElems = VecTy->getVectorNumElements();
  if (!isPowerOf2_32(NumVecElems))
    return false;

  // We look for a sequence of shuffles and adds like the following matching one
  // fadd, shuffle vector pair at a time.
  //
  // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
  //                           <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
  // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
  // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
  //                          <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
  // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
  // %r = extractelement <4 x float> %bin.rdx8, i32 0

  unsigned MaskStart = 1;
  Value *RdxOp = RdxStart;
  SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
  unsigned NumVecElemsRemain = NumVecElems;
  while (NumVecElemsRemain - 1) {
    // Check for the right reduction operation.
    BinaryOperator *BinOp;
    if (!(BinOp = dyn_cast<BinaryOperator>(RdxOp)))
      return false;
    if (BinOp->getOpcode() != RdxOpcode)
      return false;

    Value *NextRdxOp;
    ShuffleVectorInst *Shuffle;
    std::tie(NextRdxOp, Shuffle) = getShuffleAndOtherOprd(BinOp);

    // Check the current reduction operation and the shuffle use the same value.
    if (Shuffle == nullptr)
      return false;
    if (Shuffle->getOperand(0) != NextRdxOp)
      return false;

    // Check that shuffle masks matches.
    for (unsigned j = 0; j != MaskStart; ++j)
      ShuffleMask[j] = MaskStart + j;
    // Fill the rest of the mask with -1 for undef.
    std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);

    SmallVector<int, 16> Mask = Shuffle->getShuffleMask();
    if (ShuffleMask != Mask)
      return false;

    RdxOp = NextRdxOp;
    NumVecElemsRemain /= 2;
    MaskStart *= 2;
  }

  Opcode = RdxOpcode;
  Ty = VecTy;
  return true;
}

unsigned CostModelAnalysisDummy::getInstructionCost(const Instruction *I) const {

  if (!TTI)
    return -1;

  switch (I->getOpcode()) {
  case Instruction::GetElementPtr:
    return TTI->getUserCost(I);

  case Instruction::Ret:
  case Instruction::PHI:
  case Instruction::Br: {
    return TTI->getCFInstrCost(I->getOpcode());
  }
  case Instruction::Add:
  case Instruction::FAdd:
  case Instruction::Sub:
  case Instruction::FSub:
  case Instruction::Mul:
  case Instruction::FMul:
  case Instruction::UDiv:
  case Instruction::SDiv:
  case Instruction::FDiv:
  case Instruction::URem:
  case Instruction::SRem:
  case Instruction::FRem:
  case Instruction::Shl:
  case Instruction::LShr:
  case Instruction::AShr:
  case Instruction::And:
  case Instruction::Or:
  case Instruction::Xor: {
    TargetTransformInfo::OperandValueKind Op1VK =
      getOperandInfo(I->getOperand(0));
    TargetTransformInfo::OperandValueKind Op2VK =
      getOperandInfo(I->getOperand(1));
    SmallVector<const Value*, 2> Operands(I->operand_values());
    return TTI->getArithmeticInstrCost(I->getOpcode(), I->getType(), Op1VK,
                                       Op2VK, TargetTransformInfo::OP_None,
                                       TargetTransformInfo::OP_None,
                                       Operands);
  }
  case Instruction::Select: {
    const SelectInst *SI = cast<SelectInst>(I);
    Type *CondTy = SI->getCondition()->getType();
    return TTI->getCmpSelInstrCost(I->getOpcode(), I->getType(), CondTy);
  }
  case Instruction::ICmp:
  case Instruction::FCmp: {
    Type *ValTy = I->getOperand(0)->getType();
    return TTI->getCmpSelInstrCost(I->getOpcode(), ValTy);
  }
  case Instruction::Store: {
    const StoreInst *SI = cast<StoreInst>(I);
    Type *ValTy = SI->getValueOperand()->getType();
    return TTI->getMemoryOpCost(I->getOpcode(), ValTy,
                                 SI->getAlignment(),
                                 SI->getPointerAddressSpace());
  }
  case Instruction::Load: {
    const LoadInst *LI = cast<LoadInst>(I);
    return TTI->getMemoryOpCost(I->getOpcode(), I->getType(),
                                 LI->getAlignment(),
                                 LI->getPointerAddressSpace());
  }
  case Instruction::ZExt:
  case Instruction::SExt:
  case Instruction::FPToUI:
  case Instruction::FPToSI:
  case Instruction::FPExt:
  case Instruction::PtrToInt:
  case Instruction::IntToPtr:
  case Instruction::SIToFP:
  case Instruction::UIToFP:
  case Instruction::Trunc:
  case Instruction::FPTrunc:
  case Instruction::BitCast:
  case Instruction::AddrSpaceCast: {
    Type *SrcTy = I->getOperand(0)->getType();
    return TTI->getCastInstrCost(I->getOpcode(), I->getType(), SrcTy);
  }
  case Instruction::ExtractElement: {
    const ExtractElementInst * EEI = cast<ExtractElementInst>(I);
    ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
    unsigned Idx = -1;
    if (CI)
      Idx = CI->getZExtValue();

    // Try to match a reduction sequence (series of shufflevector and vector
    // adds followed by a extractelement).
    unsigned ReduxOpCode;
    Type *ReduxType;

    if (matchVectorSplittingReduction(EEI, ReduxOpCode, ReduxType))
      return TTI->getArithmeticReductionCost(ReduxOpCode, ReduxType, false);
    else if (matchPairwiseReduction(EEI, ReduxOpCode, ReduxType))
      return TTI->getArithmeticReductionCost(ReduxOpCode, ReduxType, true);

    return TTI->getVectorInstrCost(I->getOpcode(),
                                   EEI->getOperand(0)->getType(), Idx);
  }
  case Instruction::InsertElement: {
    const InsertElementInst * IE = cast<InsertElementInst>(I);
    ConstantInt *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
    unsigned Idx = -1;
    if (CI)
      Idx = CI->getZExtValue();
    return TTI->getVectorInstrCost(I->getOpcode(),
                                   IE->getType(), Idx);
  }
  case Instruction::ShuffleVector: {
    const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
    Type *VecTypOp0 = Shuffle->getOperand(0)->getType();
    unsigned NumVecElems = VecTypOp0->getVectorNumElements();
    SmallVector<int, 16> Mask = Shuffle->getShuffleMask();

    if (NumVecElems == Mask.size()) {
      if (isReverseVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_Reverse, VecTypOp0,
                                   0, nullptr);
      if (isAlternateVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_SELECT,
                                   VecTypOp0, 0, nullptr);

      if (isZeroEltBroadcastVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast,
                                   VecTypOp0, 0, nullptr);

      if (isSingleSourceVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
                                   VecTypOp0, 0, nullptr);

      return TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
                                 VecTypOp0, 0, nullptr);
    }

    return -1;
  }
  case Instruction::Call:
    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
      SmallVector<Value *, 4> Args;
      for (unsigned J = 0, JE = II->getNumArgOperands(); J != JE; ++J)
        Args.push_back(II->getArgOperand(J));

      FastMathFlags FMF;
      if (auto *FPMO = dyn_cast<FPMathOperator>(II))
        FMF = FPMO->getFastMathFlags();

      return TTI->getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(),
                                        Args, FMF);
    }
    return -1;
  default:
    // We don't have any information on this instruction.
    return -1;
  }
}

void CostModelAnalysisDummy::print(raw_ostream &OS, const Module*) const {
  if (!F)
    return;

  for (BasicBlock &B : *F) {
    for (Instruction &Inst : B) {
      unsigned Cost = getInstructionCost(&Inst);
      if (Cost != (unsigned)-1)
        OS << "Cost Model: Found an estimated cost of " << Cost;
      else
        OS << "Cost Model: Unknown cost";

      OS << " for instruction: " << Inst << "\n";
    }
  }
}
</code>```

Header File

```<code>#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
#include "llvm/IR/LegacyPassManagers.h"

using namespace llvm;

#define CM_NAME "cost-model-sanji"
#define DEBUG_TYPE CM_NAME

    class CostModelAnalysisDummy : public PMDataManager, public FunctionPass, public PMTopLevelManager {

    public:
        static char ID; // Class identification, replacement for typeinfo
        CostModelAnalysisDummy() : FunctionPass(ID), PMDataManager(), PMTopLevelManager(new FPPassManager()), F(nullptr), TTI(nullptr) {
            llvm::initializeCostModelAnalysisDummyPass(
                *PassRegistry::getPassRegistry());
        }

        /// Returns the expected cost of the instruction.
        /// Returns -1 if the cost is unknown.
        /// Note, this method does not cache the cost calculation and it
        /// can be expensive in some cases.
        unsigned getInstructionCost(const Instruction *I) const;
        bool runOnFunction(Function &F) override;

        PMDataManager *getAsPMDataManager() override { return this; }
        Pass *getAsPass() override { return this; }

        PassManagerType getTopLevelPassManagerType() override {
            return PMT_BasicBlockPassManager;
        }

        FPPassManager *getContainedManager(unsigned N) {
            assert(N < PassManagers.size() && "Pass number out of range!");
            FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
            return FP;
        }
    private:
        void getAnalysisUsage(AnalysisUsage &AU) const override;

        void print(raw_ostream &OS, const Module*) const override;

        /// The function that we analyze.
        Function *F;
        /// Target information.
        const TargetTransformInfo *TTI;
    };

    FunctionPass *createCostModelAnalysisDummyPass();
</code>```

Body:
Below is the sample which is working for me :

Main Function File to test

#include <iostream>
#include <string>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/ErrorOr.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Analysis/CostModelDummy.h>
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"

using namespace llvm;

int main(int argc, char *argv[]) {
    StringRef filename = "FILE_NAME";
    LLVMContext context;

    ErrorOr<std::unique_ptr<MemoryBuffer>> fileOrErr =
        MemoryBuffer::getFileOrSTDIN(filename);
    if (std::error_code ec = fileOrErr.getError()) {
        std::cerr << " Error opening input file: " + ec.message() << std::endl;
        return 2;
    }
    Expected<std::unique_ptr<Module>> moduleOrErr =
        parseBitcodeFile(fileOrErr.get()->getMemBufferRef(), context);
    if (std::error_code ec = fileOrErr.getError()) {
        std::cerr << "Error reading Moduule: " + ec.message() << std::endl;
        return 3;
    }

    llvm::SMDiagnostic Err;
    llvm::LLVMContext Context;
    std::unique_ptr<llvm::Module> m(parseIRFile(filename, Err, Context));
    if (!m)
      return 4;

    std::cout << "Successfully read Module:" << std::endl;
    std::cout << " Name: " << m->getName().str() << std::endl;
    std::cout << " Target triple: " << m->getTargetTriple() << std::endl;

    for (auto iter1 = m->getFunctionList().begin(); iter1 != m->getFunctionList().end(); iter1++) {
        Function &f = *iter1;

        CostModelAnalysisDummy obj;
        std::cout << " STEP: 1 Function: " << f.getName().str() << std::endl;
        obj.runOnFunction(f);

        std::cout << " STEP: 2 Function: " << f.getName().str() << std::endl;
        for (auto iter2 = f.getBasicBlockList().begin(); iter2 != f.getBasicBlockList().end(); iter2++) {
            BasicBlock &bb = *iter2;
            std::cout << "  BasicBlock: " << bb.getName().str() << std::endl;
            for (auto iter3 = bb.begin(); iter3 != bb.end(); iter3++) {
                Instruction &inst = *iter3;

                std::cout << std::endl << " Number of Cycles" << obj.getInstructionCost(&inst) << std::endl;

                std::cout << "   Instruction " << &inst << " : " << inst.getOpcodeName();

                unsigned int  i = 0;
                unsigned int opnt_cnt = inst.getNumOperands();
                for (; i < opnt_cnt; ++i)
                {
                    Value *opnd = inst.getOperand(i);
                    std::string o;
                    //          raw_string_ostream os(o);
                    //         opnd->print(os);
                    //opnd->printAsOperand(os, true, m);
                    if (opnd->hasName()) {
                        o = opnd->getName();
                        std::cout << " " << o << ",";
                    }
                    else {
                        std::cout << " ptr" << opnd << ",";
                    }
                }
                std::cout << std::endl;
            }
        }
    }
    return 0;
}

Source File

//===- CostModel.cpp ------ Cost Model Analysis ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the cost model analysis. It provides a very basic cost
// estimation for LLVM-IR. This analysis uses the services of the codegen
// to approximate the cost of any IR instruction when lowered to machine
// instructions. The cost results are unit-less and the cost number represents
// the throughput of the machine assuming that all loads hit the cache, all
// branches are predicted, etc. The cost numbers can be added in order to
// compare two or more transformation alternatives.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/CostModelDummy.h"

using namespace llvm;

// Register this pass.
char CostModelAnalysisDummy::ID = 0;
static const char cm_name[] = "Cost Model Analysis";
INITIALIZE_PASS_BEGIN(CostModelAnalysisDummy, CM_NAME, cm_name, false, true)
INITIALIZE_PASS_END(CostModelAnalysisDummy, CM_NAME, cm_name, false, true)

static cl::opt<bool> EnableReduxCost("costmodel-reduxcost-Dummy", cl::init(false),
    cl::Hidden,
    cl::desc("Recognize reduction patterns."));

FunctionPass *createCostModelAnalysisDummyPass() {
  return new CostModelAnalysisDummy();
}

void
CostModelAnalysisDummy::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
}

bool
CostModelAnalysisDummy::runOnFunction(Function &F) {
 this->F = &F;
 PMDataManager *DM = getAsPMDataManager();
 AnalysisResolver *AR = new AnalysisResolver(*DM);
 setResolver(AR);
 setTopLevelManager(new CostModelAnalysisDummy());

 recordAvailableAnalysis(new TargetTransformInfoWrapperPass());
 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
 TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;

 return false;
}

static bool isReverseVectorMask(ArrayRef<int> Mask) {
  for (unsigned i = 0, MaskSize = Mask.size(); i < MaskSize; ++i)
    if (Mask[i] >= 0 && Mask[i] != (int)(MaskSize - 1 - i))
      return false;
  return true;
}

static bool isSingleSourceVectorMask(ArrayRef<int> Mask) {
  bool Vec0 = false;
  bool Vec1 = false;
  for (unsigned i = 0, NumVecElts = Mask.size(); i < NumVecElts; ++i) {
    if (Mask[i] >= 0) {
      if ((unsigned)Mask[i] >= NumVecElts)
        Vec1 = true;
      else
        Vec0 = true;
    }
  }
  return !(Vec0 && Vec1);
}

static bool isZeroEltBroadcastVectorMask(ArrayRef<int> Mask) {
  for (unsigned i = 0; i < Mask.size(); ++i)
    if (Mask[i] > 0)
      return false;
  return true;
}

static bool isAlternateVectorMask(ArrayRef<int> Mask) {
  bool isAlternate = true;
  unsigned MaskSize = Mask.size();

  // Example: shufflevector A, B, <0,5,2,7>
  for (unsigned i = 0; i < MaskSize && isAlternate; ++i) {
    if (Mask[i] < 0)
      continue;
    isAlternate = Mask[i] == (int)((i & 1) ? MaskSize + i : i);
  }

  if (isAlternate)
    return true;

  isAlternate = true;
  // Example: shufflevector A, B, <4,1,6,3>
  for (unsigned i = 0; i < MaskSize && isAlternate; ++i) {
    if (Mask[i] < 0)
      continue;
    isAlternate = Mask[i] == (int)((i & 1) ? i : MaskSize + i);
  }

  return isAlternate;
}

static TargetTransformInfo::OperandValueKind getOperandInfo(Value *V) {
  TargetTransformInfo::OperandValueKind OpInfo =
      TargetTransformInfo::OK_AnyValue;

  // Check for a splat of a constant or for a non uniform vector of constants.
  if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
    OpInfo = TargetTransformInfo::OK_NonUniformConstantValue;
    if (cast<Constant>(V)->getSplatValue() != nullptr)
      OpInfo = TargetTransformInfo::OK_UniformConstantValue;
  }

  // Check for a splat of a uniform value. This is not loop aware, so return
  // true only for the obviously uniform cases (argument, globalvalue)
  const Value *Splat = getSplatValue(V);
  if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat)))
    OpInfo = TargetTransformInfo::OK_UniformValue;

  return OpInfo;
}

static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft,
                                     unsigned Level) {
  // We don't need a shuffle if we just want to have element 0 in position 0 of
  // the vector.
  if (!SI && Level == 0 && IsLeft)
    return true;
  else if (!SI)
    return false;

  SmallVector<int, 32> Mask(SI->getType()->getVectorNumElements(), -1);

  // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
  // we look at the left or right side.
  for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
    Mask[i] = val;

  SmallVector<int, 16> ActualMask = SI->getShuffleMask();
  return Mask == ActualMask;
}

static bool matchPairwiseReductionAtLevel(const BinaryOperator *BinOp,
                                          unsigned Level, unsigned NumLevels) {
  // Match one level of pairwise operations.
  // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
  // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
  // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
  if (BinOp == nullptr)
    return false;

  assert(BinOp->getType()->isVectorTy() && "Expecting a vector type");

  unsigned Opcode = BinOp->getOpcode();
  Value *L = BinOp->getOperand(0);
  Value *R = BinOp->getOperand(1);

  ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(L);
  if (!LS && Level)
    return false;
  ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(R);
  if (!RS && Level)
    return false;

  // On level 0 we can omit one shufflevector instruction.
  if (!Level && !RS && !LS)
    return false;

  // Shuffle inputs must match.
  Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
  Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
  Value *NextLevelOp = nullptr;
  if (NextLevelOpR && NextLevelOpL) {
    // If we have two shuffles their operands must match.
    if (NextLevelOpL != NextLevelOpR)
      return false;

    NextLevelOp = NextLevelOpL;
  } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
    // On the first level we can omit the shufflevector <0, undef,...>. So the
    // input to the other shufflevector <1, undef> must match with one of the
    // inputs to the current binary operation.
    // Example:
    //  %NextLevelOpL = shufflevector %R, <1, undef ...>
    //  %BinOp        = fadd          %NextLevelOpL, %R
    if (NextLevelOpL && NextLevelOpL != R)
      return false;
    else if (NextLevelOpR && NextLevelOpR != L)
      return false;

    NextLevelOp = NextLevelOpL ? R : L;
  } else
    return false;

  // Check that the next levels binary operation exists and matches with the
  // current one.
  BinaryOperator *NextLevelBinOp = nullptr;
  if (Level + 1 != NumLevels) {
    if (!(NextLevelBinOp = dyn_cast<BinaryOperator>(NextLevelOp)))
      return false;
    else if (NextLevelBinOp->getOpcode() != Opcode)
      return false;
  }

  // Shuffle mask for pairwise operation must match.
  if (matchPairwiseShuffleMask(LS, true, Level)) {
    if (!matchPairwiseShuffleMask(RS, false, Level))
      return false;
  } else if (matchPairwiseShuffleMask(RS, true, Level)) {
    if (!matchPairwiseShuffleMask(LS, false, Level))
      return false;
  } else
    return false;

  if (++Level == NumLevels)
    return true;

  // Match next level.
  return matchPairwiseReductionAtLevel(NextLevelBinOp, Level, NumLevels);
}

static bool matchPairwiseReduction(const ExtractElementInst *ReduxRoot,
                                   unsigned &Opcode, Type *&Ty) {
  if (!EnableReduxCost)
    return false;

  // Need to extract the first element.
  ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
  unsigned Idx = ~0u;
  if (CI)
    Idx = CI->getZExtValue();
  if (Idx != 0)
    return false;

  BinaryOperator *RdxStart = dyn_cast<BinaryOperator>(ReduxRoot->getOperand(0));
  if (!RdxStart)
    return false;

  Type *VecTy = ReduxRoot->getOperand(0)->getType();
  unsigned NumVecElems = VecTy->getVectorNumElements();
  if (!isPowerOf2_32(NumVecElems))
    return false;

  // We look for a sequence of shuffle,shuffle,add triples like the following
  // that builds a pairwise reduction tree.
  //
  //  (X0, X1, X2, X3)
  //   (X0 + X1, X2 + X3, undef, undef)
  //    ((X0 + X1) + (X2 + X3), undef, undef, undef)
  //
  // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
  // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
  //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
  // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
  // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
  //       <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
  // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
  //       <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
  // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
  // %r = extractelement <4 x float> %bin.rdx8, i32 0
  if (!matchPairwiseReductionAtLevel(RdxStart, 0,  Log2_32(NumVecElems)))
    return false;

  Opcode = RdxStart->getOpcode();
  Ty = VecTy;

  return true;
}

static std::pair<Value *, ShuffleVectorInst *>
getShuffleAndOtherOprd(BinaryOperator *B) {

  Value *L = B->getOperand(0);
  Value *R = B->getOperand(1);
  ShuffleVectorInst *S = nullptr;

  if ((S = dyn_cast<ShuffleVectorInst>(L)))
    return std::make_pair(R, S);

  S = dyn_cast<ShuffleVectorInst>(R);
  return std::make_pair(L, S);
}

static bool matchVectorSplittingReduction(const ExtractElementInst *ReduxRoot,
                                          unsigned &Opcode, Type *&Ty) {
  if (!EnableReduxCost)
    return false;

  // Need to extract the first element.
  ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
  unsigned Idx = ~0u;
  if (CI)
    Idx = CI->getZExtValue();
  if (Idx != 0)
    return false;

  BinaryOperator *RdxStart = dyn_cast<BinaryOperator>(ReduxRoot->getOperand(0));
  if (!RdxStart)
    return false;
  unsigned RdxOpcode = RdxStart->getOpcode();

  Type *VecTy = ReduxRoot->getOperand(0)->getType();
  unsigned NumVecElems = VecTy->getVectorNumElements();
  if (!isPowerOf2_32(NumVecElems))
    return false;

  // We look for a sequence of shuffles and adds like the following matching one
  // fadd, shuffle vector pair at a time.
  //
  // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
  //                           <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
  // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
  // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
  //                          <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
  // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
  // %r = extractelement <4 x float> %bin.rdx8, i32 0

  unsigned MaskStart = 1;
  Value *RdxOp = RdxStart;
  SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
  unsigned NumVecElemsRemain = NumVecElems;
  while (NumVecElemsRemain - 1) {
    // Check for the right reduction operation.
    BinaryOperator *BinOp;
    if (!(BinOp = dyn_cast<BinaryOperator>(RdxOp)))
      return false;
    if (BinOp->getOpcode() != RdxOpcode)
      return false;

    Value *NextRdxOp;
    ShuffleVectorInst *Shuffle;
    std::tie(NextRdxOp, Shuffle) = getShuffleAndOtherOprd(BinOp);

    // Check the current reduction operation and the shuffle use the same value.
    if (Shuffle == nullptr)
      return false;
    if (Shuffle->getOperand(0) != NextRdxOp)
      return false;

    // Check that shuffle masks matches.
    for (unsigned j = 0; j != MaskStart; ++j)
      ShuffleMask[j] = MaskStart + j;
    // Fill the rest of the mask with -1 for undef.
    std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);

    SmallVector<int, 16> Mask = Shuffle->getShuffleMask();
    if (ShuffleMask != Mask)
      return false;

    RdxOp = NextRdxOp;
    NumVecElemsRemain /= 2;
    MaskStart *= 2;
  }

  Opcode = RdxOpcode;
  Ty = VecTy;
  return true;
}

unsigned CostModelAnalysisDummy::getInstructionCost(const Instruction *I) const {

  if (!TTI)
    return -1;

  switch (I->getOpcode()) {
  case Instruction::GetElementPtr:
    return TTI->getUserCost(I);

  case Instruction::Ret:
  case Instruction::PHI:
  case Instruction::Br: {
    return TTI->getCFInstrCost(I->getOpcode());
  }
  case Instruction::Add:
  case Instruction::FAdd:
  case Instruction::Sub:
  case Instruction::FSub:
  case Instruction::Mul:
  case Instruction::FMul:
  case Instruction::UDiv:
  case Instruction::SDiv:
  case Instruction::FDiv:
  case Instruction::URem:
  case Instruction::SRem:
  case Instruction::FRem:
  case Instruction::Shl:
  case Instruction::LShr:
  case Instruction::AShr:
  case Instruction::And:
  case Instruction::Or:
  case Instruction::Xor: {
    TargetTransformInfo::OperandValueKind Op1VK =
      getOperandInfo(I->getOperand(0));
    TargetTransformInfo::OperandValueKind Op2VK =
      getOperandInfo(I->getOperand(1));
    SmallVector<const Value*, 2> Operands(I->operand_values());
    return TTI->getArithmeticInstrCost(I->getOpcode(), I->getType(), Op1VK,
                                       Op2VK, TargetTransformInfo::OP_None,
                                       TargetTransformInfo::OP_None,
                                       Operands);
  }
  case Instruction::Select: {
    const SelectInst *SI = cast<SelectInst>(I);
    Type *CondTy = SI->getCondition()->getType();
    return TTI->getCmpSelInstrCost(I->getOpcode(), I->getType(), CondTy);
  }
  case Instruction::ICmp:
  case Instruction::FCmp: {
    Type *ValTy = I->getOperand(0)->getType();
    return TTI->getCmpSelInstrCost(I->getOpcode(), ValTy);
  }
  case Instruction::Store: {
    const StoreInst *SI = cast<StoreInst>(I);
    Type *ValTy = SI->getValueOperand()->getType();
    return TTI->getMemoryOpCost(I->getOpcode(), ValTy,
                                 SI->getAlignment(),
                                 SI->getPointerAddressSpace());
  }
  case Instruction::Load: {
    const LoadInst *LI = cast<LoadInst>(I);
    return TTI->getMemoryOpCost(I->getOpcode(), I->getType(),
                                 LI->getAlignment(),
                                 LI->getPointerAddressSpace());
  }
  case Instruction::ZExt:
  case Instruction::SExt:
  case Instruction::FPToUI:
  case Instruction::FPToSI:
  case Instruction::FPExt:
  case Instruction::PtrToInt:
  case Instruction::IntToPtr:
  case Instruction::SIToFP:
  case Instruction::UIToFP:
  case Instruction::Trunc:
  case Instruction::FPTrunc:
  case Instruction::BitCast:
  case Instruction::AddrSpaceCast: {
    Type *SrcTy = I->getOperand(0)->getType();
    return TTI->getCastInstrCost(I->getOpcode(), I->getType(), SrcTy);
  }
  case Instruction::ExtractElement: {
    const ExtractElementInst * EEI = cast<ExtractElementInst>(I);
    ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
    unsigned Idx = -1;
    if (CI)
      Idx = CI->getZExtValue();

    // Try to match a reduction sequence (series of shufflevector and vector
    // adds followed by a extractelement).
    unsigned ReduxOpCode;
    Type *ReduxType;

    if (matchVectorSplittingReduction(EEI, ReduxOpCode, ReduxType))
      return TTI->getArithmeticReductionCost(ReduxOpCode, ReduxType, false);
    else if (matchPairwiseReduction(EEI, ReduxOpCode, ReduxType))
      return TTI->getArithmeticReductionCost(ReduxOpCode, ReduxType, true);

    return TTI->getVectorInstrCost(I->getOpcode(),
                                   EEI->getOperand(0)->getType(), Idx);
  }
  case Instruction::InsertElement: {
    const InsertElementInst * IE = cast<InsertElementInst>(I);
    ConstantInt *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
    unsigned Idx = -1;
    if (CI)
      Idx = CI->getZExtValue();
    return TTI->getVectorInstrCost(I->getOpcode(),
                                   IE->getType(), Idx);
  }
  case Instruction::ShuffleVector: {
    const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
    Type *VecTypOp0 = Shuffle->getOperand(0)->getType();
    unsigned NumVecElems = VecTypOp0->getVectorNumElements();
    SmallVector<int, 16> Mask = Shuffle->getShuffleMask();

    if (NumVecElems == Mask.size()) {
      if (isReverseVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_Reverse, VecTypOp0,
                                   0, nullptr);
      if (isAlternateVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_SELECT,
                                   VecTypOp0, 0, nullptr);

      if (isZeroEltBroadcastVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast,
                                   VecTypOp0, 0, nullptr);

      if (isSingleSourceVectorMask(Mask))
        return TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
                                   VecTypOp0, 0, nullptr);

      return TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
                                 VecTypOp0, 0, nullptr);
    }

    return -1;
  }
  case Instruction::Call:
    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
      SmallVector<Value *, 4> Args;
      for (unsigned J = 0, JE = II->getNumArgOperands(); J != JE; ++J)
        Args.push_back(II->getArgOperand(J));

      FastMathFlags FMF;
      if (auto *FPMO = dyn_cast<FPMathOperator>(II))
        FMF = FPMO->getFastMathFlags();

      return TTI->getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(),
                                        Args, FMF);
    }
    return -1;
  default:
    // We don't have any information on this instruction.
    return -1;
  }
}

void CostModelAnalysisDummy::print(raw_ostream &OS, const Module*) const {
  if (!F)
    return;

  for (BasicBlock &B : *F) {
    for (Instruction &Inst : B) {
      unsigned Cost = getInstructionCost(&Inst);
      if (Cost != (unsigned)-1)
        OS << "Cost Model: Found an estimated cost of " << Cost;
      else
        OS << "Cost Model: Unknown cost";

      OS << " for instruction: " << Inst << "\n";
    }
  }
}

Header File

#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
#include "llvm/IR/LegacyPassManagers.h"

using namespace llvm;

#define CM_NAME "cost-model-sanji"
#define DEBUG_TYPE CM_NAME

    class CostModelAnalysisDummy : public PMDataManager, public FunctionPass, public PMTopLevelManager {

    public:
        static char ID; // Class identification, replacement for typeinfo
        CostModelAnalysisDummy() : FunctionPass(ID), PMDataManager(), PMTopLevelManager(new FPPassManager()), F(nullptr), TTI(nullptr) {
            llvm::initializeCostModelAnalysisDummyPass(
                *PassRegistry::getPassRegistry());
        }

        /// Returns the expected cost of the instruction.
        /// Returns -1 if the cost is unknown.
        /// Note, this method does not cache the cost calculation and it
        /// can be expensive in some cases.
        unsigned getInstructionCost(const Instruction *I) const;
        bool runOnFunction(Function &F) override;

        PMDataManager *getAsPMDataManager() override { return this; }
        Pass *getAsPass() override { return this; }

        PassManagerType getTopLevelPassManagerType() override {
            return PMT_BasicBlockPassManager;
        }

        FPPassManager *getContainedManager(unsigned N) {
            assert(N < PassManagers.size() && "Pass number out of range!");
            FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
            return FP;
        }
    private:
        void getAnalysisUsage(AnalysisUsage &AU) const override;

        void print(raw_ostream &OS, const Module*) const override;

        /// The function that we analyze.
        Function *F;
        /// Target information.
        const TargetTransformInfo *TTI;
    };

    FunctionPass *createCostModelAnalysisDummyPass();


来源: stackexchange

问:
Load MovieClip inline in TextField
I want to load a MovieClip inside a TextField inline with the text.

The TextField documentation says "HTML text that you assign to a text field can contain embedded media (movie clips, SWF files, GIF files, PNG files, and JPEG files)."

How can this be done with MovieClips? There must be a listener we can override.

source: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html

答:
You can use the  tag to link to an swf.

Or, if you need to have more control, place an to load a placeholder, and use getImageReference to access and/or modify the image's Loader object.  This will also allow you to set the loader content to visible = false, and add a MovieClip to it using addChild.

ContentLicense: CC BY-SA 2.5

Title: Load MovieClip inline in TextField

Body:
You can use the <img> tag to link to an swf.

Or, if you need to have more control, place an <img>to load a placeholder, and use getImageReference to access and/or modify the image's Loader object.  This will also allow you to set the loader content to visible = false, and add a MovieClip to it using addChild.


问:
Heroku postgres relation "information_schema.session_state" does not exist
I am trying to move Ktor backend to Heroku postgres db. Here whole application code:

https://github.com/MarcinMoskala/KotlinAcademyApp/tree/master/backend

To move to Heroku postgres, I based on this example project:

https://github.com/orangy/ktor-heroku-start

I changed my database configuration to following:

```<code>private val config = application.environment.config.config("database")

private val poolSize = config.property("poolSize").getString().toInt()

private val hikariConfig = HikariConfig().apply {
    val url = System.getenv("JDBC_DATABASE_URL") ?: config.property("connection").getString()
    application.log.info("DB url is $url")
    jdbcUrl = url
    maximumPoolSize = poolSize
    validate()
}

private val dataSource = HikariDataSource(hikariConfig)

private val connection: DatabaseConnection = H2Connection { dataSource.connection }

private val dispatcher = newFixedThreadPoolContext(poolSize, "database-pool")

init {
    connection.transaction {
        databaseSchema().create(listOf(NewsTable, FeedbackTable, TokensTable))
    }
}
</code>```

And I added postgressql dependency:

```<code>compile "org.postgresql:postgresql:9.4-1201-jdbc4"
</code>```

Locally it is still creating SQLite database, but when I push it to Heroku then I have following result:

```<code>DEBUG com.zaxxer.hikari.HikariConfig - jdbc4ConnectionTest.............false
DEBUG com.zaxxer.hikari.HikariConfig - jdbcUrl.........................jdbc:postgresql://ec7-77-77-777-77.compute-1.amazonaws.com:7777/7777777?user=aaaaaaaaaaaa&password=<masked>&sslmode=require
DEBUG com.zaxxer.hikari.HikariConfig - leakDetectionThreshold..........0
DEBUG com.zaxxer.hikari.HikariConfig - maximumPoolSize.................20
DEBUG com.zaxxer.hikari.HikariConfig - maxLifetime.....................1800000
DEBUG com.zaxxer.hikari.HikariConfig - metricRegistry..................none
DEBUG com.zaxxer.hikari.HikariConfig - metricsTrackerFactory...........none
DEBUG com.zaxxer.hikari.HikariConfig - minimumIdle.....................20
DEBUG com.zaxxer.hikari.HikariConfig - password........................<masked>
 [main] DEBUG com.zaxxer.hikari.HikariConfig - poolName........................"HikariPool-1"
DEBUG com.zaxxer.hikari.HikariConfig - registerMbeans..................false
DEBUG com.zaxxer.hikari.HikariConfig - readOnly........................false
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutor...............none
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutorService........internal
DEBUG com.zaxxer.hikari.HikariConfig - schema..........................none
DEBUG com.zaxxer.hikari.HikariConfig - threadFactory...................internal
DEBUG com.zaxxer.hikari.HikariConfig - transactionIsolation............default
DEBUG com.zaxxer.hikari.HikariConfig - username........................none
DEBUG com.zaxxer.hikari.HikariConfig - validationTimeout...............5000
DEBUG com.zaxxer.hikari.HikariConfig - allowPoolSuspension.............false
DEBUG com.zaxxer.hikari.HikariConfig - autoCommit......................true
DEBUG com.zaxxer.hikari.HikariConfig - HikariPool-1 - configuration:
DEBUG com.zaxxer.hikari.HikariConfig - connectionInitSql...............none
DEBUG com.zaxxer.hikari.HikariConfig - catalog.........................none
DEBUG com.zaxxer.hikari.HikariConfig - connectionTestQuery.............none
DEBUG com.zaxxer.hikari.HikariConfig - connectionTimeout...............30000
DEBUG com.zaxxer.hikari.HikariConfig - dataSource......................none
DEBUG com.zaxxer.hikari.HikariConfig - dataSourceClassName.............none
DEBUG com.zaxxer.hikari.HikariConfig - dataSourceJNDI..................none
DEBUG com.zaxxer.hikari.HikariConfig - dataSourceProperties............{password=<masked>}
DEBUG com.zaxxer.hikari.HikariConfig - driverClassName.................none
DEBUG com.zaxxer.hikari.HikariConfig - healthCheckProperties...........{}
DEBUG com.zaxxer.hikari.HikariConfig - healthCheckRegistry.............none
DEBUG com.zaxxer.hikari.HikariConfig - idleTimeout.....................600000
DEBUG com.zaxxer.hikari.HikariConfig - initializationFailFast..........true
DEBUG com.zaxxer.hikari.HikariConfig - initializationFailTimeout.......1
DEBUG com.zaxxer.hikari.HikariConfig - isolateInternalQueries..........false
DEBUG com.zaxxer.hikari.HikariConfig - jdbc4ConnectionTest.............false
DEBUG com.zaxxer.hikari.HikariConfig - jdbcUrl.........................jdbc:postgresql://ec2-23-21-155-53.compute-1.amazonaws.com:5432/d1bj65rb5gi9qt?user=ufwvhxlvfjopkm&password=<masked>&sslmode=require
DEBUG com.zaxxer.hikari.HikariConfig - maxLifetime.....................1800000
DEBUG com.zaxxer.hikari.HikariConfig - leakDetectionThreshold..........0
DEBUG com.zaxxer.hikari.HikariConfig - maximumPoolSize.................20
DEBUG com.zaxxer.hikari.HikariConfig - metricRegistry..................none
DEBUG com.zaxxer.hikari.HikariConfig - metricsTrackerFactory...........none
DEBUG com.zaxxer.hikari.HikariConfig - minimumIdle.....................20
DEBUG com.zaxxer.hikari.HikariConfig - password........................<masked>
DEBUG com.zaxxer.hikari.HikariConfig - poolName........................"HikariPool-1"
DEBUG com.zaxxer.hikari.HikariConfig - readOnly........................false
DEBUG com.zaxxer.hikari.HikariConfig - registerMbeans..................false
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutorService........internal
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutor...............none
DEBUG com.zaxxer.hikari.HikariConfig - schema..........................none
DEBUG com.zaxxer.hikari.HikariConfig - threadFactory...................internal
DEBUG com.zaxxer.hikari.HikariConfig - transactionIsolation............default
DEBUG com.zaxxer.hikari.HikariConfig - username........................none
DEBUG com.zaxxer.hikari.HikariConfig - validationTimeout...............5000
INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
Process exited with status 1
2017-12-01 08:38:27.783 [main] INFO  com.zaxxer.hikari.pool.PoolBase - HikariPool-1 - Driver does not support get/set network timeout for connections. (Method org.postgresql.jdbc4.Jdbc4Connection.getNetworkTimeout() is not yet implemented.)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2017-12-01 08:38:27.832 [main] DEBUG com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection org.postgresql.jdbc4.Jdbc4Connection@49c66ade
2017-12-01 08:38:27.834 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:107)
    at kotlin.reflect.jvm.internal.FunctionCaller$Method.callMethod(FunctionCaller.kt:98)
    at kotlin.reflect.jvm.internal.FunctionCaller$StaticMethod.call(FunctionCaller.kt:108)
    at kotlin.reflect.jvm.internal.KCallableImpl.callDefaultMethod(KCallableImpl.kt:149)
    at kotlin.reflect.jvm.internal.KCallableImpl.callBy(KCallableImpl.kt:111)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:270)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:247)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.callFunctionWithInjection(ApplicationEngineEnvironmentReloading.kt:314)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:118)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:227)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:43)
    at com.marcinmoskala.kotlinacademy.backend.ServerKt.main(Server.kt:8)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:15)
    at io.ktor.server.engine.ApplicationEngine$DefaultImpls.start$default(ApplicationEngine.kt:29)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "information_schema.session_state" does not exist
  Position: 15
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:305)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
    at org.jetbrains.squash.schema.DatabaseSchemaBase.createStatements(DatabaseSchemaBase.kt:23)
    at org.jetbrains.squash.dialects.h2.H2DatabaseSchema.currentSchema(H2DatabaseSchema.kt:8)
    at org.jetbrains.squash.drivers.JDBCDatabaseSchema.tables(JDBCDatabaseSchema.kt:12)
    at com.marcinmoskala.kotlinacademy.backend.db.Database$1.invoke(Database.kt:25)
    at com.marcinmoskala.kotlinacademy.backend.db.Database.<init>(Database.kt:46)
    at org.jetbrains.squash.schema.DatabaseSchemaBase.create(DatabaseSchemaBase.kt:10)
    at com.marcinmoskala.kotlinacademy.backend.MainKt.main(Main.kt:39)
    at com.marcinmoskala.kotlinacademy.backend.db.Database$1.invoke(Database.kt:47)
    at org.jetbrains.squash.connection.DatabaseConnectionKt.transaction(DatabaseConnection.kt:25)
    ... 18 more
State changed from starting to crashed
</code>```

答: You cannot use H2Connection with Postgress. Add compile "org.jetbrains.squash:squash-postgres:$squash_version" to your Gradle files and replace H2Connection with PgConnection

ContentLicense: CC BY-SA 3.0

Body:
I am trying to move Ktor backend to Heroku postgres db. Here whole application code:

https://github.com/MarcinMoskala/KotlinAcademyApp/tree/master/backend

To move to Heroku postgres, I based on this example project:

https://github.com/orangy/ktor-heroku-start

I changed my database configuration to following:

private val config = application.environment.config.config("database")

private val poolSize = config.property("poolSize").getString().toInt()

private val hikariConfig = HikariConfig().apply {
    val url = System.getenv("JDBC_DATABASE_URL") ?: config.property("connection").getString()
    application.log.info("DB url is $url")
    jdbcUrl = url
    maximumPoolSize = poolSize
    validate()
}

private val dataSource = HikariDataSource(hikariConfig)

private val connection: DatabaseConnection = H2Connection { dataSource.connection }

private val dispatcher = newFixedThreadPoolContext(poolSize, "database-pool")

init {
    connection.transaction {
        databaseSchema().create(listOf(NewsTable, FeedbackTable, TokensTable))
    }
}

And I added postgressql dependency:

compile "org.postgresql:postgresql:9.4-1201-jdbc4"

Locally it is still creating SQLite database, but when I push it to Heroku then I have following result:

DEBUG com.zaxxer.hikari.HikariConfig - jdbc4ConnectionTest.............false
DEBUG com.zaxxer.hikari.HikariConfig - jdbcUrl.........................jdbc:postgresql://ec7-77-77-777-77.compute-1.amazonaws.com:7777/7777777?user=aaaaaaaaaaaa&password=<masked>&sslmode=require
DEBUG com.zaxxer.hikari.HikariConfig - leakDetectionThreshold..........0
DEBUG com.zaxxer.hikari.HikariConfig - maximumPoolSize.................20
DEBUG com.zaxxer.hikari.HikariConfig - maxLifetime.....................1800000
DEBUG com.zaxxer.hikari.HikariConfig - metricRegistry..................none
DEBUG com.zaxxer.hikari.HikariConfig - metricsTrackerFactory...........none
DEBUG com.zaxxer.hikari.HikariConfig - minimumIdle.....................20
DEBUG com.zaxxer.hikari.HikariConfig - password........................<masked>
 [main] DEBUG com.zaxxer.hikari.HikariConfig - poolName........................"HikariPool-1"
DEBUG com.zaxxer.hikari.HikariConfig - registerMbeans..................false
DEBUG com.zaxxer.hikari.HikariConfig - readOnly........................false
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutor...............none
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutorService........internal
DEBUG com.zaxxer.hikari.HikariConfig - schema..........................none
DEBUG com.zaxxer.hikari.HikariConfig - threadFactory...................internal
DEBUG com.zaxxer.hikari.HikariConfig - transactionIsolation............default
DEBUG com.zaxxer.hikari.HikariConfig - username........................none
DEBUG com.zaxxer.hikari.HikariConfig - validationTimeout...............5000
DEBUG com.zaxxer.hikari.HikariConfig - allowPoolSuspension.............false
DEBUG com.zaxxer.hikari.HikariConfig - autoCommit......................true
DEBUG com.zaxxer.hikari.HikariConfig - HikariPool-1 - configuration:
DEBUG com.zaxxer.hikari.HikariConfig - connectionInitSql...............none
DEBUG com.zaxxer.hikari.HikariConfig - catalog.........................none
DEBUG com.zaxxer.hikari.HikariConfig - connectionTestQuery.............none
DEBUG com.zaxxer.hikari.HikariConfig - connectionTimeout...............30000
DEBUG com.zaxxer.hikari.HikariConfig - dataSource......................none
DEBUG com.zaxxer.hikari.HikariConfig - dataSourceClassName.............none
DEBUG com.zaxxer.hikari.HikariConfig - dataSourceJNDI..................none
DEBUG com.zaxxer.hikari.HikariConfig - dataSourceProperties............{password=<masked>}
DEBUG com.zaxxer.hikari.HikariConfig - driverClassName.................none
DEBUG com.zaxxer.hikari.HikariConfig - healthCheckProperties...........{}
DEBUG com.zaxxer.hikari.HikariConfig - healthCheckRegistry.............none
DEBUG com.zaxxer.hikari.HikariConfig - idleTimeout.....................600000
DEBUG com.zaxxer.hikari.HikariConfig - initializationFailFast..........true
DEBUG com.zaxxer.hikari.HikariConfig - initializationFailTimeout.......1
DEBUG com.zaxxer.hikari.HikariConfig - isolateInternalQueries..........false
DEBUG com.zaxxer.hikari.HikariConfig - jdbc4ConnectionTest.............false
DEBUG com.zaxxer.hikari.HikariConfig - jdbcUrl.........................jdbc:postgresql://ec2-23-21-155-53.compute-1.amazonaws.com:5432/d1bj65rb5gi9qt?user=ufwvhxlvfjopkm&password=<masked>&sslmode=require
DEBUG com.zaxxer.hikari.HikariConfig - maxLifetime.....................1800000
DEBUG com.zaxxer.hikari.HikariConfig - leakDetectionThreshold..........0
DEBUG com.zaxxer.hikari.HikariConfig - maximumPoolSize.................20
DEBUG com.zaxxer.hikari.HikariConfig - metricRegistry..................none
DEBUG com.zaxxer.hikari.HikariConfig - metricsTrackerFactory...........none
DEBUG com.zaxxer.hikari.HikariConfig - minimumIdle.....................20
DEBUG com.zaxxer.hikari.HikariConfig - password........................<masked>
DEBUG com.zaxxer.hikari.HikariConfig - poolName........................"HikariPool-1"
DEBUG com.zaxxer.hikari.HikariConfig - readOnly........................false
DEBUG com.zaxxer.hikari.HikariConfig - registerMbeans..................false
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutorService........internal
DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutor...............none
DEBUG com.zaxxer.hikari.HikariConfig - schema..........................none
DEBUG com.zaxxer.hikari.HikariConfig - threadFactory...................internal
DEBUG com.zaxxer.hikari.HikariConfig - transactionIsolation............default
DEBUG com.zaxxer.hikari.HikariConfig - username........................none
DEBUG com.zaxxer.hikari.HikariConfig - validationTimeout...............5000
INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
Process exited with status 1
2017-12-01 08:38:27.783 [main] INFO  com.zaxxer.hikari.pool.PoolBase - HikariPool-1 - Driver does not support get/set network timeout for connections. (Method org.postgresql.jdbc4.Jdbc4Connection.getNetworkTimeout() is not yet implemented.)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2017-12-01 08:38:27.832 [main] DEBUG com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection org.postgresql.jdbc4.Jdbc4Connection@49c66ade
2017-12-01 08:38:27.834 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:107)
    at kotlin.reflect.jvm.internal.FunctionCaller$Method.callMethod(FunctionCaller.kt:98)
    at kotlin.reflect.jvm.internal.FunctionCaller$StaticMethod.call(FunctionCaller.kt:108)
    at kotlin.reflect.jvm.internal.KCallableImpl.callDefaultMethod(KCallableImpl.kt:149)
    at kotlin.reflect.jvm.internal.KCallableImpl.callBy(KCallableImpl.kt:111)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:270)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:247)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.callFunctionWithInjection(ApplicationEngineEnvironmentReloading.kt:314)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:118)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:227)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:43)
    at com.marcinmoskala.kotlinacademy.backend.ServerKt.main(Server.kt:8)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:15)
    at io.ktor.server.engine.ApplicationEngine$DefaultImpls.start$default(ApplicationEngine.kt:29)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "information_schema.session_state" does not exist
  Position: 15
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:305)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
    at org.jetbrains.squash.schema.DatabaseSchemaBase.createStatements(DatabaseSchemaBase.kt:23)
    at org.jetbrains.squash.dialects.h2.H2DatabaseSchema.currentSchema(H2DatabaseSchema.kt:8)
    at org.jetbrains.squash.drivers.JDBCDatabaseSchema.tables(JDBCDatabaseSchema.kt:12)
    at com.marcinmoskala.kotlinacademy.backend.db.Database$1.invoke(Database.kt:25)
    at com.marcinmoskala.kotlinacademy.backend.db.Database.<init>(Database.kt:46)
    at org.jetbrains.squash.schema.DatabaseSchemaBase.create(DatabaseSchemaBase.kt:10)
    at com.marcinmoskala.kotlinacademy.backend.MainKt.main(Main.kt:39)
    at com.marcinmoskala.kotlinacademy.backend.db.Database$1.invoke(Database.kt:47)
    at org.jetbrains.squash.connection.DatabaseConnectionKt.transaction(DatabaseConnection.kt:25)
    ... 18 more
State changed from starting to crashed


问:
interval missing first item
I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

```<code> <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
    <h1>Creative Development</h1>
    <h2 id="changingword">Design</h2>
  </div>
</code>```

The JS:

```<code><script>
(function(){
    var words = [
        'Development',
        'E-commerce Solutions',
        'Optimisation',
        'Support',
        'Design'
        ], i = 0;
    setInterval(function(){
        $('#changingword').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
        });
    }, 1500);

})();
</script>
</code>```

Any ideas why this is happening?

答:
The problem is in here:

```<code>$('#changingword').fadeOut(function(){
    $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
});
</code>```

You're updating i, then using the resulting value in the calculation.

Update i after using it:

```<code>$('#changingword').fadeOut(function(){
    $(this).html(words[i%words.length]).fadeIn("slow");
    i++;
});
</code>```

Title: interval missing first item

Body:
I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

Creative Development

Design

The JS:

Any ideas why this is happening?

Body:
The problem is in here:

$('#changingword').fadeOut(function(){
    $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
});

You're updating i, then using the resulting value in the calculation.

Update i after using it:

$('#changingword').fadeOut(function(){
    $(this).html(words[i%words.length]).fadeIn("slow");
    i++;
});


问:
Drupal 8 add javascript and pass data in a hook with custom module
I am building a custom module with Drupal 8. One of the requirements of the module is that it sets up a javascript file based on the configuration settings, which the user of the module sets up in module configuration.

The javascript which needs to be added to the page depends on the configuration settings. Hence I can not add it using Libraries as mentioned in this article: Adding assets to Drupal module.

I first implemented it using a block. I use Twig templates to pass the configuration variables in PHP to the twig file, and in the twig file, I have a  tag to add the javascript based on the config variables. Refer Using twig templates.

The problem with this approach is that user needs to add the block on the page, and there is no UI facing element on that block. I also find it very messy.

Is there a cleaner way to add my javascript using hook and pass variables to it? I looked around and found hook_install and hook_page_attachments. So I can add Javascript, but don't know how I can pass any php variables to it.

I am new to Drupal development. Any help with this is really appreciated.

TL;DR I need to find a way to add Javascript using Drupal hook and pass some PHP variables to it.

答:
Use in hook_page_attachments:

```<code>$attachments['#attached']['drupalSettings']['myvar'] = $myVariable;
</code>```

Then in your js (I assume you already know how to attach js library):

```<code>(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.my_custom_behavior = {
    attach: function (context, settings) {
      var strings = drupalSettings.myvar;
      ...
    }
  }

})(jQuery, Drupal, drupalSettings);
</code>```

See nice Acquia tutorial for more examples.

Body:
Use in hook_page_attachments:

$attachments['#attached']['drupalSettings']['myvar'] = $myVariable;

Then in your js (I assume you already know how to attach js library):

(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.my_custom_behavior = {
    attach: function (context, settings) {
      var strings = drupalSettings.myvar;
      ...
    }
  }

})(jQuery, Drupal, drupalSettings);

See nice Acquia tutorial for more examples.


问:
Combining an Image with Text inside a Button
Hi guys im new to coding and currently learning xml and java for android.
Im trying to make a Button which says GOAL but instead of the "O" it will have an image of a ball,i tried just making an image in a designer program thats says goal with the icon of the ball inside it and than use it as an image background for the button but it than misses the gray (which im planning to change to green) background and its not really what im going for.
Is there a way to just add an image inside a button that has text?
Or should i just design the button in a different software and than add it as a background for the button?

like "Te~ImageHere~xt"

答:
Try this use android:drawableLeft="@mipmap/ic_launcher_round" to add image in Button

```<code><Button
    android:text="Prem"
    android:drawableLeft="@mipmap/ic_launcher_round"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</code>```

You can also use drawableTop, drawableBottom, drawableRight and drawableEnd like below code

```<code>android:drawableTop="@mipmap/ic_launcher_round"
android:drawableBottom="@mipmap/ic_launcher_round"
android:drawableRight="@mipmap/ic_launcher_round"
android:drawableLeft="@mipmap/ic_launcher_round"
android:drawableEnd="@mipmap/ic_launcher_round"
</code>```

Body:
Try this use android:drawableLeft="@mipmap/ic_launcher_round" to add image in Button

<Button
    android:text="Prem"
    android:drawableLeft="@mipmap/ic_launcher_round"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

You can also use drawableTop, drawableBottom, drawableRight and drawableEnd like below code

android:drawableTop="@mipmap/ic_launcher_round"
android:drawableBottom="@mipmap/ic_launcher_round"
android:drawableRight="@mipmap/ic_launcher_round"
android:drawableLeft="@mipmap/ic_launcher_round"
android:drawableEnd="@mipmap/ic_launcher_round"


问:
How to find maximum value in a list of arrays
I have a very large list of arrays that looks something like this:

```<code>'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])
</code>```

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

答:
would this work?</p>

```<code>big_dict = {"apple" : list([1,2,3]),
            "pear" : list([4,5,6])}

print max([max(v) for v in big_dict.itervalues()])
</code>```

Body:
I have a very large list of arrays that looks something like this:

'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

Body:
would this work?

big_dict = {"apple" : list([1,2,3]),
            "pear" : list([4,5,6])}

print max([max(v) for v in big_dict.itervalues()])


问:
Lazy Loading tutorial by fedor in list update problem?
friends,

i am using following tutorial to lazy load list view

now problem is i cannot update if new data comes in any one guide me what mistake am i doing?
Lazy Load Tutorial

my changed code

```<code>public class MainActivity extends Activity {

    ListView list;
    LazyAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this, mStrings,mValues);
        list.setAdapter(adapter);

        Button b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(listener);
    }

    @Override
    public void onDestroy()
    {
        adapter.imageLoader.stopThread();
        list.setAdapter(null);
        super.onDestroy();
    }

    public OnClickListener listener=new OnClickListener(){
        @Override
        public void onClick(View v) {
            adapter.imageLoader.clearCache();
            ChangeData();
           // adapter=new LazyAdapter(MainActivity.this, mStrings,mValues);

            adapter.notifyDataSetChanged();
        }
    };

    public void ChangeData()
    {
        mValues = mValues1;
        mStrings = mStrings2;

    }

 private String[] mValues = {

            "670625317/aam-logo-v3-twitter.png",
            "740897825/AndroidCast-350_normal.png",
            "121630227/Droid_normal.jpg",
            "957149154/twitterhalf_normal.jpg"
 };

    private String[] mValues1 = {

            "670625317/aam-logo-v3-twitter.png",
            "740897825/AndroidCast-350_normal.png",
            "121630227/Droid_normal.jpg",
            "957149154/twitterhalf_normal.jpg",
            "97470808/icon_normal.png",
            "511790713/AG.png",
            "956404323/androinica-avatar_normal.png",
            "909231146/Android_Biz_Man_normal.png",

    };

    private String[] mStrings ={ "http://zef.me/wp-content/uploads/2008/02/funny-cat.jpg",
            "http://www.prchurch.com/data/43_800px-Bulgaria_stub.svg.png",
            "http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
            "http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg"};

    private String[] mStrings2={
            "http://zef.me/wp-content/uploads/2008/02/funny-cat.jpg",
            "http://www.prchurch.com/data/43_800px-Bulgaria_stub.svg.png",
            "http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
            "http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
            "http://a1.twimg.com/profile_images/97470808/icon_normal.png",
            "http://a3.twimg.com/profile_images/511790713/AG.png",
            "http://a3.twimg.com/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.twimg.com/profile_images/909231146/Android_Biz_Man_normal.png",
               };
}
</code>```

答:
I believe whats happening here is that the data does not really change for the adapter.
You could add a method like this to the adapter:

```<code>changeData(String[] d) {

 data=d;
 notifyDatasetChanged();
}
</code>```

I think that should resolve your problem.

Cheers

Body:
friends,

i am using following tutorial to lazy load list view

now problem is i cannot update if new data comes in any one guide me what mistake am i doing?
Lazy Load Tutorial

my changed code

public class MainActivity extends Activity {

    ListView list;
    LazyAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this, mStrings,mValues);
        list.setAdapter(adapter);

        Button b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(listener);
    }

    @Override
    public void onDestroy()
    {
        adapter.imageLoader.stopThread();
        list.setAdapter(null);
        super.onDestroy();
    }

    public OnClickListener listener=new OnClickListener(){
        @Override
        public void onClick(View v) {
            adapter.imageLoader.clearCache();
            ChangeData();
           // adapter=new LazyAdapter(MainActivity.this, mStrings,mValues);

            adapter.notifyDataSetChanged();
        }
    };

    public void ChangeData()
    {
        mValues = mValues1;
        mStrings = mStrings2;

    }

 private String[] mValues = {

            "670625317/aam-logo-v3-twitter.png",
            "740897825/AndroidCast-350_normal.png",
            "121630227/Droid_normal.jpg",
            "957149154/twitterhalf_normal.jpg"
 };

    private String[] mValues1 = {

            "670625317/aam-logo-v3-twitter.png",
            "740897825/AndroidCast-350_normal.png",
            "121630227/Droid_normal.jpg",
            "957149154/twitterhalf_normal.jpg",
            "97470808/icon_normal.png",
            "511790713/AG.png",
            "956404323/androinica-avatar_normal.png",
            "909231146/Android_Biz_Man_normal.png",

    };

    private String[] mStrings ={ "http://zef.me/wp-content/uploads/2008/02/funny-cat.jpg",
            "http://www.prchurch.com/data/43_800px-Bulgaria_stub.svg.png",
            "http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
            "http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg"};

    private String[] mStrings2={
            "http://zef.me/wp-content/uploads/2008/02/funny-cat.jpg",
            "http://www.prchurch.com/data/43_800px-Bulgaria_stub.svg.png",
            "http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
            "http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
            "http://a1.twimg.com/profile_images/97470808/icon_normal.png",
            "http://a3.twimg.com/profile_images/511790713/AG.png",
            "http://a3.twimg.com/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.twimg.com/profile_images/909231146/Android_Biz_Man_normal.png",
               };
}

Body:
I believe whats happening here is that the data does not really change for the adapter.
You could add a method like this to the adapter:

changeData(String[] d) {

 data=d;
 notifyDatasetChanged();
}

I think that should resolve your problem.

Cheers


问:
React.js create multiple tables from array
I have searched for a solution to my problem but nothing worked probably because of my lack of understanding.

I am trying to work with React.js to create tables of dynamic length.

I call an API in my project with the axios library that returns an array of JSON objects, We dont know the size of the returned array, but for each JSON object within the array I need to create a table and add its data. Here is an example of the API call return.

```<code>[

  {
        "feedbackID": 12,
        "posterID": "John",
        "comment": "shortcomment"
    },
    {
        "feedbackID": 23,
        "posterID": "billy",
        "comment": "long comment"
  }
]
</code>```

So with this return I will have to create 2 tables, one under the other as follows:

```<code>| Feedback ID | 12           |
| Poster ID   | John         |
| Comment     | shortcomment |

| Feedback ID | 23           |
| Poster ID   | billy        |
| Comment     | long comment |
</code>```

Here is my code so far:

```<code>   export class ViewFeedback extends Component {
  constructor(props) {
    super(props)
    this.state = {
      feedback: []
    }
  }

  componentDidMount() {
    var id = this.props.match.params.id;

    // this returns the JSON array like shown above
    getfeedback(id).then((response) => {

     this.setState({feedback:response})

    })

  }
</code>```

I have no clue at all how to make the tables, I tried the createElement and also Grid But I did it so wrong it wouldn't even compile the code.

答:
```<code>{this.state.feedback.map(item => {
  return (
    <table>
      <tr>
          <td>Feedback ID</td>
          <td>{item.feedbackID}</td>
      </tr>
      <tr>
          <td>Poster ID</td>
          <td>{item.posterID}</td>
      </tr>
      <tr>
          <td>Comment</td>
          <td>{item.comment}</td>
      </tr>
  </table>
  )
})}
</code>```

Use this in your render method

Body:
I have searched for a solution to my problem but nothing worked probably because of my lack of understanding.

I am trying to work with React.js to create tables of dynamic length.

I call an API in my project with the axios library that returns an array of JSON objects, We dont know the size of the returned array, but for each JSON object within the array I need to create a table and add its data. Here is an example of the API call return.

[

  {
        "feedbackID": 12,
        "posterID": "John",
        "comment": "shortcomment"
    },
    {
        "feedbackID": 23,
        "posterID": "billy",
        "comment": "long comment"
  }
]

So with this return I will have to create 2 tables, one under the other as follows:

| Feedback ID | 12           |
| Poster ID   | John         |
| Comment     | shortcomment |

| Feedback ID | 23           |
| Poster ID   | billy        |
| Comment     | long comment |

Here is my code so far:

   export class ViewFeedback extends Component {
  constructor(props) {
    super(props)
    this.state = {
      feedback: []
    }
  }

  componentDidMount() {
    var id = this.props.match.params.id;

    // this returns the JSON array like shown above
    getfeedback(id).then((response) => {

     this.setState({feedback:response})

    })

  }

I have no clue at all how to make the tables, I tried the createElement and also Grid But I did it so wrong it wouldn't even compile the code.

Body:
{this.state.feedback.map(item => {
  return (
    <table>
      <tr>
          <td>Feedback ID</td>
          <td>{item.feedbackID}</td>
      </tr>
      <tr>
          <td>Poster ID</td>
          <td>{item.posterID}</td>
      </tr>
      <tr>
          <td>Comment</td>
          <td>{item.comment}</td>
      </tr>
  </table>
  )
})}

Use this in your render method


问:
Why might my .click event not fire?
I'm trying to create a carousel using jQuery. I have a prev class and a next class. A button and an a tag, respectively. Neither .click event works. The events are inside document.ready. </p>

```<code><button type="button" class="prev">❮</button>
<a class="next">❯</a>
</code>```

<p>.</p>

```<code>$(document).ready(function(){
    $("#slide1").show();

    $(".next").click(function () {
        if ($slideNumber < 2){
            switch ($slideNumber){
                case 0: $("#slide0").hide();
                case 1: $("#slide1").hide();
            }
            $slideNumber++
        }else { ...
    });

    $(".prev").click(function () {
        if ($slideNumber > 0){
            switch ($slideNumber){
                case 1: $("#slide1").hide();
                case 2: $("#slide2").hide();
            }
            $slideNumber--
        }else { ...
</code>```

答: The issue is because of overlap of HTML elements. This caused the clickable area of the button/a tag to be obstructed. </p>

Title: Why might my .click event not fire?

Body:
I'm trying to create a carousel using jQuery. I have a prev class and a next class. A button and an a tag, respectively. Neither .click event works. The events are inside document.ready.

<button type="button" class="prev">❮</button>
❯

.

$(document).ready(function(){
    $("#slide1").show();

    $(".next").click(function () {
        if ($slideNumber < 2){
            switch ($slideNumber){
                case 0: $("#slide0").hide();
                case 1: $("#slide1").hide();
            }
            $slideNumber++
        }else { ...
    });

    $(".prev").click(function () {
        if ($slideNumber > 0){
            switch ($slideNumber){
                case 1: $("#slide1").hide();
                case 2: $("#slide2").hide();
            }
            $slideNumber--
        }else { ...


答: you can't directly do that, try to form a another array and check 'max(arraylist)'</p>

Title: How to find maximum value in a list of arrays


问:
How to use get_attachment call upon QueryResult (python cloudant) ?
I've been trying to get attachment image data  from documents in Cloudant.
I can successfully do it once a document is selected (direct extract with _id, etc).

Now trying to do it in combination with "query" operation using selector, I run into trouble.

Here is my code.

```<code>targetName="chibika33"
targetfile="chibitest.png"

#--------------------------------------------------
# get all the documents with the specific nameField
#--------------------------------------------------
myDatabase.create_query_index(fields = ['nameField'])
selector = {'nameField': {'$eq': targetName}}
docs = myDatabase.get_query_result(selector)

#--------------------------------------------------
# get the attachment files to them, save it locally
#--------------------------------------------------
count = 0
for doc in docs:
    count=count+1
    result_filename="result%03d.png"%(count)

    dataContent = doc.get_attachment(targetfile, attachment_type='binary')
    dataContentb =base64.b64decode(dataContent)
    with open(result_filename,'wb') as output:
        output.write(dataContentb)
</code>```

Causes error as;

```<code>Traceback (most recent call last):
  File "view8.py", line 44, in <module>

   dataContent = doc.get_attachment(targetfile, attachment_type='binary')
AttributeError: 'dict' object has no attribute 'get_attachment'
</code>```

So far, I've been unable to find any API for converting dict to document object  in the python-cloudant-document...[python-cloudant document]:  http://python-cloudant.readthedocs.io/en/latest/index.html

Any advise would be highly appreciated.

答:
The returned structure from get_query_result(...) isn't an array of documents.

Try:

```<code>resp = myDatabase.get_query_result(selector)
for doc in resp['docs']:
    # your code here
</code>```

See the docs at:

http://python-cloudant.readthedocs.io/en/latest/database.html#cloudant.database.CloudantDatabase.get_query_result

Body:
I've been trying to get attachment image data  from documents in Cloudant.
I can successfully do it once a document is selected (direct extract with _id, etc).

Now trying to do it in combination with "query" operation using selector, I run into trouble.

Here is my code.

targetName="chibika33"
targetfile="chibitest.png"

#--------------------------------------------------
# get all the documents with the specific nameField
#--------------------------------------------------
myDatabase.create_query_index(fields = ['nameField'])
selector = {'nameField': {'$eq': targetName}}
docs = myDatabase.get_query_result(selector)

#--------------------------------------------------
# get the attachment files to them, save it locally
#--------------------------------------------------
count = 0
for doc in docs:
    count=count+1
    result_filename="result%03d.png"%(count)

    dataContent = doc.get_attachment(targetfile, attachment_type='binary')
    dataContentb =base64.b64decode(dataContent)
    with open(result_filename,'wb') as output:
        output.write(dataContentb)

Causes error as;

Traceback (most recent call last):
  File "view8.py", line 44, in <module>

   dataContent = doc.get_attachment(targetfile, attachment_type='binary')
AttributeError: 'dict' object has no attribute 'get_attachment'

So far, I've been unable to find any API for converting dict to document object  in the python-cloudant-document...[python-cloudant document]:  http://python-cloudant.readthedocs.io/en/latest/index.html

Any advise would be highly appreciated.

Body:
The returned structure from get_query_result(...) isn't an array of documents.

Try:

resp = myDatabase.get_query_result(selector)
for doc in resp['docs']:
    # your code here

See the docs at:

http://python-cloudant.readthedocs.io/en/latest/database.html#cloudant.database.CloudantDatabase.get_query_result


问:
JaCoCo and MR Jars
There is an issue with JaCoCo and the MultiRelease JAR files. Since the same class name exist on two places, JaCoCo complains:

```<code>Caused by: java.lang.IllegalStateException: Can't add different class with same name: jodd/core/JavaBridge
        at org.jacoco.core.analysis.CoverageBuilder.visitCoverage(CoverageBuilder.java:107)
        at org.jacoco.core.analysis.Analyzer$1.visitEnd(Analyzer.java:96)
</code>```

How we can tell JaCoCo (in Gradle) to skip the classes from META-INF path? OR to behave like it should (use correct class and ignoring other versions), depending on JVM version?

答:
As explained by @nullpointer, JaCoCo doesn't support Multi-Release JAR Files.

My workaround is to ignore the versions classes. I was not able to ignore just the class by explicitly set its name, it looks like JaCoCo is scanning all of them and then only later applies the filters for exclusion (but maybe I am wrong).

Therefore, the only way to remove versions classes was to exclude all resources - since they are not used anyway. Like this:

```<code>task codeCoverage(type: JacocoReport) {
    executionData fileTree("${buildDir}/jacoco/").include("*.exec")

    //sourceSets it.sourceSets.main  <--- REPLACED WITH FOLLOWING LINES!!!
    sourceDirectories = it.sourceSets.main.java
    classDirectories = it.sourceSets.main.output.classesDirs

    reports {
        xml.enabled true
        html.enabled true
    }
}
</code>```

So I changed this:

```<code>sourceSets it.sourceSets.main
</code>```

to this:

```<code>sourceDirectories = it.sourceSets.main.java
classDirectories = it.sourceSets.main.output.classesDirs
</code>```

The difference here that we explicitly state: sourceSets.main.output.classesDirs which excludes resources.

Source

Title: JaCoCo and MR Jars

Body:
There is an issue with JaCoCo and the MultiRelease JAR files. Since the same class name exist on two places, JaCoCo complains:

Caused by: java.lang.IllegalStateException: Can't add different class with same name: jodd/core/JavaBridge
        at org.jacoco.core.analysis.CoverageBuilder.visitCoverage(CoverageBuilder.java:107)
        at org.jacoco.core.analysis.Analyzer$1.visitEnd(Analyzer.java:96)

How we can tell JaCoCo (in Gradle) to skip the classes from META-INF path? OR to behave like it should (use correct class and ignoring other versions), depending on JVM version?

Body:
As explained by @nullpointer, JaCoCo doesn't support Multi-Release JAR Files.

My workaround is to ignore the versions classes. I was not able to ignore just the class by explicitly set its name, it looks like JaCoCo is scanning all of them and then only later applies the filters for exclusion (but maybe I am wrong).

Therefore, the only way to remove versions classes was to exclude all resources - since they are not used anyway. Like this:

task codeCoverage(type: JacocoReport) {
    executionData fileTree("${buildDir}/jacoco/").include("*.exec")

    //sourceSets it.sourceSets.main  <--- REPLACED WITH FOLLOWING LINES!!!
    sourceDirectories = it.sourceSets.main.java
    classDirectories = it.sourceSets.main.output.classesDirs

    reports {
        xml.enabled true
        html.enabled true
    }
}

So I changed this:

sourceSets it.sourceSets.main

to this:

sourceDirectories = it.sourceSets.main.java
classDirectories = it.sourceSets.main.output.classesDirs

The difference here that we explicitly state: sourceSets.main.output.classesDirs which excludes resources.

Source