text:
//===--- ToolChain.cpp - Collections of tools for one platform ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Tools.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/SanitizerArgs.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetParser.h"

using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm;
using namespace llvm::opt;

static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
                         options::OPT_fno_rtti, options::OPT_frtti);
}

static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
                                             const llvm::Triple &Triple,
                                             const Arg *CachedRTTIArg) {
  // Explicit rtti/no-rtti args
  if (CachedRTTIArg) {
    if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
      return ToolChain::RM_EnabledExplicitly;
    else
      return ToolChain::RM_DisabledExplicitly;
  }

  // -frtti is default, except for the PS4 CPU.
  if (!Triple.isPS4CPU())
    return ToolChain::RM_EnabledImplicitly;

  // On the PS4, turning on c++ exceptions turns on rtti.
  // We're assuming that, if we see -fexceptions, rtti gets turned on.
  Arg *Exceptions = Args.getLastArgNoClaim(
      options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
      options::OPT_fexceptions, options::OPT_fno_exceptions);
  if (Exceptions &&
      (Exceptions->getOption().matches(options::OPT_fexceptions) ||
       Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
    return ToolChain::RM_EnabledImplicitly;

  return ToolChain::RM_DisabledImplicitly;
}

ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
                     const ArgList &Args)
    : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
      CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
  if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
    if (!isThreadModelSupported(A->getValue()))
      D.Diag(diag::err_drv_invalid_thread_model_for_target)
          << A->getValue() << A->getAsString(Args);
}

ToolChain::~ToolChain() {
}

vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); }

bool ToolChain::useIntegratedAs() const {
  return Args.hasFlag(options::OPT_fintegrated_as,
                      options::OPT_fno_integrated_as,
                      IsIntegratedAssemblerDefault());
}

const SanitizerArgs& ToolChain::getSanitizerArgs() const {
  if (!SanitizerArguments.get())
    SanitizerArguments.reset(new SanitizerArgs(*this, Args));
  return *SanitizerArguments.get();
}

namespace {
struct DriverSuffix {
  const char *Suffix;
  const char *ModeFlag;
};

const DriverSuffix *FindDriverSuffix(StringRef ProgName) {
  // A list of known driver suffixes. Suffixes are compared against the
  // program name in order. If there is a match, the frontend type is updated as
  // necessary by applying the ModeFlag.
  static const DriverSuffix DriverSuffixes[] = {
      {"clang", nullptr},
      {"clang++", "--driver-mode=g++"},
      {"clang-c++", "--driver-mode=g++"},
      {"clang-cc", nullptr},
      {"clang-cpp", "--driver-mode=cpp"},
      {"clang-g++", "--driver-mode=g++"},
      {"clang-gcc", nullptr},
      {"clang-cl", "--driver-mode=cl"},
      {"cc", nullptr},
      {"cpp", "--driver-mode=cpp"},
      {"cl", "--driver-mode=cl"},
      {"++", "--driver-mode=g++"},
  };

  for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
    if (ProgName.endswith(DriverSuffixes[i].Suffix))
      return &DriverSuffixes[i];
  return nullptr;
}

/// Normalize the program name from argv[0] by stripping the file extension if
/// present and lower-casing the string on Windows.
std::string normalizeProgramName(llvm::StringRef Argv0) {
  std::string ProgName = llvm::sys::path::stem(Argv0);
#ifdef LLVM_ON_WIN32
  // Transform to lowercase for case insensitive file systems.
  std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
#endif
  return ProgName;
}

const DriverSuffix *parseDriverSuffix(StringRef ProgName) {
  // Try to infer frontend type and default target from the program name by
  // comparing it against DriverSuffixes in order.

  // If there is a match, the function tries to identify a target as prefix.
  // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
  // prefix "x86_64-linux". If such a target prefix is found, it may be
  // added via -target as implicit first argument.
  const DriverSuffix *DS = FindDriverSuffix(ProgName);

  if (!DS) {
    // Try again after stripping any trailing version number:
    // clang++3.5 -> clang++
    ProgName = ProgName.rtrim("0123456789.");
    DS = FindDriverSuffix(ProgName);
  }

  if (!DS) {
    // Try again after stripping trailing -component.
    // clang++-tot -> clang++
    ProgName = ProgName.slice(0, ProgName.rfind('-'));
    DS = FindDriverSuffix(ProgName);
  }
  return DS;
}
} // anonymous namespace

std::pair<std::string, std::string>
ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
  std::string ProgName = normalizeProgramName(PN);
  const DriverSuffix *DS = parseDriverSuffix(ProgName);
  if (!DS)
    return std::make_pair("", "");
  std::string ModeFlag = DS->ModeFlag == nullptr ? "" : DS->ModeFlag;

  std::string::size_type LastComponent =
      ProgName.rfind('-', ProgName.size() - strlen(DS->Suffix));
  if (LastComponent == std::string::npos)
    return std::make_pair("", ModeFlag);

  // Infer target from the prefix.
  StringRef Prefix(ProgName);
  Prefix = Prefix.slice(0, LastComponent);
  std::string IgnoredError;
  std::string Target;
  if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
    Target = Prefix;
  }
  return std::make_pair(Target, ModeFlag);
}

StringRef ToolChain::getDefaultUniversalArchName() const {
  // In universal driver terms, the arch name accepted by -arch isn't exactly
  // the same as the ones that appear in the triple. Roughly speaking, this is
  // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
  // only interesting special case is powerpc.
  switch (Triple.getArch()) {
  case llvm::Triple::ppc:
    return "ppc";
  case llvm::Triple::ppc64:
    return "ppc64";
  case llvm::Triple::ppc64le:
    return "ppc64le";
  default:
    return Triple.getArchName();
  }
}

bool ToolChain::IsUnwindTablesDefault() const {
  return false;
}

Tool *ToolChain::getClang() const {
  if (!Clang)
    Clang.reset(new tools::Clang(*this));
  return Clang.get();
}

Tool *ToolChain::buildAssembler() const {
  return new tools::ClangAs(*this);
}

Tool *ToolChain::buildLinker() const {
  llvm_unreachable("Linking is not supported by this toolchain");
}

Tool *ToolChain::getAssemble() const {
  if (!Assemble)
    Assemble.reset(buildAssembler());
  return Assemble.get();
}

Tool *ToolChain::getClangAs() const {
  if (!Assemble)
    Assemble.reset(new tools::ClangAs(*this));
  return Assemble.get();
}

Tool *ToolChain::getLink() const {
  if (!Link)
    Link.reset(buildLinker());
  return Link.get();
}

Tool *ToolChain::getTool(Action::ActionClass AC) const {
  switch (AC) {
  case Action::AssembleJobClass:
    return getAssemble();

  case Action::LinkJobClass:
    return getLink();

  case Action::InputClass:
  case Action::BindArchClass:
  case Action::CudaDeviceClass:
  case Action::CudaHostClass:
  case Action::LipoJobClass:
  case Action::DsymutilJobClass:
  case Action::VerifyDebugInfoJobClass:
    llvm_unreachable("Invalid tool kind.");

  case Action::CompileJobClass:
  case Action::PrecompileJobClass:
  case Action::PreprocessJobClass:
  case Action::AnalyzeJobClass:
  case Action::MigrateJobClass:
  case Action::VerifyPCHJobClass:
  case Action::BackendJobClass:
    return getClang();
  }

  llvm_unreachable("Invalid tool kind.");
}

static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
                                             const ArgList &Args) {
  const llvm::Triple &Triple = TC.getTriple();
  bool IsWindows = Triple.isOSWindows();

  if (Triple.isWindowsMSVCEnvironment() && TC.getArch() == llvm::Triple::x86)
    return "i386";

  if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
    return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
               ? "armhf"
               : "arm";

  return TC.getArchName();
}

std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
                                     bool Shared) const {
  const llvm::Triple &TT = getTriple();
  const char *Env = TT.isAndroid() ? "-android" : "";
  bool IsITANMSVCWindows =
      TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();

  StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
  const char *Prefix = IsITANMSVCWindows ? "" : "lib";
  const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
                              : (IsITANMSVCWindows ? ".lib" : ".a");

  SmallString<128> Path(getDriver().ResourceDir);
  StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS();
  llvm::sys::path::append(Path, "lib", OSLibName);
  llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
                                    Arch + Env + Suffix);
  return Path.str();
}

const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
                                              StringRef Component,
                                              bool Shared) const {
  return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
}

bool ToolChain::needsProfileRT(const ArgList &Args) {
  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
                   false) ||
      Args.hasArg(options::OPT_fprofile_generate) ||
      Args.hasArg(options::OPT_fprofile_generate_EQ) ||
      Args.hasArg(options::OPT_fprofile_instr_generate) ||
      Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
      Args.hasArg(options::OPT_fcreate_profile) ||
      Args.hasArg(options::OPT_coverage))
    return true;

  return false;
}

Tool *ToolChain::SelectTool(const JobAction &JA) const {
  if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
  Action::ActionClass AC = JA.getKind();
  if (AC == Action::AssembleJobClass && useIntegratedAs())
    return getClangAs();
  return getTool(AC);
}

std::string ToolChain::GetFilePath(const char *Name) const {
  return D.GetFilePath(Name, *this);
}

std::string ToolChain::GetProgramPath(const char *Name) const {
  return D.GetProgramPath(Name, *this);
}

std::string ToolChain::GetLinkerPath() const {
  if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
    StringRef Suffix = A->getValue();

    // If we're passed -fuse-ld= with no argument, or with the argument ld,
    // then use whatever the default system linker is.
    if (Suffix.empty() || Suffix == "ld")
      return GetProgramPath("ld");

    llvm::SmallString<8> LinkerName("ld.");
    LinkerName.append(Suffix);

    std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
    if (llvm::sys::fs::exists(LinkerPath))
      return LinkerPath;

    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
    return "";
  }

  return GetProgramPath(DefaultLinker);
}

types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
  return types::lookupTypeForExtension(Ext);
}

bool ToolChain::HasNativeLLVMSupport() const {
  return false;
}

bool ToolChain::isCrossCompiling() const {
  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
  switch (HostTriple.getArch()) {
  // The A32/T32/T16 instruction sets are not separate architectures in this
  // context.
  case llvm::Triple::arm:
  case llvm::Triple::armeb:
  case llvm::Triple::thumb:
  case llvm::Triple::thumbeb:
    return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
           getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
  default:
    return HostTriple.getArch() != getArch();
  }
}

ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
                     VersionTuple());
}

bool ToolChain::isThreadModelSupported(const StringRef Model) const {
  if (Model == "single") {
    // FIXME: 'single' is only supported on ARM and WebAssembly so far.
    return Triple.getArch() == llvm::Triple::arm ||
           Triple.getArch() == llvm::Triple::armeb ||
           Triple.getArch() == llvm::Triple::thumb ||
           Triple.getArch() == llvm::Triple::thumbeb ||
           Triple.getArch() == llvm::Triple::wasm32 ||
           Triple.getArch() == llvm::Triple::wasm64;
  } else if (Model == "posix")
    return true;

  return false;
}

std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
                                         types::ID InputType) const {
  switch (getTriple().getArch()) {
  default:
    return getTripleString();

  case llvm::Triple::x86_64: {
    llvm::Triple Triple = getTriple();
    if (!Triple.isOSBinFormatMachO())
      return getTripleString();

    if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
      // x86_64h goes in the triple. Other -march options just use the
      // vanilla triple we already have.
      StringRef MArch = A->getValue();
      if (MArch == "x86_64h")
        Triple.setArchName(MArch);
    }
    return Triple.getTriple();
  }
  case llvm::Triple::aarch64: {
    llvm::Triple Triple = getTriple();
    if (!Triple.isOSBinFormatMachO())
      return getTripleString();

    // FIXME: older versions of ld64 expect the "arm64" component in the actual
    // triple string and query it to determine whether an LTO file can be
    // handled. Remove this when we don't care any more.
    Triple.setArchName("arm64");
    return Triple.getTriple();
  }
  case llvm::Triple::arm:
  case llvm::Triple::armeb:
  case llvm::Triple::thumb:
  case llvm::Triple::thumbeb: {
    // FIXME: Factor into subclasses.
    llvm::Triple Triple = getTriple();
    bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
                       getTriple().getArch() == llvm::Triple::thumbeb;

    // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
    // '-mbig-endian'/'-EB'.
    if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
                                 options::OPT_mbig_endian)) {
      IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
    }

    // Thumb2 is the default for V7 on Darwin.
    //
    // FIXME: Thumb should just be another -target-feaure, not in the triple.
    StringRef MCPU, MArch;
    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
      MCPU = A->getValue();
    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
      MArch = A->getValue();
    std::string CPU =
        Triple.isOSBinFormatMachO()
            ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
            : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
    StringRef Suffix =
      tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
    bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::PK_M;
    bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
                                       getTriple().isOSBinFormatMachO());
    // FIXME: this is invalid for WindowsCE
    if (getTriple().isOSWindows())
      ThumbDefault = true;
    std::string ArchName;
    if (IsBigEndian)
      ArchName = "armeb";
    else
      ArchName = "arm";

    // Assembly files should start in ARM mode, unless arch is M-profile.
    if ((InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb,
         options::OPT_mno_thumb, ThumbDefault)) || IsMProfile) {
      if (IsBigEndian)
        ArchName = "thumbeb";
      else
        ArchName = "thumb";
    }
    Triple.setArchName(ArchName + Suffix.str());

    return Triple.getTriple();
  }
  }
}

std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
                                                   types::ID InputType) const {
  return ComputeLLVMTriple(Args, InputType);
}

void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
                                          ArgStringList &CC1Args) const {
  // Each toolchain should provide the appropriate include flags.
}

void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
                                      ArgStringList &CC1Args) const {
}

void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}

void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
                                 llvm::opt::ArgStringList &CmdArgs) const {
  if (!needsProfileRT(Args)) return;

  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
  return;
}

ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
    const ArgList &Args) const {
  if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
    StringRef Value = A->getValue();
    if (Value == "compiler-rt")
      return ToolChain::RLT_CompilerRT;
    if (Value == "libgcc")
      return ToolChain::RLT_Libgcc;
    getDriver().Diag(diag::err_drv_invalid_rtlib_name)
      << A->getAsString(Args);
  }

  return GetDefaultRuntimeLibType();
}

ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
    StringRef Value = A->getValue();
    if (Value == "libc++")
      return ToolChain::CST_Libcxx;
    if (Value == "libstdc++")
      return ToolChain::CST_Libstdcxx;
    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
      << A->getAsString(Args);
  }

  return ToolChain::CST_Libstdcxx;
}

/// \brief Utility function to add a system include directory to CC1 arguments.
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
                                            ArgStringList &CC1Args,
                                            const Twine &Path) {
  CC1Args.push_back("-internal-isystem");
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
}

/// \brief Utility function to add a system include directory with extern "C"
/// semantics to CC1 arguments.
///
/// Note that this should be used rarely, and only for directories that
/// historically and for legacy reasons are treated as having implicit extern
/// "C" semantics. These semantics are *ignored* by and large today, but its
/// important to preserve the preprocessor changes resulting from the
/// classification.
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
                                                   ArgStringList &CC1Args,
                                                   const Twine &Path) {
  CC1Args.push_back("-internal-externc-isystem");
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
}

void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
                                                ArgStringList &CC1Args,
                                                const Twine &Path) {
  if (llvm::sys::fs::exists(Path))
    addExternCSystemInclude(DriverArgs, CC1Args, Path);
}

/// \brief Utility function to add a list of system include directories to CC1.
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
                                             ArgStringList &CC1Args,
                                             ArrayRef<StringRef> Paths) {
  for (StringRef Path : Paths) {
    CC1Args.push_back("-internal-isystem");
    CC1Args.push_back(DriverArgs.MakeArgString(Path));
  }
}

void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
                                             ArgStringList &CC1Args) const {
  // Header search paths should be handled by each of the subclasses.
  // Historically, they have not been, and instead have been handled inside of
  // the CC1-layer frontend. As the logic is hoisted out, this generic function
  // will slowly stop being called.
  //
  // While it is being called, replicate a bit of a hack to propagate the
  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  // header search paths with it. Once all systems are overriding this
  // function, the CC1 flag and this line can be removed.
  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
}

void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
                                    ArgStringList &CmdArgs) const {
  CXXStdlibType Type = GetCXXStdlibType(Args);

  switch (Type) {
  case ToolChain::CST_Libcxx:
    CmdArgs.push_back("-lc++");
    break;

  case ToolChain::CST_Libstdcxx:
    CmdArgs.push_back("-lstdc++");
    break;
  }
}

void ToolChain::AddFilePathLibArgs(const ArgList &Args,
                                   ArgStringList &CmdArgs) const {
  for (const auto &LibPath : getFilePaths())
    if(LibPath.length() > 0)
      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
}

void ToolChain::AddCCKextLibArgs(const ArgList &Args,
                                 ArgStringList &CmdArgs) const {
  CmdArgs.push_back("-lcc_kext");
}

bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
                                              ArgStringList &CmdArgs) const {
  // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
  // (to keep the linker options consistent with gcc and clang itself).
  if (!isOptimizationLevelFast(Args)) {
    // Check if -ffast-math or -funsafe-math.
    Arg *A =
        Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
                        options::OPT_funsafe_math_optimizations,
                        options::OPT_fno_unsafe_math_optimizations);

    if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
        A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
      return false;
  }
  // If crtfastmath.o exists add it to the arguments.
  std::string Path = GetFilePath("crtfastmath.o");
  if (Path == "crtfastmath.o") // Not found.
    return false;

  CmdArgs.push_back(Args.MakeArgString(Path));
  return true;
}

SanitizerMask ToolChain::getSupportedSanitizers() const {
  // Return sanitizers which don't require runtime support and are not
  // platform dependent.
  using namespace SanitizerKind;
  SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
                      CFICastStrict | UnsignedIntegerOverflow | LocalBounds;
  if (getTriple().getArch() == llvm::Triple::x86 ||
      getTriple().getArch() == llvm::Triple::x86_64)
    Res |= CFIICall;
  return Res;
}

void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
                                   ArgStringList &CC1Args) const {}


text:
using System.Text.Json;
using Azure.Communication.MediaComposition;
using Azure.Core;

namespace Azure.Communication.MediaComposition.Models
{
    public partial class LayoutLayer : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("zIndex");
            writer.WriteNumberValue(ZIndex);
            if (Optional.IsDefined(Visibility))
            {
                writer.WritePropertyName("visibility");
                writer.WriteStringValue(Visibility.Value.ToString());
            }
            writer.WriteEndObject();
        }

        internal static LayoutLayer DeserializeLayoutLayer(JsonElement element)
        {
            int zIndex = default;
            Optional<LayerVisibility> visibility = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("zIndex"))
                {
                    zIndex = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("visibility"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    visibility = new LayerVisibility(property.Value.GetString());
                    continue;
                }
            }
            return new LayoutLayer(zIndex, Optional.ToNullable(visibility));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
HDC hDC;
HGLRC openGLRC;
RECT clientRect;

//OpenGL
GLuint vertexBuf = 0;
GLuint indexBuf = 0;
GLuint texture = 0;
GLuint vShader = 0;
GLuint pShader = 0;
GLuint program = 0;
GLint attributePos = 0;
GLint attributeTexCoord = 0;
GLint uniformViewport = 0;
GLenum err = GL_NO_ERROR;

//image
unsigned char* image;
unsigned width, height;

BOOL CreateOpenGLRenderContext(HWND hWnd);
BOOL InitGLEW();
BOOL InitOpenGL();
void DestroyOpenGL(HWND hWnd);
BOOL Update(HWND hWnd);
void Render(HWND hWnd);
void fnCheckGLError(const char* szFile, int nLine);
#define _CheckGLError_ fnCheckGLError(__FILE__,__LINE__);

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int __stdcall WinMain(__in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd)
{
	BOOL bResult = FALSE;

	MSG msg = { 0 };
	WNDCLASS wc = { 0 };
	wc.lpfnWndProc = WndProc;
	wc.hInstance = hInstance;
	wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
	wc.lpszClassName = L"Opengl330TemplateWindowClass";
	wc.style = CS_OWNDC;
	if (!RegisterClass(&wc))
		return 1;
	HWND hWnd = CreateWindowW(wc.lpszClassName, L"Opengl 3.3 Template", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 640, 480, 0, 0, hInstance, 0);

	ShowWindow(hWnd, nShowCmd);
	UpdateWindow(hWnd);

	bResult = CreateOpenGLRenderContext(hWnd);
	if (bResult == FALSE)
	{
		OutputDebugStringA("CreateOpenGLRenderContext failed!\n");
		return 1;
	}
	InitGLEW();
	InitOpenGL();

	while (true)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0)
		{
			if (msg.message == WM_QUIT)
			{
				break;
			}
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			Update(hWnd);
			Render(hWnd);
		}
	}

	return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_DESTROY:
		DestroyOpenGL(hWnd);
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

BOOL InitGLEW()
{
	char buffer[128];
	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		sprintf(buffer, "Error: %s\n", (char*)glewGetErrorString(err));
		OutputDebugStringA(buffer);
		return FALSE;
	}
	sprintf(buffer, "Status: Using GLEW %s\n", (char*)glewGetString(GLEW_VERSION));
	OutputDebugStringA(buffer);
	return TRUE;
}

BOOL CreateOpenGLRenderContext(HWND hWnd)
{
	BOOL bResult;
	char buffer[128];
	PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),  //  size of this pfd
		1,                     // version number
		PFD_DRAW_TO_WINDOW |   // support window
		PFD_SUPPORT_OPENGL |   // support OpenGL
		PFD_DOUBLEBUFFER,      // double buffered
		PFD_TYPE_RGBA,         // RGBA type
		32,                    // 32-bit color depth
		0, 0, 0, 0, 0, 0,      // color bits ignored
		0,                     // no alpha buffer
		0,                     // shift bit ignored
		0,                     // no accumulation buffer
		0, 0, 0, 0,            // accum bits ignored
		24,                    // 24-bit z-buffer
		8,                     // no stencil buffer
		0,                     // no auxiliary buffer
		PFD_MAIN_PLANE,        // main layer
		0,                     // reserved
		0, 0, 0                // layer masks ignored
	};

	hDC = GetDC(hWnd);
	if (hDC == NULL)
	{
		OutputDebugStringA("Error: GetDC Failed!\n");
		return FALSE;
	}

	int pixelFormatIndex;
	pixelFormatIndex = ChoosePixelFormat(hDC, &pfd);
	if (pixelFormatIndex == 0)
	{
		sprintf(buffer, "Error %d: ChoosePixelFormat Failed!\n", GetLastError());
		OutputDebugStringA(buffer);
		return FALSE;
	}
	bResult = SetPixelFormat(hDC, pixelFormatIndex, &pfd);
	if (bResult == FALSE)
	{
		OutputDebugStringA("SetPixelFormat Failed!\n");
		return FALSE;
	}

	openGLRC = wglCreateContext(hDC);
	if (openGLRC == NULL)
	{
		sprintf(buffer, "Error %d: wglCreateContext Failed!\n", GetLastError());
		OutputDebugStringA(buffer);
		return FALSE;
	}
	bResult = wglMakeCurrent(hDC, openGLRC);
	if (bResult == FALSE)
	{
		sprintf(buffer, "Error %d: wglMakeCurrent Failed!\n", GetLastError());
		OutputDebugStringA(buffer);
		return FALSE;
	}

	sprintf(buffer, "OpenGL version info: %s\n", (char*)glGetString(GL_VERSION));
	OutputDebugStringA(buffer);
	return TRUE;
}

void fnCheckGLError(const char* szFile, int nLine)
{
	GLenum ErrCode = glGetError();
	if (GL_NO_ERROR != ErrCode)
	{
		const char* szErr = "GL_UNKNOWN ERROR";
		switch (ErrCode)
		{
		case GL_INVALID_ENUM:		szErr = "GL_INVALID_ENUM		";		break;
		case GL_INVALID_VALUE:		szErr = "GL_INVALID_VALUE		";		break;
		case GL_INVALID_OPERATION:	szErr = "GL_INVALID_OPERATION	";		break;
		case GL_OUT_OF_MEMORY:		szErr = "GL_OUT_OF_MEMORY		";		break;
		}
		char buffer[512];
		sprintf(buffer, "%s(%d):glError %s\n", szFile, nLine, szErr);
		OutputDebugStringA(buffer);
	}
}

BOOL InitOpenGL()
{
	GLint compiled;
	//Vertex shader
	const char* vShaderStr = R"(
#version 330 core
in vec4 in_Position;
in vec2 in_TexCoord;
out vec2 TexCoord;
void main()
{
	gl_Position = in_Position;
	TexCoord = in_TexCoord;
}
)";
	vShader = glCreateShader(GL_VERTEX_SHADER);
	if (vShader == 0)
	{
		OutputDebugString(L"glCreateShader Failed!\n");
		return -1;
	}
	glShaderSource(vShader, 1, &vShaderStr, nullptr);
	glCompileShader(vShader);
	glGetShaderiv(vShader, GL_COMPILE_STATUS, &compiled);
	if (!compiled)
	{
		GLint infoLength = 0;
		glGetShaderiv(vShader, GL_INFO_LOG_LENGTH, &infoLength);
		if (infoLength > 1)
		{
			char* infoLog = (char*)malloc(sizeof(char)*infoLength);
			glGetShaderInfoLog(vShader, infoLength, nullptr, infoLog);
			OutputDebugString(L"Error compiling vertex shader: \n");
			OutputDebugStringA(infoLog);
			OutputDebugStringA("\n");
			free(infoLog);
		}
		glDeleteShader(vShader);
		return -1;
	}

	//Fragment shader
	const char* pShaderStr = R"(
#version 330 core
uniform sampler2D mysampler;
in vec2 TexCoord;
out vec4 out_Color;
void main()
{
	vec2 st = TexCoord.st;
	out_Color = texture2D(mysampler,vec2(st.s, 1- st.t));
}
)";
	pShader = glCreateShader(GL_FRAGMENT_SHADER);
	if (vShader == 0)
	{
		OutputDebugString(L"glCreateShader Failed!\n");
		return FALSE;
	}
	glShaderSource(pShader, 1, &pShaderStr, nullptr);
	glCompileShader(pShader);
	glGetShaderiv(pShader, GL_COMPILE_STATUS, &compiled);
	if (!compiled)
	{
		GLint infoLength = 0;
		glGetShaderiv(pShader, GL_INFO_LOG_LENGTH, &infoLength);
		if (infoLength > 1)
		{
			char* infoLog = (char*)malloc(sizeof(char)*infoLength);
			glGetShaderInfoLog(pShader, infoLength, NULL, infoLog);
			OutputDebugString(L"Error compiling fragment shader: \n");
			OutputDebugStringA(infoLog);
			OutputDebugStringA("\n");
			free(infoLog);
		}
		glDeleteShader(pShader);
		return FALSE;
	}

	//Program
	GLint linked;
	program = glCreateProgram();
	if (program == 0)
	{
		OutputDebugString(L"glCreateProgram Failed!\n");
		return -1;
	}
	glAttachShader(program, vShader);
	glAttachShader(program, pShader);
	glLinkProgram(program);
	glGetProgramiv(program, GL_LINK_STATUS, &linked);
	if (!linked)
	{
		GLint infoLength = 0;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLength);
		if (infoLength > 1)
		{
			char* infoLog = (char*)malloc(sizeof(char) * infoLength);
			glGetProgramInfoLog(program, infoLength, nullptr, infoLog);
			OutputDebugString(L"Error Linking program: \n");
			OutputDebugStringA(infoLog);
			OutputDebugStringA("\n");
			free(infoLog);
		}
		glDeleteProgram(program);
		return FALSE;
	}
	glUseProgram(program);

	//get attribute and uniform location by name
	attributePos = glGetAttribLocation(program, "in_Position");//get location of attribute <in_Position>
	attributeTexCoord = glGetAttribLocation(program, "in_TexCoord");//get location of attribute <in_TexCoord>

	//vertex buffer
	GLfloat vertex[] =
	{
		-1, -1, 0,	0,0,
		-1, 1, 0,	0,1,
		1, 1, 0,	1,1,
		1, -1, 0,	1,0
	};
	glGenBuffers(1, &vertexBuf);
	assert(vertexBuf != 0);
	glBindBuffer(GL_ARRAY_BUFFER, vertexBuf);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), (GLvoid*)vertex, GL_STATIC_DRAW);

	//set attribute of positon and texcoord
	glVertexAttribPointer(attributePos, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);
	glVertexAttribPointer(attributeTexCoord, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
	//enable attribute array
	glEnableVertexAttribArray(attributePos);
	glEnableVertexAttribArray(attributeTexCoord);

	//texture
	unsigned error;

	error = lodepng_decode32_file(&image, &width, &height, "CheckerMap.png");
	if (error)
	{
		char buf[128];
		sprintf(buf, "error %u: %s\n", error, lodepng_error_text(error));
		OutputDebugStringA(buf);
	}

	glActiveTexture(GL_TEXTURE0);
	glEnable(GL_TEXTURE_2D);

	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
	free(image);

	//sampler settings
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	//other settings
	glClearColor(0.0f, 0.0f, 0.9f, 1.0f);
	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);
	glCullFace(GL_BACK);

	return TRUE;
}

void DestroyOpenGL(HWND hWnd)
{
	//OpenGL Destroy
	glDeleteShader(vShader);
	glDeleteShader(pShader);
	glDeleteProgram(program);

	//OpenGL Context Destroy
	wglMakeCurrent(NULL, NULL);
	wglDeleteContext(openGLRC);
	ReleaseDC(hWnd, hDC);
}

BOOL Update(HWND hWnd)
{
	RECT newClientRect;
	// Set viewport according to the client rect
	if (!GetClientRect(hWnd, &newClientRect))
	{
		OutputDebugString(L"GetClientRect Failed!\n");
		return FALSE;
	}
	if (newClientRect.left != clientRect.left
		|| newClientRect.top != clientRect.top
		|| newClientRect.right != clientRect.right
		|| newClientRect.bottom != clientRect.bottom)
	{
		clientRect = newClientRect;
		glViewport(0, 0, GLsizei(clientRect.right - clientRect.left), GLsizei(clientRect.bottom - clientRect.top));
	}
	return TRUE;
}

void Render(HWND hWnd)
{
	_CheckGLError_

	//Clear
	glClear(GL_COLOR_BUFFER_BIT);

	// Bind the VBO
	glBindBuffer(GL_ARRAY_BUFFER, vertexBuf);

	glBindTexture(GL_TEXTURE_2D, texture);

	//Draw two trangles
	glDrawArrays(GL_TRIANGLE_FAN, 0, 6);

	SwapBuffers(hDC);
}


text:
package voyager.quickstart.location.autonomy;

import java.io.InputStream;
import java.io.StringReader;
import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;

import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.s9api.Axis;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmSequenceIterator;

import org.apache.commons.io.IOUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import voyager.api.discovery.jobs.JobSubmitter;
import voyager.api.domain.model.entry.Entry;
import voyager.api.domain.model.entry.EntryMeta;
import voyager.api.error.DiscoveryError;
import voyager.discovery.location.BaseDiscoveryRunner;
import voyager.common.http.VoyagerHttpClient;
import voyager.common.http.VoyagerHttpException;
import voyager.common.http.VoyagerHttpRequest;
import voyager.quickstart.location.autonomy.bean.AutnHit;
import voyager.quickstart.location.autonomy.bean.AutnResponseData;
import voyager.quickstart.location.autonomy.util.*;

import com.google.common.base.Function;
import com.google.common.base.Throwables;

public class AutonomyRunner extends BaseDiscoveryRunner<AutonomyLocation> {

  static final Logger log = LoggerFactory.getLogger(AutonomyRunner.class);

  final AutonomyXMLReader reader;
  final XmlHttpParser parser;

  public AutonomyRunner( AutonomyLocation loc, SolrClient solr, JobSubmitter jobs) {
    super(loc, solr, jobs);

    AutonomyXMLReader r = null;
    try {
      r = new AutonomyXMLReader();
    }
    catch(SaxonApiException x) {
      Throwables.propagate(x);
    }

    reader = r;
    parser = new XmlHttpParser(reader.builder) {
      @Override
      public XmlHttpResponse parse(VoyagerHttpRequest req, InputStream input, String contentType, String encoding) throws VoyagerHttpException {
        XmlHttpResponse rsp = new XmlHttpResponse();
        try {
          // HACK HACK HACK!
          // we are just fixing the XML so it has an autonomy response
          // hopefully a real service advertises real headers
          String xml = IOUtils.toString(input);
          xml = xml.replaceFirst("<autnresponse>", "<autnresponse xmlns:autn=\"http://schemas.autonomy.com/aci/\">");
          rsp.doc = builder.build(new StreamSource(new StringReader(xml)));
        }
        catch (Exception e) {
          throw new VoyagerHttpException( req, "Error reading stram", e );
        }
        return rsp;
      }
    };
  }

  //----------------------------------------------------
  //----------------------------------------------------

  @Override
  protected void doCrawl() throws Exception {
    URI uri = location.getURI();
    if(uri==null) {
      throw new IllegalArgumentException("Missing URI");
    }

    setProcessedCount(0);

    VoyagerHttpRequest req = new VoyagerHttpRequest("https://voyagerdemo.com/Autonomy");
    req.params = new ModifiableSolrParams();

    final AtomicInteger count = new AtomicInteger(0);
    int start = 1;
    while(!isStopRequested()) {
      req.params.set("Start", start);
      req.params.set("MaxResults", start+location.getPageSize());
      req.params.set("predict", Boolean.FALSE);
      count.set(0);

      XdmNode doc = parser.parse(req, VoyagerHttpClient.getInstance()).doc;

      final AutnHit hit = new AutnHit();
      AutnResponseData d = reader.readResponse(doc, new Function<XdmNode, Void>() {
        @Override
        public Void apply(XdmNode node) {
          incrProcessedCount(1);

          hit.reset();
          count.incrementAndGet();
          XdmNode content = reader.fillHitContent(hit, node);
          try {
            addDoc( toEntry(hit, content) );
          }
          catch(Exception ex) {
            addError(new DiscoveryError("error adding hit", ex));
          }
          return null;
        }
      });
      setItemsToProcess(d.totalhits);

      if(count.get()==0) { // no results returned
        break;
      }

      start += location.getPageSize(); // or count.size?
      if(start>=d.totalhits) {
        break;
      }
    }
  }

  public Entry toEntry(AutnHit hit, XdmNode content) {
    if(hit.id==null) {
      throw new IllegalArgumentException("Autonomy result is missing an id");
    }
    Entry entry = new Entry(hit.title);
    entry.setId(location.getIdForPath(hit.id));
    SolrInputDocument doc = entry.getFields();
    doc.setField("id_autn", hit.id);
    doc.setField("meta_autn_database", hit.database);
    doc.setField("meta_autn_reference", hit.reference);
    doc.setField("meta_autn_links", hit.links);

    if(content!=null) {
      XdmSequenceIterator iter = content.axisIterator(Axis.CHILD);
      if(iter.hasNext()) {
        XdmNode node = (XdmNode)iter.next();
        // TODO -- run xpath queries here?  It is already parsed!
        EntryMeta meta = new EntryMeta();
        meta.setBody(node.toString()); // the raw XML
        entry.setMeta(meta);
      }
      if(iter.hasNext()) {
        entry.addWarning("multiple content sections", content.toString());
      }
    }
    return entry;
  }
}


text:
<?php namespace RainLab\Blog\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class CreatePostsContentHtml extends Migration
{

    public function up()
    {
        Schema::table('rainlab_blog_posts', function($table)
        {
            $table->text('content_html')->nullable();
        });
    }

    public function down()
    {
        Schema::table('rainlab_blog_posts', function($table)
        {
            $table->dropColumn('content_html');
        });
    }
}


text:
package org.openqa.selenium.javascript;

import com.google.common.base.Stopwatch;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;

import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;

import static org.junit.jupiter.api.Assertions.fail;
import static org.openqa.selenium.testing.TestUtilities.isOnTravis;

public class ClosureTestStatement {

  private static final Logger LOG = Logger.getLogger(ClosureTestStatement.class.getName());

  private final Supplier<WebDriver> driverSupplier;
  private final String testPath;
  private final Function<String, URL> filePathToUrlFn;
  private final long timeoutSeconds;

  public ClosureTestStatement(
    Supplier<WebDriver> driverSupplier,
    String testPath,
    Function<String, URL> filePathToUrlFn,
    long timeoutSeconds) {
    this.driverSupplier = driverSupplier;
    this.testPath = testPath;
    this.filePathToUrlFn = filePathToUrlFn;
    this.timeoutSeconds = Math.max(0, timeoutSeconds);
  }

  public void evaluate() throws Throwable {
    URL testUrl = filePathToUrlFn.apply(testPath);
    LOG.info("Running: " + testUrl);

    Stopwatch stopwatch = Stopwatch.createStarted();

    WebDriver driver = driverSupplier.get();

    if (!isOnTravis()) {
      // Attempt to make the window as big as possible.
      try {
        driver.manage().window().maximize();
      } catch (RuntimeException ignored) {
        // We tried.
      }
    }

    JavascriptExecutor executor = (JavascriptExecutor) driver;
    // Avoid Safari JS leak between tests.
    executor.executeScript("if (window && window.top) window.top.G_testRunner = null");

    try {
      driver.get(testUrl.toString());
    } catch (WebDriverException e) {
      fail("Test failed to load: " + e.getMessage());
    }

    while (!getBoolean(executor, Query.IS_FINISHED)) {
      long elapsedTime = stopwatch.elapsed(TimeUnit.SECONDS);
      if (timeoutSeconds > 0 && elapsedTime > timeoutSeconds) {
        throw new JavaScriptAssertionError("Tests timed out after " + elapsedTime + " s. \nCaptured Errors: " +
          ((JavascriptExecutor) driver).executeScript("return window.errors;")
          + "\nPageSource: " + driver.getPageSource() + "\nScreenshot: " +
          ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64));
      }
      TimeUnit.MILLISECONDS.sleep(100);
    }

    if (!getBoolean(executor, Query.IS_SUCCESS)) {
      String report = getString(executor, Query.GET_REPORT);
      throw new JavaScriptAssertionError(report);
    }
  }

  private boolean getBoolean(JavascriptExecutor executor, Query query) {
    return (Boolean) executor.executeScript(query.script);
  }

  private String getString(JavascriptExecutor executor, Query query) {
    return (String) executor.executeScript(query.script);
  }

  private enum Query {
    IS_FINISHED("return !!tr && tr.isFinished();"),
    IS_SUCCESS("return !!tr && tr.isSuccess();"),
    GET_REPORT("return tr.getReport(true);");

    private final String script;

    Query(String script) {
      this.script = "var tr = window.top.G_testRunner;" + script;
    }
  }
}


text:
---
title: React Testing Recipes
layout: post
published: false
---

A list of recipes to testing your React code

Part of the code and ideas are borrowed from **React Testing Cookbook** series on [egghead.io](https://egghead.io) with awareness of personal choice of tools.

Setup
-----

Install babel 6 preset family

```
npm i babel-preset-es2015 babel-preset-react babel-preset-stage-0 babel-core babel-cli --save-dev
```

Add `.babelrc`

```JSON
{
  "presets": ["es2015", "stage-0", "react"]
}

```

Install testing dependencies

```
$ npm i tape sinon enzyme react-addons-test-utils babel-tape-runner faucet --save-dev
$ npm i react react-dom --save
```
* **tape** - tap-producing test harness for node and browsers
* **enzyme** - JavaScript Testing utilities for React http://airbnb.io/enzyme/
* **react-addons-test-utils** - ReactTestUtils makes it easy to test React components in the testing framework of your choice
* **babel-tape-runner** - Babel + Tape runner for your ESNext code
* **faucet** - human-readable TAP summarizer
* **sinon** - Standalone test spies, stubs and mocks for JavaScript.

Lint your ES6 and React code with [standard](https://github.com/feross/standard) and better test error message with snazzy.

```
$ npm i standard snazzy --save-dev
```
In order to make standard understand your `ES6` code and `JSX` syntax, you may also need to install `babel-eslint` and the following to `package.json`.

```JSON
{
  "standard": {
    "parser": "babel-eslint"
  }
}
```
* **standard** - :star2: JavaScript Standard Style http://standardjs.com
* **snazzy** - Format JavaScript Standard Style as Stylish (i.e. snazzy) output

Add `scripts` to `package.json`

```JSON
{
  "scripts": {
    "lint": "standard src/**/*.js | snazzy",
    "pretest": "npm run lint",
    "test": "babel-tape-runner tests/**/*.test.js | faucet"
  }
}
```

Running test
------------

* You can start lint with `npm run lint`
* Running tests with `npm test`, `lint` is part of the test as we defined in `pretest`.

What to test
----------------

#### Shallow Rendering

> Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components.

Make sure you always import `React` to let the test runner know you have JSX syntax in your code.

```JavaScript
import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'

const DummyComponent = (props) => <div>{props.content}</div>

test('Dummy component', assert => {
  const msg = 'should render dummy content'

  const expected = '<div>dummy content</div>'

  const props = {
    content: 'dummy content'
  }

  const $ = shallow(<DummyComponent {...props} />)
  const output = $.html()

  assert.equal(output, expected, msg)

  assert.end()
}))
```

#### Check a component has certain className

```JavaScript
assert.true($.hasClass('myClassName'), msg)
```

#### Check a DOM node exist

```JavaScript
assert.true($.find('.someDOMNode').length, msg)
```

#### Check a component has child element

```JavaScript
const expected = props.data.length
assert.equal($.find('.childClass').children().length, expected, msg)
```
#### Emulate mouse event

First we prepare a simple React `ListComponent` class, the list item will take a `handleMouseDown` callback function from props.

```JavaScript
// ListComponent
class ListComponent extends React.Component {
  constructor (props) {
    super(props)
  }

  render () {
    const { user, handleMouseDown } = this.props
    return (
      <li onMouseDown={handleMouseDown}>{user.name}</li>
    )
  }
}

export default ListComponent
```

Than we can start to test it.

```JavaScript
import ListComponent from './ListComponent'
import sinon from 'sinon'

// ...

// we spy on the `handleMouseDown` function
const handleMouseDown = sinon.spy()
const props = {
  user: {
    name: 'fraserxu',
    title: 'Frontend Developer'
  },
  handleMouseDown
}
const $ = shallow(<ListComponent {...props} />)
const listItem = $.find('li')

// emulate the `mouseDown` event
listItem.simulate('mouseDown')

// check if the function get called
const actual = handleMouseDown.calledOnce
const expected = true

assert.equal(actual, expected, msg)
assert.end()
```

#### Test custom data-attribute

First we prepare a simple React `ListComponent` class, the list item will have a custom data attribute `data-selected` from props.

```JavaScript
// ListComponent
class ListComponent extends React.Component {
  constructor (props) {
    super(props)
  }

  render () {
    const { user, handleMouseDown, isSelected } = this.props
    return (
      <li onMouseDown={handleMouseDown} data-selected={isSelected}>>{user.name}</li>
    )
  }
}

export default ListComponent
```

This part is a little tricky. As for normal DOM node, we can [access the data attribute](https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes) with `$.node.dataset.isSelected`, I tried to get the data attribute for a while and the only solution I found is `listItemNode.getAttribute('data-selected')`.

```JavaScript
import ListComponent from './ListComponent'

// ...

const noop = () => {}
const props = {
  user: {
    name: 'fraserxu',
    title: 'Frontend Developer'
  },
  handleMouseDown: noop,
  isSelected: true
}
const $ = shallow(<ListComponent {...props} />)
const listItem = $.find('li').node

// here is the trick part
assert.equal(listItemNode.getAttribute('data-selected'), 'true', msg)
assert.end()
```

#### Test JSX equal with `tape-jsx-equals`

Same as [expect-jsx](https://github.com/algolia/expect-jsx), you can use [tape-jsx](https://www.npmjs.com/package/tape-jsx-equals) to test JSX strings.

```
$ npm install --save-dev extend-tape
$ npm install --save-dev tape-jsx-equals
```

```JavaScript
import tape from 'tape'
import addAssertions from 'extend-tape'
import jsxEquals from 'tape-jsx-equals'

const test = addAssertions(tape, {jsxEquals})

assert.jsxEquals(result, <div className='box color-red'></div>)
```

Roadmap
---------

This is just the beginning of this recipes and is quite limited to the bacis of testing React code. I'll add more along working and learning. If you are interestd to contribue or want to know how to test certain code, send a pull request here or open a Github issue.

Happy testing!

Further readings
---------------

* [Why I use Tape Instead of Mocha & So Should You](https://medium.com/javascript-scene/why-i-use-tape-instead-of-mocha-so-should-you-6aa105d8eaf4)
* [A pure component dev starter kit for React.](https://github.com/ericelliott/react-pure-component-starter)

Special thanks to [@ericelliott](https://github.com/ericelliott) for sharing his knowledge and effort to make our life easier writing JavaScript.

### License
MIT


text:
package it.skyhash.git.dungeons;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;

import com.connorlinfoot.actionbarapi.ActionBarAPI;
import com.massivecraft.factions.entity.Faction;
import com.massivecraft.factions.entity.MPlayer;
import com.massivecraft.massivecore.util.IdUtil;

import io.lumine.xikage.mythicmobs.api.bukkit.BukkitAPIHelper;
import io.lumine.xikage.mythicmobs.api.exceptions.InvalidMobTypeException;
import io.lumine.xikage.mythicmobs.mobs.MythicMob;
import net.milkbowl.vault.economy.Economy;

public class ListenerGUI implements Listener {

	public static Economy economy = null;

	@EventHandler
    public void onClick(InventoryClickEvent e)
    {
        if(e.getInventory().equals(DungeonCMD.inv))
        {
            if(e.getCurrentItem() != null && e.getCurrentItem().getType() != null)
            {
                e.setCancelled(true);
                Player p = (Player) e.getWhoClicked();
                if(e.getCurrentItem().hasItemMeta() && e.getCurrentItem().getItemMeta().hasDisplayName())
                {
                    ItemStack is = e.getCurrentItem();
                    if(is.getType() == Material.ARROW)
                    {
                    	e.setCancelled(true);
                    }
                    else if(is.getType() == Material.STAINED_GLASS_PANE)
                    {
                    	e.setCancelled(true);
                    }
                    else if(is.getType() == Material.EMERALD)
                    {
                    	e.setCancelled(true);
                    }
                    else
                    {
                    	e.setCancelled(true);
                    	String s = is.getItemMeta().getDisplayName();
                    	s = s.replace("§a", "");
                    	//Backtrack to the object
                    	Dungeon d = Main.getMap().get(s);
                    	if(d.getGameStatus())
                    	{
                    		p.sendMessage(Utils.logo + "§cThis arena is already in-game!");
                			return;
                    	}
                    	else
                    	{
                        	if(setupEconomy())
                        	{
                        		double ec = economy.getBalance(p);
                        		if(ec < d.getCost())
                        		{
                        			p.sendMessage(Utils.logo + "§cYou don't have enough money!");
                                	p.closeInventory();
                        			return;
                        		}
                        		if(ec >= d.getCost())
                        		{
                        			economy.withdrawPlayer(p, d.getCost());
                        			d.setGameStatus(true);
                        			p.sendMessage(Utils.logo + "§cYour faction will be teleported to " + d.getName() + "!");
                                	p.closeInventory();
                        			teleport(p,d);
                        		}
                        	}
                    	}
                    }
                }
            }
        }
    }

	private boolean setupEconomy() {
		RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
        if (economyProvider != null) {
            economy = economyProvider.getProvider();
        }

        return (economy != null);
	}

	public void teleport(Player p,Dungeon d)
	{
		MPlayer mplayer = MPlayer.get(IdUtil.getId(p.getName()));
		World w = d.getWorld();
		//Get faction object
		Faction f = mplayer.getFaction();
		for(MPlayer mp : f.getMPlayers())
		{
			if(mp.isOnline())
			{
				if(mp.getPlayer().getWorld().equals(w))
				{
					mp.getPlayer().sendMessage(Utils.logo + "§dYou will be teleported to §b"+d.getName()+" §din §b5 §dseconds.");
					d.getLastLoc().put(mp.getPlayer(), mp.getPlayer().getLocation());
					d.addPlayerToList(mp.getPlayer());
					DungeonManager.addDungeon(mp.getPlayer(), d);
				}
			}
		}
		Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInstance(), new Runnable()
        {
          public void run()
          {
        	for(Player z : d.getPlayers())
      		{
      			z.teleport(d.getLocation());
      			z.sendMessage(Utils.logo + "§dYou have been successfully teleported to §b"+d.getName()+"!");
            	bossBar(z,d);
      		}
  			spawnMobs(d.getLocation(),d);
  			d.startTimer();
          }
        }, 100);
	}

	public void spawnMobs(Location loc,Dungeon d)
	{
		BukkitAPIHelper api = new BukkitAPIHelper();
		try {
			for(String s : d.getMobs())
			{
				MythicMob mob = api.getMythicMob(s);
				api.spawnMythicMob(s, loc);
				DungeonManager.getDungMobs().put(mob.getDisplayName(), d);
				DungeonManager.test.add(s);
				d.increaseMobsAlive();
			}
		} catch (InvalidMobTypeException e) {

		}
	}

	public void bossBar(Player p,Dungeon d)
	{

		Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), new Runnable() {
			public void run() {
				if(DungeonManager.getDungeons().containsKey(p))
				{
					ActionBarAPI.sendActionBar(p, "§aTime left in arena§9: §b"+ Utils.convert(d.getTime()));
				}
			}
		}, 0L, 100L); //Repeating it every second
	}

	@EventHandler
	public void onJoin(PlayerDeathEvent e)
	{
		if(!(e.getEntity() instanceof Player))
		{
			return;
		}
		Player p = e.getEntity();
		if(DungeonManager.getDungeons().containsKey(p))
		{
			Dungeon d = DungeonManager.getDungeon(p);
			d.getPlayers().remove(p);
			DungeonManager.getDungeons().remove(p);
			p.sendMessage(Utils.logo+"§cYou died! You will get teleported back to this world spawn!");
			p.teleport(p.getWorld().getSpawnLocation());
		}
	}

	@EventHandler
	public void onMobDeath(EntityDeathEvent e)
	{
		String b = e.getEntity().getCustomName();
		try
		{
			b.length();
		}catch(java.lang.NullPointerException x)
		{
			return;
		}
		String a = e.getEntity().getCustomName();
		char[] c = a.toCharArray();
		for(int i=0;i<a.toCharArray().length;i++)
		{
			if(c[i] == '§')
			{
				c[i] = 'Z';
				c[i+1] = 'J';
			}
			if(c[i] == ' ')
			{
				c[i] = '9';
			}
		}
		String str = "";

		for (Character v : c)
		{
		    str += v.toString();
		}

		String finale = str.replaceAll("ZJ", "");
		String finalee = finale.replaceAll("9", "");

		if(DungeonManager.test.contains(finalee))
		{
			Dungeon d = DungeonManager.getDungeonFromLoc(e.getEntity().getCustomName());
			d.decreaseMobsAlive();
			if(d.getMobsAlive() == 0)
			{
				Utils.dungFinish(d);
			}
		}
	}

}


text:
help ccmatch                                                     (version 1.1)
By Daniel E. Cook {Danielecook@gmail.com}                   www.Danielecook.com
-------------------------------------------------------------------------------
ccmatch

     ccmatch -- Used to randomly match cases and controls
                based on specified criteria. For instance,
                if you wanted to randomly match cases and
                controls based on age, you can use ccmatch
                to specify age as a criterion on which to
                match cases and controls and it will match
                randomly by age. You can use multiple
                variables to match based on multiple
                criteria

     ccmatch creates two variables:

                match_id gives the id of the partner an
                individual has been matched to.

                matched_pair Numbers pairs starting from
                one. Pairs will share the same number in
                this column (see example below).

Syntax

     ccmatch variable_list, cc() id()

          variable_list -- Specify variables you want each pair to share here.

          cc(var) -- Specify the variable you use to identify cases and
          controls. Must be coded 0=controls, 1=cases.

          id(var) -- Specify the variable you to name individuals/observations
          in your dataset.

Example

         match_id       matched_pair   name                     case_control
>           age
         a6             1              a2                       0
>           15
         a2             1              a6                       1
>           15
         a7             2              a4                       0
>           16
         a4             2              a7                       1
>           16
         a8             3              a5                       0
>           17
         a5             3              a8                       1
>           17
         a10            4              a1                       0
>           19
         a1             4              a10                      1
>           19
                        .              a3                       0
>           15
                        .              a9                       1
>           18

     The above output is an example of what match can do. The original data
     (name, case_control, age) is unchanged, except that it has been reordered
     The command used was:

     ccmatch age, id(name) cc(case_control)

     Age was specified following ccmatch to indicate that we wanted to match
     cases/control who are the same age.

     The case/control variable is specified as an option using cc(), and the id
     of each individual is specified using id().

-------------------------------------------------------------------------------
note I use individual in this document but it could be interchanged with the
word 'observation' and meaning would be the same. This program should be used
in cases where each row of your dataset constitutes a single individual.
-------------------------------------------------------------------------------
Last Revised  12/18/12
 Update - 12/18/12
          - Huge performance improvement - works on extremely large datasets no
> w.

 Update - 06/27/12
          - Fixed issue where a maximum of only 1600 individuals could be match
> ed.

 Initial Release - 12/18/11


text:
<TITLE>Review for Star Trek: First Contact (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Star Trek: First Contact (1996)

reviewed by
Yamamoto

[Note that followups are directed to rec.arts.movies.current-films and
rec.arts.movies.startrek.current only, not to rec.arts.sf.movies.  -Moderator]

                        STAR TREK: FIRST CONTACT
                       A film review by Yamamoto
                        Copyright 1996 Yamamoto

Have you noticed that right after you get your clothes back from dry
cleaners, they attract stains?  And only for first week or so.  Then
you never spill anything on the dirty clothes again.  I swear there
must be a conspiracy going on around here.  I bet the dry cleaners
add stain attracting chemicals on your clothes that last about a week
or so.  Of course, if you keep it in the closet, it won't attract dirt until
you first put it on again.

Speaking of conspiracies, STAR TREK: FIRST CONTACT came
out so I had to go check it out.  It's the latest of the Star Trek movie
series.  This time around, the Federation's arch enemy come
knocking on the front door so of course Star Trek: The New
Generation crew must come to the rescue.  And they go through the
trekkie techno babble along the way just to save not only earth but
the whole world as we know it.

No nakkid boobs.  33 bullets.  Ship loads of dead bodies.  32 on the
vomit meter.  No moon shots.  What we got here are:  attack of the
killer borg-fu, drill to the eye-fu, implant-fu, dreams from hell-fu,
attack of killer comet-fu, targetting of non essential area-fu, techno
babble-fu, futile resistance-fu, ankle grab-fu, attack of bullet proof
body-fu, touchy feeling-fu,  tequila shots-fu, bad whisky-fu, and of
course, more techno babble-fu.  Video hall of fame nominations to:
James Cromwell for saying stuff like  "Engage" and to Alice Krige
for saying stuff like "You strive to be imperfect?" and to Brent
Spiner for saying stuff like "You mean sexually?"  Of course to
Gates McFadden for saying stuff like "captain has made his
decision" and to Alfre Woodard for saying stuff like "captain Ahab"
and to Michael Dorn for saying stuff like "it made me sick to my
stomach".  And we can never forget Marina Sirtis for saying stuff
like "This is a primitive society" and to Patrick Stewart for saying
stuff like "I will make them pay!" and to Jonathan Frakes for saying
stuff like "you mean you told him" and to Levar Burton for saying
stuff like "that's funny".  Three and a half stars.  Shaggy Bob says
wicked!

Spoilers -- Another one of the Borg ship heads to earth to assimilate.
Jean Luc is placed out of the loop because the higher up things he's a
liability.  Of course, he proves all the higher ups wrong and saves
the day.   In defeat, escaping Borg ship time travels and attack earth
in the past.  Hmm... didn't Cyberdine System 101 and T1000 try to
do something like that?  Anyhow, the Enterprise and her crew
follows and prevents altering of time line and saves the world from
being conquered by the Borg.  All the cameo by people from the
different series adds flavor to the flick.  But you really do need to
follow the TV series to fully appreciate the little quirks and inside
humor.
If you're waiting for the phone call from Paulina Porizkova, take the
cell phone and go see this movie.  If you follow Star Trek at all, I
doubt I'll even have to say that.

Alien Alert!  Why do politicians like to make people's lives
difficult?  And why do we elect these people who try their darnest to
make our lives miserable?  For example, the another freeway is
coming down but may not be replaced.  Gee, that makes spending
what, extra 40 min on the surface road instead of extra 20 min the
commuters spend now.  And if there were freeway system as it was
furst intended, we would be saving all that time for something more
constructive than sitting in the car, getting aggrivated by the BMW
who just cut you off.  No wonder people go postal.

For wisdom according to Shaggy Bob, hit that reply key now.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
var NonwideningOperation = {
    None: 0,
    Neg: 1,
    Ld: 2,
    ConvNum: 3,

    Count: 4
};

var bools = [false, true];

// Test helper constants and variables
var indent = 0;
var nonwideningOperation = -1;

var minTreeDepth = (53 - 32) >> 1;
var maxTreeDepth = (53 - 32 + 1) << 1;
var midTreeDepth = (minTreeDepth + maxTreeDepth) >> 1;
for(var treeDepth = minTreeDepth;
    treeDepth <= maxTreeDepth;
    treeDepth += treeDepth <= midTreeDepth ? treeDepth - (minTreeDepth - 1) : ((maxTreeDepth - treeDepth) >> 1) + 1) {

    for(var treeBranches = 1; treeBranches <= 8; treeBranches <<= 1) {
        for(var useNegativeNumbersIndex = 0; useNegativeNumbersIndex < bools.length; ++useNegativeNumbersIndex) {
            var useNegativeNumbers = bools[useNegativeNumbersIndex];

            echo("generateAndRun(" + treeDepth + ", " + treeBranches + ", " + useNegativeNumbers + ");");
            generateAndRun(treeDepth, treeBranches, useNegativeNumbers);
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Test helpers

function generateAndRun(treeDepth, treeBranches, useNegativeNumbers) {
    var low_i32 = -0x80000001;
    var high_i32 = 0x7fffffff;
    var ui32 = 0xffffffff;

    var f = "";
    f += echos("(function test() {", 1);
    {
        f += echos("echo(inner(" + toHex(useNegativeNumbers ? low_i32 : high_i32) + "));");
        f += echos("function inner(a) {", 1);
        {
            f += echos("a |= 0;");
            f += echos("var r = 0;");
            buildTree(treeDepth, treeBranches).traverse(function visit(node) {
                nonwideningOperation = (nonwideningOperation + 1) % NonwideningOperation.Count;
                var nodeName = varName(node.number);
                var dst =
                    nonwideningOperation === NonwideningOperation.None || nonwideningOperation === NonwideningOperation.ConvNum
                        ? nodeName
                        : tempName(node.number);
                var parentNodeName = node.parent ? varName(node.parent.number) : "a";
                if(nonwideningOperation === NonwideningOperation.Neg)
                    parentNodeName = "-" + parentNodeName;
                else if(nonwideningOperation === NonwideningOperation.ConvNum)
                    parentNodeName = "+" + parentNodeName;
                var right =
                    node.parent && nonwideningOperation !== NonwideningOperation.Neg && (node.number & 3) === 0
                        ? useNegativeNumbers ? low_i32 : ui32
                        : parentNodeName;
                f += echos("var " + dst + " = " + parentNodeName + " + " + right + " + 1;");
                if(nonwideningOperation === NonwideningOperation.Neg)
                    f += echos("var " + nodeName + " = -" + dst + ";");
                else if(nonwideningOperation === NonwideningOperation.Ld)
                    f += echos("var " + nodeName + " = " + dst + ";");
                if(node.left || node.right)
                    return;
                f += echos("r ^= " + nodeName + ";");
            });
            f += echos("return r;");
        }
        f += echos("}", -1);
    }
    f += echos("});", -1);
    f = f.substring(0, f.length - 1);
    echo(f);
    f = eval(f);
    f();
    echo();

    function buildTree(depth, branches, numberContainer, parent) {
        function TreeNode(number, parent) {
            this.number = number;
            this.parent = parent ? parent : null;
            this.left = null;
            this.right = null;
        }
        TreeNode.prototype.traverse = function (visit) {
            visit(this);
            if(this.left)
                this.left.traverse(visit);
            if(this.right)
                this.right.traverse(visit);
        };

        if(depth <= 0)
            throw new Error("Invalid tree depth");
        if(branches <= 0)
            throw new Error("Invalid number of branches");
        if((branches & branches - 1) !== 0)
            throw new Error("Number of branches must be a power of 2");
        if(!numberContainer)
            numberContainer = [0];
        else if(numberContainer[0] < 0)
            throw new Error("Invalid node number");

        var node = new TreeNode(numberContainer[0]++, parent);
        if(--depth !== 0) {
            var branch = branches !== 1;
            if(branch)
                branches >>= 1;
            node.left = buildTree(depth, branches, numberContainer, node);
            if(branch)
                node.right = buildTree(depth, branches, numberContainer, node);
        }

        return node;
    }

    function varName(number) {
        return "v" + number;
    }

    function tempName(number) {
        return "t" + number;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function toHex(n) {
    if(typeof n !== "number")
        return n;
    return n >= 0 ? "0x" + n.toString(16) : "-0x" + (-n).toString(16);
}

function echos(s, changeIndent) {
    if(changeIndent && changeIndent < 0)
        indent += changeIndent * 4;
    if(s && s !== "") {
        var spaces = "";
        for(var i = 0; i < indent; ++i)
            spaces += " ";
        s = spaces + s + "\n";
    }
    else if(s === "")
        s = "\n";
    else
        s = "";
    if(changeIndent && changeIndent > 0)
        indent += changeIndent * 4;
    return s;
}

function echo() {
    var doEcho;
    if(this.WScript)
        doEcho = function (s) { this.WScript.Echo(s); };
    else if(this.document)
        doEcho = function (s) {
            var div = this.document.createElement("div");
            div.innerText = s;
            this.document.body.appendChild(div);
        };
    else
        doEcho = function (s) { this.print(s); };
    echo = function () {
        var s = "";
        for(var i = 0; i < arguments.length; ++i)
            s += arguments[i];
        doEcho(s);
    };
    echo.apply(this, arguments);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 480 (1898)

#### Original name
Agaricus squamosus Schaeff., 1774

### Remarks
null


text:
#include <math.h>
#include "stat.h"
#include "evlist.h"
#include "evsel.h"
#include "thread_map.h"

void update_stats(struct stats *stats, u64 val)
{
	double delta;

	stats->n++;
	delta = val - stats->mean;
	stats->mean += delta / stats->n;
	stats->M2 += delta*(val - stats->mean);

	if (val > stats->max)
		stats->max = val;

	if (val < stats->min)
		stats->min = val;
}

double avg_stats(struct stats *stats)
{
	return stats->mean;
}

/*
 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
 *
 *       (\Sum n_i^2) - ((\Sum n_i)^2)/n
 * s^2 = -------------------------------
 *                  n - 1
 *
 * http://en.wikipedia.org/wiki/Stddev
 *
 * The std dev of the mean is related to the std dev by:
 *
 *             s
 * s_mean = -------
 *          sqrt(n)
 *
 */
double stddev_stats(struct stats *stats)
{
	double variance, variance_mean;

	if (stats->n < 2)
		return 0.0;

	variance = stats->M2 / (stats->n - 1);
	variance_mean = variance / stats->n;

	return sqrt(variance_mean);
}

double rel_stddev_stats(double stddev, double avg)
{
	double pct = 0.0;

	if (avg)
		pct = 100.0 * stddev/avg;

	return pct;
}

bool __perf_evsel_stat__is(struct perf_evsel *evsel,
			   enum perf_stat_evsel_id id)
{
	struct perf_stat *ps = evsel->priv;

	return ps->id == id;
}

#define ID(id, name) [PERF_STAT_EVSEL_ID__##id] = #name
static const char *id_str[PERF_STAT_EVSEL_ID__MAX] = {
	ID(NONE,		x),
	ID(CYCLES_IN_TX,	cpu/cycles-t/),
	ID(TRANSACTION_START,	cpu/tx-start/),
	ID(ELISION_START,	cpu/el-start/),
	ID(CYCLES_IN_TX_CP,	cpu/cycles-ct/),
};
#undef ID

void perf_stat_evsel_id_init(struct perf_evsel *evsel)
{
	struct perf_stat *ps = evsel->priv;
	int i;

	/* ps->id is 0 hence PERF_STAT_EVSEL_ID__NONE by default */

	for (i = 0; i < PERF_STAT_EVSEL_ID__MAX; i++) {
		if (!strcmp(perf_evsel__name(evsel), id_str[i])) {
			ps->id = i;
			break;
		}
	}
}

void perf_evsel__reset_stat_priv(struct perf_evsel *evsel)
{
	int i;
	struct perf_stat *ps = evsel->priv;

	for (i = 0; i < 3; i++)
		init_stats(&ps->res_stats[i]);

	perf_stat_evsel_id_init(evsel);
}

int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
{
	evsel->priv = zalloc(sizeof(struct perf_stat));
	if (evsel->priv == NULL)
		return -ENOMEM;
	perf_evsel__reset_stat_priv(evsel);
	return 0;
}

void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
{
	zfree(&evsel->priv);
}

int perf_evsel__alloc_prev_raw_counts(struct perf_evsel *evsel,
				      int ncpus, int nthreads)
{
	struct perf_counts *counts;

	counts = perf_counts__new(ncpus, nthreads);
	if (counts)
		evsel->prev_raw_counts = counts;

	return counts ? 0 : -ENOMEM;
}

void perf_evsel__free_prev_raw_counts(struct perf_evsel *evsel)
{
	perf_counts__delete(evsel->prev_raw_counts);
	evsel->prev_raw_counts = NULL;
}

int perf_evsel__alloc_stats(struct perf_evsel *evsel, bool alloc_raw)
{
	int ncpus = perf_evsel__nr_cpus(evsel);
	int nthreads = thread_map__nr(evsel->threads);

	if (perf_evsel__alloc_stat_priv(evsel) < 0 ||
	    perf_evsel__alloc_counts(evsel, ncpus, nthreads) < 0 ||
	    (alloc_raw && perf_evsel__alloc_prev_raw_counts(evsel, ncpus, nthreads) < 0))
		return -ENOMEM;

	return 0;
}

int perf_evlist__alloc_stats(struct perf_evlist *evlist, bool alloc_raw)
{
	struct perf_evsel *evsel;

	evlist__for_each(evlist, evsel) {
		if (perf_evsel__alloc_stats(evsel, alloc_raw))
			goto out_free;
	}

	return 0;

out_free:
	perf_evlist__free_stats(evlist);
	return -1;
}

void perf_evlist__free_stats(struct perf_evlist *evlist)
{
	struct perf_evsel *evsel;

	evlist__for_each(evlist, evsel) {
		perf_evsel__free_stat_priv(evsel);
		perf_evsel__free_counts(evsel);
		perf_evsel__free_prev_raw_counts(evsel);
	}
}

void perf_evlist__reset_stats(struct perf_evlist *evlist)
{
	struct perf_evsel *evsel;

	evlist__for_each(evlist, evsel) {
		perf_evsel__reset_stat_priv(evsel);
		perf_evsel__reset_counts(evsel);
	}
}

static void zero_per_pkg(struct perf_evsel *counter)
{
	if (counter->per_pkg_mask)
		memset(counter->per_pkg_mask, 0, MAX_NR_CPUS);
}

static int check_per_pkg(struct perf_evsel *counter,
			 struct perf_counts_values *vals, int cpu, bool *skip)
{
	unsigned long *mask = counter->per_pkg_mask;
	struct cpu_map *cpus = perf_evsel__cpus(counter);
	int s;

	*skip = false;

	if (!counter->per_pkg)
		return 0;

	if (cpu_map__empty(cpus))
		return 0;

	if (!mask) {
		mask = zalloc(MAX_NR_CPUS);
		if (!mask)
			return -ENOMEM;

		counter->per_pkg_mask = mask;
	}

	/*
	 * we do not consider an event that has not run as a good
	 * instance to mark a package as used (skip=1). Otherwise
	 * we may run into a situation where the first CPU in a package
	 * is not running anything, yet the second is, and this function
	 * would mark the package as used after the first CPU and would
	 * not read the values from the second CPU.
	 */
	if (!(vals->run && vals->ena))
		return 0;

	s = cpu_map__get_socket(cpus, cpu);
	if (s < 0)
		return -1;

	*skip = test_and_set_bit(s, mask) == 1;
	return 0;
}

static int
process_counter_values(struct perf_stat_config *config, struct perf_evsel *evsel,
		       int cpu, int thread,
		       struct perf_counts_values *count)
{
	struct perf_counts_values *aggr = &evsel->counts->aggr;
	static struct perf_counts_values zero;
	bool skip = false;

	if (check_per_pkg(evsel, count, cpu, &skip)) {
		pr_err("failed to read per-pkg counter\n");
		return -1;
	}

	if (skip)
		count = &zero;

	switch (config->aggr_mode) {
	case AGGR_THREAD:
	case AGGR_CORE:
	case AGGR_SOCKET:
	case AGGR_NONE:
		if (!evsel->snapshot)
			perf_evsel__compute_deltas(evsel, cpu, thread, count);
		perf_counts_values__scale(count, config->scale, NULL);
		if (config->aggr_mode == AGGR_NONE)
			perf_stat__update_shadow_stats(evsel, count->values, cpu);
		break;
	case AGGR_GLOBAL:
		aggr->val += count->val;
		if (config->scale) {
			aggr->ena += count->ena;
			aggr->run += count->run;
		}
	default:
		break;
	}

	return 0;
}

static int process_counter_maps(struct perf_stat_config *config,
				struct perf_evsel *counter)
{
	int nthreads = thread_map__nr(counter->threads);
	int ncpus = perf_evsel__nr_cpus(counter);
	int cpu, thread;

	if (counter->system_wide)
		nthreads = 1;

	for (thread = 0; thread < nthreads; thread++) {
		for (cpu = 0; cpu < ncpus; cpu++) {
			if (process_counter_values(config, counter, cpu, thread,
						   perf_counts(counter->counts, cpu, thread)))
				return -1;
		}
	}

	return 0;
}

int perf_stat_process_counter(struct perf_stat_config *config,
			      struct perf_evsel *counter)
{
	struct perf_counts_values *aggr = &counter->counts->aggr;
	struct perf_stat *ps = counter->priv;
	u64 *count = counter->counts->aggr.values;
	int i, ret;

	aggr->val = aggr->ena = aggr->run = 0;
	init_stats(ps->res_stats);

	if (counter->per_pkg)
		zero_per_pkg(counter);

	ret = process_counter_maps(config, counter);
	if (ret)
		return ret;

	if (config->aggr_mode != AGGR_GLOBAL)
		return 0;

	if (!counter->snapshot)
		perf_evsel__compute_deltas(counter, -1, -1, aggr);
	perf_counts_values__scale(aggr, config->scale, &counter->counts->scaled);

	for (i = 0; i < 3; i++)
		update_stats(&ps->res_stats[i], count[i]);

	if (verbose) {
		fprintf(config->output, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
			perf_evsel__name(counter), count[0], count[1], count[2]);
	}

	/*
	 * Save the full runtime - to allow normalization during printout:
	 */
	perf_stat__update_shadow_stats(counter, count, 0);

	return 0;
}


text:
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
    Microsoft.NetCore.Analyzers.Runtime.DoNotLockOnObjectsWithWeakIdentityAnalyzer,
    Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
    Microsoft.NetCore.Analyzers.Runtime.DoNotLockOnObjectsWithWeakIdentityAnalyzer,
    Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;

namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
    public class DoNotLockOnObjectsWithWeakIdentityTests
    {
        [Fact]
        public async Task CA2002TestLockOnStrongType()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
            using System;
            public class SomeClass {
                public void Test() {
                    object o = new object();
                    lock (o) {
                        Console.WriteLine();
                    }
                }
            }
");
            await VerifyVB.VerifyAnalyzerAsync(@"
            Imports System
            Public Class SomeClass
                Public Sub Test()
                    Dim o As new Object()
                    SyncLock o
                        Console.WriteLine()
                    End SyncLock
                End Sub
            End Class
");
        }

        [Fact]
        public async Task CA2002TestLockOnWeakIdentities()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
            using System;
            public class SomeClass
            {
                public void Test()
                {
                    string s1 = """";
                    lock (s1) { }
                    lock (""Hello"") { }

                    var o1 = new OutOfMemoryException();
                    lock (o1) { }
                    var o2 = new StackOverflowException();
                    lock (o2) { }
                    var o3 = new ExecutionEngineException();
                    lock (o3) { }

                    lock (System.Threading.Thread.CurrentThread) { }

                    lock (typeof(SomeClass)) { }

                    System.Reflection.MemberInfo mi = null;
                    lock (mi) { }

                    System.Reflection.ConstructorInfo ci = null;
                    lock (ci) { }

                    System.Reflection.ParameterInfo pi = null;
                    lock (pi) { }

                    int[] values = { 1, 2, 3 };
                    lock (values) { }

                    System.Reflection.MemberInfo[] values1 = null;
                    lock (values1) { }

                    lock (this) { }
                }
            }
            ",
            GetCSharpResultAt(8, 27, "string"),
            GetCSharpResultAt(9, 27, "string"),
            GetCSharpResultAt(12, 27, "System.OutOfMemoryException"),
            GetCSharpResultAt(14, 27, "System.StackOverflowException"),
            GetCSharpResultAt(16, 27, "System.ExecutionEngineException"),
            GetCSharpResultAt(18, 27, "System.Threading.Thread"),
            GetCSharpResultAt(20, 27, "System.Type"),
            GetCSharpResultAt(23, 27, "System.Reflection.MemberInfo"),
            GetCSharpResultAt(26, 27, "System.Reflection.ConstructorInfo"),
            GetCSharpResultAt(29, 27, "System.Reflection.ParameterInfo"),
            GetCSharpResultAt(32, 27, "int[]"),
            GetCSharpResultAt(37, 27, "this"));

            await VerifyVB.VerifyAnalyzerAsync(@"
            Imports System
            Public Class SomeClass
                Public Sub Test()
                    Dim s1 As String = """"
                    SyncLock s1
                    End SyncLock
                    SyncLock (""Hello"")
                    End SyncLock

                    Dim o1 = New OutOfMemoryException()
                    SyncLock o1
                    End SyncLock
                    Dim o2 = New StackOverflowException()
                    SyncLock o2
                    End SyncLock
                    Dim o3 = New ExecutionEngineException()
                    SyncLock o3
                    End SyncLock

                    SyncLock System.Threading.Thread.CurrentThread
                    End SyncLock

                    SyncLock GetType(SomeClass)
                    End SyncLock

                    Dim mi As System.Reflection.MemberInfo = Nothing
                    SyncLock mi
                    End SyncLock

                    Dim ci As System.Reflection.ConstructorInfo = Nothing
                    SyncLock ci
                    End SyncLock

                    Dim pi As System.Reflection.ParameterInfo = Nothing
                    SyncLock pi
                    End SyncLock

                    Dim values As Integer() = { 1, 2, 3}
                    SyncLock values
                    End SyncLock

                    Dim values1 As System.Reflection.MemberInfo() = Nothing
                    SyncLock values1
                    End SyncLock

                    SyncLock Me
                    End SyncLock
                End Sub
            End Class",
            GetBasicResultAt(6, 30, "String"),
            GetBasicResultAt(8, 30, "String"),
            GetBasicResultAt(12, 30, "System.OutOfMemoryException"),
            GetBasicResultAt(15, 30, "System.StackOverflowException"),
            GetBasicResultAt(18, 30, "System.ExecutionEngineException"),
            GetBasicResultAt(21, 30, "System.Threading.Thread"),
            GetBasicResultAt(24, 30, "System.Type"),
            GetBasicResultAt(28, 30, "System.Reflection.MemberInfo"),
            GetBasicResultAt(32, 30, "System.Reflection.ConstructorInfo"),
            GetBasicResultAt(36, 30, "System.Reflection.ParameterInfo"),
            GetBasicResultAt(40, 30, "Integer()"),
            GetBasicResultAt(47, 30, "Me"));
        }

        [Fact]
        public async Task CA2002TestLockOnWeakIdentitiesWithScope()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
            using System;
            public class SomeClass
            {
                public void Test()
                {
                    string s1 = """";
                    lock ([|s1|]) { }
                    lock ([|""Hello""|]) { }

                    var o1 = new OutOfMemoryException();
                    lock ([|o1|]) { }
                    var o2 = new StackOverflowException();
                    lock ([|o2|]) { }
                    var o3 = new ExecutionEngineException();
                    lock ([|o3|]) { }

                    lock ([|System.Threading.Thread.CurrentThread|]) { }

                    lock ([|typeof(SomeClass)|]) { }

                    System.Reflection.MemberInfo mi = null;
                    lock ([|mi|]) { }

                    System.Reflection.ConstructorInfo ci = null;
                    lock ([|ci|]) { }

                    System.Reflection.ParameterInfo pi = null;
                    lock ([|pi|]) { }

                    int[] values = { 1, 2, 3 };
                    lock ([|values|]) { }

                    System.Reflection.MemberInfo[] values1 = null;
                    lock (values1) { }
                }
            }");

            await VerifyVB.VerifyAnalyzerAsync(@"
            Imports System
            Public Class SomeClass
                Public Sub Test()
                    Dim s1 As String = """"
                    SyncLock [|s1|]
                    End SyncLock
                    SyncLock [|(""Hello"")|]
                    End SyncLock

                    Dim o1 = New OutOfMemoryException()
                    SyncLock [|o1|]
                    End SyncLock
                    Dim o2 = New StackOverflowException()
                    SyncLock [|o2|]
                    End SyncLock
                    Dim o3 = New ExecutionEngineException()
                    SyncLock [|o3|]
                    End SyncLock

                    SyncLock [|System.Threading.Thread.CurrentThread|]
                    End SyncLock

                    SyncLock [|GetType (SomeClass)|]
                    End SyncLock

                    Dim mi As System.Reflection.MemberInfo = Nothing
                    SyncLock [|mi|]
                    End SyncLock

                    Dim ci As System.Reflection.ConstructorInfo = Nothing
                    SyncLock [|ci|]
                    End SyncLock

                    Dim pi As System.Reflection.ParameterInfo = Nothing
                    SyncLock [|pi|]
                    End SyncLock

                    Dim values As Integer() = { 1, 2, 3}
                    SyncLock [|values|]
                    End SyncLock

                    Dim values1 As System.Reflection.MemberInfo() = Nothing
                    SyncLock values1
                    End SyncLock
                End Sub
            End Class");
        }

        [Fact]
        [WorkItem(2744, "https://github.com/dotnet/roslyn-analyzers/issues/2744")]
        public async Task CA2002_MonitorEnter_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.Threading;

public class C
{
    public void SomeMethod()
    {
        Monitor.Enter(this);
        Monitor.Enter(""test1"");

        bool b = true;
        Monitor.Enter(this, ref b);
        Monitor.Enter(""test1"", ref b);
    }
}",
                GetCSharpResultAt(8, 23, "C"),
                GetCSharpResultAt(9, 23, "C"),
                GetCSharpResultAt(12, 23, "C"),
                GetCSharpResultAt(13, 23, "C"));

            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Threading

Public Class C
    Public Sub SomeMethod()
        Monitor.Enter(Me)
        Monitor.Enter(""test1"")

        Dim b As Boolean = True
        Monitor.Enter(Me, b)
        Monitor.Enter(""test1"", b)
    End Sub
End Class
",
                GetBasicResultAt(6, 23, "C"),
                GetBasicResultAt(7, 23, "C"),
                GetBasicResultAt(10, 23, "C"),
                GetBasicResultAt(11, 23, "C"));
        }

        [Fact]
        [WorkItem(2744, "https://github.com/dotnet/roslyn-analyzers/issues/2744")]
        public async Task CA2002_MonitorTryEnter_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Threading;

public class C
{
    public void SomeMethod()
    {
        Monitor.TryEnter(this);
        Monitor.TryEnter(""test1"");

        Monitor.TryEnter(this, 42);
        Monitor.TryEnter(""test1"", 42);

        Monitor.TryEnter(this, TimeSpan.FromMilliseconds(42));
        Monitor.TryEnter(""test1"", TimeSpan.FromMilliseconds(42));

        bool b = true;
        Monitor.TryEnter(this, ref b);
        Monitor.TryEnter(""test1"", ref b);

        Monitor.TryEnter(this, 42, ref b);
        Monitor.TryEnter(""test1"", 42, ref b);
    }
}",
                GetCSharpResultAt(9, 26, "C"),
                GetCSharpResultAt(10, 26, "C"),
                GetCSharpResultAt(12, 26, "C"),
                GetCSharpResultAt(13, 26, "C"),
                GetCSharpResultAt(15, 26, "C"),
                GetCSharpResultAt(16, 26, "C"),
                GetCSharpResultAt(19, 26, "C"),
                GetCSharpResultAt(20, 26, "C"),
                GetCSharpResultAt(22, 26, "C"),
                GetCSharpResultAt(23, 26, "C"));

            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Threading

Public Class C
    Public Sub SomeMethod()
        Monitor.TryEnter(Me)
        Monitor.TryEnter(""test1"")

        Monitor.TryEnter(Me, 42)
        Monitor.TryEnter(""test1"", 42)

        Monitor.TryEnter(Me, TimeSpan.FromMilliseconds(42))
        Monitor.TryEnter(""test1"", TimeSpan.FromMilliseconds(42))

        Dim b As Boolean = True
        Monitor.TryEnter(Me, b)
        Monitor.TryEnter(""test1"", b)

        Monitor.TryEnter(Me, 42, b)
        Monitor.TryEnter(""test1"", 42, b)
    End Sub
End Class
",
                GetBasicResultAt(7, 26, "C"),
                GetBasicResultAt(8, 26, "C"),
                GetBasicResultAt(10, 26, "C"),
                GetBasicResultAt(11, 26, "C"),
                GetBasicResultAt(13, 26, "C"),
                GetBasicResultAt(14, 26, "C"),
                GetBasicResultAt(17, 26, "C"),
                GetBasicResultAt(18, 26, "C"),
                GetBasicResultAt(20, 26, "C"),
                GetBasicResultAt(21, 26, "C"));
        }

        private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
            => VerifyCS.Diagnostic()
                .WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
                .WithArguments(arguments);

        private static DiagnosticResult GetBasicResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
            => VerifyVB.Diagnostic()
                .WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
                .WithArguments(arguments);
    }
}


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

package com.azure.resourcemanager.avs.generated;

import com.azure.core.util.Context;

/** Samples for PrivateClouds Delete. */
public final class PrivateCloudsDeleteSamples {
    /*
     * x-ms-original-file: specification/vmware/resource-manager/Microsoft.AVS/stable/2022-05-01/examples/PrivateClouds_Delete.json
     */
    /**
     * Sample code: PrivateClouds_Delete.
     *
     * @param manager Entry point to AvsManager.
     */
    public static void privateCloudsDelete(com.azure.resourcemanager.avs.AvsManager manager) {
        manager.privateClouds().delete("group1", "cloud1", Context.NONE);
    }
}