text:
using namespace llvm;
using namespace object;
using namespace llvm::support::endian;

static const char *const Magic = "!<arch>\n";
static const char *const ThinMagic = "!<thin>\n";

void Archive::anchor() { }

StringRef ArchiveMemberHeader::getName() const {
  char EndCond;
  if (Name[0] == '/' || Name[0] == '#')
    EndCond = ' ';
  else
    EndCond = '/';
  llvm::StringRef::size_type end =
      llvm::StringRef(Name, sizeof(Name)).find(EndCond);
  if (end == llvm::StringRef::npos)
    end = sizeof(Name);
  assert(end <= sizeof(Name) && end > 0);
  // Don't include the EndCond if there is one.
  return llvm::StringRef(Name, end);
}

uint32_t ArchiveMemberHeader::getSize() const {
  uint32_t Ret;
  if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
    llvm_unreachable("Size is not a decimal number.");
  return Ret;
}

sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
  unsigned Ret;
  if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
    llvm_unreachable("Access mode is not an octal number.");
  return static_cast<sys::fs::perms>(Ret);
}

sys::TimeValue ArchiveMemberHeader::getLastModified() const {
  unsigned Seconds;
  if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
          .getAsInteger(10, Seconds))
    llvm_unreachable("Last modified time not a decimal number.");

  sys::TimeValue Ret;
  Ret.fromEpochTime(Seconds);
  return Ret;
}

unsigned ArchiveMemberHeader::getUID() const {
  unsigned Ret;
  if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
    llvm_unreachable("UID time not a decimal number.");
  return Ret;
}

unsigned ArchiveMemberHeader::getGID() const {
  unsigned Ret;
  if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
    llvm_unreachable("GID time not a decimal number.");
  return Ret;
}

Archive::Child::Child(const Archive *Parent, const char *Start)
    : Parent(Parent) {
  if (!Start)
    return;

  const ArchiveMemberHeader *Header =
      reinterpret_cast<const ArchiveMemberHeader *>(Start);
  uint64_t Size = sizeof(ArchiveMemberHeader);
  if (!Parent->IsThin || Header->getName() == "/" || Header->getName() == "//")
    Size += Header->getSize();
  Data = StringRef(Start, Size);

  // Setup StartOfFile and PaddingBytes.
  StartOfFile = sizeof(ArchiveMemberHeader);
  // Don't include attached name.
  StringRef Name = Header->getName();
  if (Name.startswith("#1/")) {
    uint64_t NameSize;
    if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
      llvm_unreachable("Long name length is not an integer");
    StartOfFile += NameSize;
  }
}

uint64_t Archive::Child::getSize() const {
  if (Parent->IsThin)
    return getHeader()->getSize();
  return Data.size() - StartOfFile;
}

uint64_t Archive::Child::getRawSize() const {
  return getHeader()->getSize();
}

Archive::Child Archive::Child::getNext() const {
  size_t SpaceToSkip = Data.size();
  // If it's odd, add 1 to make it even.
  if (SpaceToSkip & 1)
    ++SpaceToSkip;

  const char *NextLoc = Data.data() + SpaceToSkip;

  // Check to see if this is past the end of the archive.
  if (NextLoc >= Parent->Data.getBufferEnd())
    return Child(Parent, nullptr);

  return Child(Parent, NextLoc);
}

uint64_t Archive::Child::getChildOffset() const {
  const char *a = Parent->Data.getBuffer().data();
  const char *c = Data.data();
  uint64_t offset = c - a;
  return offset;
}

ErrorOr<StringRef> Archive::Child::getName() const {
  StringRef name = getRawName();
  // Check if it's a special name.
  if (name[0] == '/') {
    if (name.size() == 1) // Linker member.
      return name;
    if (name.size() == 2 && name[1] == '/') // String table.
      return name;
    // It's a long name.
    // Get the offset.
    std::size_t offset;
    if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
      llvm_unreachable("Long name offset is not an integer");
    const char *addr = Parent->StringTable->Data.begin()
                       + sizeof(ArchiveMemberHeader)
                       + offset;
    // Verify it.
    if (Parent->StringTable == Parent->child_end()
        || addr < (Parent->StringTable->Data.begin()
                   + sizeof(ArchiveMemberHeader))
        || addr > (Parent->StringTable->Data.begin()
                   + sizeof(ArchiveMemberHeader)
                   + Parent->StringTable->getSize()))
      return object_error::parse_failed;

    // GNU long file names end with a /.
    if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
      StringRef::size_type End = StringRef(addr).find('/');
      return StringRef(addr, End);
    }
    return StringRef(addr);
  } else if (name.startswith("#1/")) {
    uint64_t name_size;
    if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
      llvm_unreachable("Long name length is not an ingeter");
    return Data.substr(sizeof(ArchiveMemberHeader), name_size)
        .rtrim(StringRef("\0", 1));
  }
  // It's a simple name.
  if (name[name.size() - 1] == '/')
    return name.substr(0, name.size() - 1);
  return name;
}

ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
  ErrorOr<StringRef> NameOrErr = getName();
  if (std::error_code EC = NameOrErr.getError())
    return EC;
  StringRef Name = NameOrErr.get();
  return MemoryBufferRef(getBuffer(), Name);
}

ErrorOr<std::unique_ptr<Binary>>
Archive::Child::getAsBinary(LLVMContext *Context) const {
  ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
  if (std::error_code EC = BuffOrErr.getError())
    return EC;

  return createBinary(BuffOrErr.get(), Context);
}

ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
  std::error_code EC;
  std::unique_ptr<Archive> Ret(new Archive(Source, EC));
  if (EC)
    return EC;
  return std::move(Ret);
}

Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
    : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()) {
  StringRef Buffer = Data.getBuffer();
  // Check for sufficient magic.
  if (Buffer.startswith(ThinMagic)) {
    IsThin = true;
  } else if (Buffer.startswith(Magic)) {
    IsThin = false;
  } else {
    ec = object_error::invalid_file_type;
    return;
  }

  // Get the special members.
  child_iterator i = child_begin(false);
  child_iterator e = child_end();

  if (i == e) {
    ec = object_error::success;
    return;
  }

  StringRef Name = i->getRawName();

  // Below is the pattern that is used to figure out the archive format
  // GNU archive format
  //  First member : / (may exist, if it exists, points to the symbol table )
  //  Second member : // (may exist, if it exists, points to the string table)
  //  Note : The string table is used if the filename exceeds 15 characters
  // BSD archive format
  //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
  //  There is no string table, if the filename exceeds 15 characters or has a
  //  embedded space, the filename has #1/<size>, The size represents the size
  //  of the filename that needs to be read after the archive header
  // COFF archive format
  //  First member : /
  //  Second member : / (provides a directory of symbols)
  //  Third member : // (may exist, if it exists, contains the string table)
  //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
  //  even if the string table is empty. However, lib.exe does not in fact
  //  seem to create the third member if there's no member whose filename
  //  exceeds 15 characters. So the third member is optional.

  if (Name == "__.SYMDEF") {
    Format = K_BSD;
    SymbolTable = i;
    ++i;
    FirstRegular = i;
    ec = object_error::success;
    return;
  }

  if (Name.startswith("#1/")) {
    Format = K_BSD;
    // We know this is BSD, so getName will work since there is no string table.
    ErrorOr<StringRef> NameOrErr = i->getName();
    ec = NameOrErr.getError();
    if (ec)
      return;
    Name = NameOrErr.get();
    if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
      SymbolTable = i;
      ++i;
    }
    FirstRegular = i;
    return;
  }

  // MIPS 64-bit ELF archives use a special format of a symbol table.
  // This format is marked by `ar_name` field equals to "/SYM64/".
  // For detailed description see page 96 in the following document:
  // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf

  bool has64SymTable = false;
  if (Name == "/" || Name == "/SYM64/") {
    SymbolTable = i;
    if (Name == "/SYM64/")
      has64SymTable = true;

    ++i;
    if (i == e) {
      ec = object_error::parse_failed;
      return;
    }
    Name = i->getRawName();
  }

  if (Name == "//") {
    Format = has64SymTable ? K_MIPS64 : K_GNU;
    StringTable = i;
    ++i;
    FirstRegular = i;
    ec = object_error::success;
    return;
  }

  if (Name[0] != '/') {
    Format = has64SymTable ? K_MIPS64 : K_GNU;
    FirstRegular = i;
    ec = object_error::success;
    return;
  }

  if (Name != "/") {
    ec = object_error::parse_failed;
    return;
  }

  Format = K_COFF;
  SymbolTable = i;

  ++i;
  if (i == e) {
    FirstRegular = i;
    ec = object_error::success;
    return;
  }

  Name = i->getRawName();

  if (Name == "//") {
    StringTable = i;
    ++i;
  }

  FirstRegular = i;
  ec = object_error::success;
}

Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
  if (Data.getBufferSize() == 8) // empty archive.
    return child_end();

  if (SkipInternal)
    return FirstRegular;

  const char *Loc = Data.getBufferStart() + strlen(Magic);
  Child c(this, Loc);
  return c;
}

Archive::child_iterator Archive::child_end() const {
  return Child(this, nullptr);
}

StringRef Archive::Symbol::getName() const {
  return Parent->SymbolTable->getBuffer().begin() + StringIndex;
}

ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
  const char *Buf = Parent->SymbolTable->getBuffer().begin();
  const char *Offsets = Buf;
  if (Parent->kind() == K_MIPS64)
    Offsets += sizeof(uint64_t);
  else
    Offsets += sizeof(uint32_t);
  uint32_t Offset = 0;
  if (Parent->kind() == K_GNU) {
    Offset = read32be(Offsets + SymbolIndex * 4);
  } else if (Parent->kind() == K_MIPS64) {
    Offset = read64be(Offsets + SymbolIndex * 8);
  } else if (Parent->kind() == K_BSD) {
    // The SymbolIndex is an index into the ranlib structs that start at
    // Offsets (the first uint32_t is the number of bytes of the ranlib
    // structs).  The ranlib structs are a pair of uint32_t's the first
    // being a string table offset and the second being the offset into
    // the archive of the member that defines the symbol.  Which is what
    // is needed here.
    Offset = read32le(Offsets + SymbolIndex * 8 + 4);
  } else {
    // Skip offsets.
    uint32_t MemberCount = read32le(Buf);
    Buf += MemberCount * 4 + 4;

    uint32_t SymbolCount = read32le(Buf);
    if (SymbolIndex >= SymbolCount)
      return object_error::parse_failed;

    // Skip SymbolCount to get to the indices table.
    const char *Indices = Buf + 4;

    // Get the index of the offset in the file member offset table for this
    // symbol.
    uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
    // Subtract 1 since OffsetIndex is 1 based.
    --OffsetIndex;

    if (OffsetIndex >= MemberCount)
      return object_error::parse_failed;

    Offset = read32le(Offsets + OffsetIndex * 4);
  }

  const char *Loc = Parent->getData().begin() + Offset;
  child_iterator Iter(Child(Parent, Loc));
  return Iter;
}

Archive::Symbol Archive::Symbol::getNext() const {
  Symbol t(*this);
  if (Parent->kind() == K_BSD) {
    // t.StringIndex is an offset from the start of the __.SYMDEF or
    // "__.SYMDEF SORTED" member into the string table for the ranlib
    // struct indexed by t.SymbolIndex .  To change t.StringIndex to the
    // offset in the string table for t.SymbolIndex+1 we subtract the
    // its offset from the start of the string table for t.SymbolIndex
    // and add the offset of the string table for t.SymbolIndex+1.

    // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
    // which is the number of bytes of ranlib structs that follow.  The ranlib
    // structs are a pair of uint32_t's the first being a string table offset
    // and the second being the offset into the archive of the member that
    // define the symbol. After that the next uint32_t is the byte count of
    // the string table followed by the string table.
    const char *Buf = Parent->SymbolTable->getBuffer().begin();
    uint32_t RanlibCount = 0;
    RanlibCount = read32le(Buf) / 8;
    // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
    // don't change the t.StringIndex as we don't want to reference a ranlib
    // past RanlibCount.
    if (t.SymbolIndex + 1 < RanlibCount) {
      const char *Ranlibs = Buf + 4;
      uint32_t CurRanStrx = 0;
      uint32_t NextRanStrx = 0;
      CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
      NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
      t.StringIndex -= CurRanStrx;
      t.StringIndex += NextRanStrx;
    }
  } else {
    // Go to one past next null.
    t.StringIndex =
        Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
  }
  ++t.SymbolIndex;
  return t;
}

Archive::symbol_iterator Archive::symbol_begin() const {
  if (!hasSymbolTable())
    return symbol_iterator(Symbol(this, 0, 0));

  const char *buf = SymbolTable->getBuffer().begin();
  if (kind() == K_GNU) {
    uint32_t symbol_count = 0;
    symbol_count = read32be(buf);
    buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
  } else if (kind() == K_MIPS64) {
    uint64_t symbol_count = read64be(buf);
    buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
  } else if (kind() == K_BSD) {
    // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
    // which is the number of bytes of ranlib structs that follow.  The ranlib
    // structs are a pair of uint32_t's the first being a string table offset
    // and the second being the offset into the archive of the member that
    // define the symbol. After that the next uint32_t is the byte count of
    // the string table followed by the string table.
    uint32_t ranlib_count = 0;
    ranlib_count = read32le(buf) / 8;
    const char *ranlibs = buf + 4;
    uint32_t ran_strx = 0;
    ran_strx = read32le(ranlibs);
    buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
    // Skip the byte count of the string table.
    buf += sizeof(uint32_t);
    buf += ran_strx;
  } else {
    uint32_t member_count = 0;
    uint32_t symbol_count = 0;
    member_count = read32le(buf);
    buf += 4 + (member_count * 4); // Skip offsets.
    symbol_count = read32le(buf);
    buf += 4 + (symbol_count * 2); // Skip indices.
  }
  uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
  return symbol_iterator(Symbol(this, 0, string_start_offset));
}

Archive::symbol_iterator Archive::symbol_end() const {
  if (!hasSymbolTable())
    return symbol_iterator(Symbol(this, 0, 0));

  const char *buf = SymbolTable->getBuffer().begin();
  uint32_t symbol_count = 0;
  if (kind() == K_GNU) {
    symbol_count = read32be(buf);
  } else if (kind() == K_MIPS64) {
    symbol_count = read64be(buf);
  } else if (kind() == K_BSD) {
    symbol_count = read32le(buf) / 8;
  } else {
    uint32_t member_count = 0;
    member_count = read32le(buf);
    buf += 4 + (member_count * 4); // Skip offsets.
    symbol_count = read32le(buf);
  }
  return symbol_iterator(Symbol(this, symbol_count, 0));
}

Archive::child_iterator Archive::findSym(StringRef name) const {
  Archive::symbol_iterator bs = symbol_begin();
  Archive::symbol_iterator es = symbol_end();

  for (; bs != es; ++bs) {
    StringRef SymName = bs->getName();
    if (SymName == name) {
      ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
      // FIXME: Should we really eat the error?
      if (ResultOrErr.getError())
        return child_end();
      return ResultOrErr.get();
    }
  }
  return child_end();
}

bool Archive::hasSymbolTable() const {
  return SymbolTable != child_end();
}


text:
source_file "$ALOJA_REPO_PATH/shell/common/common_hive.sh"
set_hive_requires

BENCH_REQUIRED_FILES["hivebench"]="$ALOJA_PUBLIC_HTTP/aplic2/tarballs/hivebench.tar.gz"

#BENCH_REQUIRED_FILES["tpch-hive"]="$ALOJA_PUBLIC_HTTP/aplic2/tarballs/tpch-hive.tar.gz"
[ ! "$BENCH_LIST" ] && BENCH_LIST="datagen aggregation join"

data_location="/hivebench/data"
hivebench_pages="1200" #hivebench default 120000000
hivebench_visits="10000" #hivebench default 1000000000

#[ "$(get_hadoop_major_version)" != "2" ] && die "Hadoop v2 is required for TPCH-hive"

benchmark_suite_config() {

  initialize_hadoop_vars
  prepare_hadoop_config "$NET" "$DISK" "$BENCH_SUITE"
  start_hadoop

  initialize_hive_vars
  prepare_hive_config "$HIVE_SETTINGS_FILE" "$HIVE_SETTINGS_FILE_PATH"
}

# Iterate the specified benchmarks in the suite
benchmark_suite_run() {
  logger "INFO: Running $BENCH_SUITE"

  for bench in $BENCH_LIST ; do

    # Prepare run (in case defined)
    function_call "benchmark_prepare_$bench"

    # Bench Run
    function_call "benchmark_$bench"

    # Validate (eg. teravalidate)
    function_call "benchmark_validate_$bench"

    # Clean-up HDFS space (in case necessary)
    clean_HDFS "$bench_name" "$BENCH_SUITE"

  done

  logger "INFO: DONE executing $BENCH_SUITE"
}

benchmark_suite_save() {
  logger "DEBUG: No specific ${FUNCNAME[0]} defined for $BENCH_SUITE"
}

benchmark_suite_cleanup() {
  clean_hadoop
}

benchmark_datagen() {
  local bench_name="${FUNCNAME[0]##*benchmark_}"
  logger "INFO: Running $bench_name"

  if [ "$DELETE_HDFS" ] ; then
    local jar="$(get_local_apps_path)/hivebench/datatools.jar"
    execute_hadoop_new "$bench_name" "jar $jar HiBench.DataGen -t hive -m $MAX_MAPS -r $MAX_MAPS -b $(dirname "$data_location") -n $(basename "$data_location") -p $hivebench_pages -v $hivebench_visits -o sequence" "time"
  else
    logger "WARNING: Reusing data already generated"
  fi
}

benchmark_prepare_aggregation() {
  local bench_name="${FUNCNAME[0]##*benchmark_}"
  logger "INFO: Running $bench_name"

  local create_tables="
DROP TABLE uservisits;
CREATE EXTERNAL TABLE uservisits (sourceIP STRING,destURL STRING,visitDate STRING,adRevenue DOUBLE,userAgent STRING,countryCode STRING,languageCode STRING,searchWord STRING,duration INT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS SEQUENCEFILE LOCATION '$data_location/uservisits';
DROP TABLE uservisits_aggre;
"

  local local_file_path="$(create_local_file "$bench_name.sql" "$create_tables")"

  logger "DEBUG: Running query:\n$create_tables"
  execute_hive "$bench_name" "-f '$local_file_path'" "time"
}

benchmark_aggregation() {
  local bench_name="${FUNCNAME[0]##*benchmark_}"
  logger "INFO: Running $bench_name"

  local create_tables="
CREATE TABLE uservisits_aggre ( sourceIP STRING, sumAdRevenue DOUBLE) STORED AS SEQUENCEFILE ;
INSERT OVERWRITE TABLE uservisits_aggre SELECT sourceIP, SUM(adRevenue) FROM uservisits GROUP BY sourceIP;
"

  local local_file_path="$(create_local_file "$bench_name.sql" "$create_tables")"

  logger "DEBUG: Running query:\n$create_tables"
  execute_hive "$bench_name" "-f '$local_file_path'" "time"
}

benchmark_prepare_join() {
  local bench_name="${FUNCNAME[0]##*benchmark_}"
  logger "INFO: Running $bench_name"

  local create_tables="
DROP TABLE rankings;
CREATE EXTERNAL TABLE rankings (pageURL STRING, pageRank INT, avgDuration INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS SEQUENCEFILE LOCATION '$data_location/rankings';
DROP TABLE rankings_uservisits_join;
"

  local local_file_path="$(create_local_file "$bench_name.sql" "$create_tables")"

  logger "DEBUG: Running query:\n$create_tables"
  execute_hive "$bench_name" "-f '$local_file_path'" "time"

  #Now create the uservisits copy
  benchmark_uservisits_copy
}

benchmark_uservisits_copy() {
  local bench_name="${FUNCNAME[0]##*benchmark_}"
  logger "INFO: Running $bench_name"

  local create_tables="
DROP TABLE uservisits_copy;
CREATE EXTERNAL TABLE uservisits_copy (sourceIP STRING,destURL STRING,visitDate STRING,adRevenue DOUBLE,userAgent STRING,countryCode STRING,languageCode STRING,searchWord STRING,duration INT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS SEQUENCEFILE LOCATION '$data_location/uservisits';
"

  local local_file_path="$(create_local_file "$bench_name.sql" "$create_tables")"

  logger "DEBUG: Running query:\n$create_tables"
  execute_hive "$bench_name" "-f '$local_file_path'" "time"
}

benchmark_join() {
  local bench_name="${FUNCNAME[0]##*benchmark_}"
  logger "INFO: Running $bench_name"

  local create_tables="
CREATE TABLE rankings_uservisits_join ( sourceIP STRING, avgPageRank DOUBLE, totalRevenue DOUBLE) STORED AS SEQUENCEFILE;
INSERT OVERWRITE TABLE rankings_uservisits_join SELECT sourceIP, avg(pageRank), sum(adRevenue) as totalRevenue FROM rankings R JOIN (SELECT sourceIP, destURL, adRevenue FROM uservisits_copy UV WHERE (datediff(UV.visitDate, '1999-01-01')>=0 AND datediff(UV.visitDate, '2000-01-01')<=0)) NUV ON (R.pageURL = NUV.destURL) group by sourceIP order by totalRevenue DESC limit 1;
"

  local local_file_path="$(create_local_file "$bench_name.sql" "$create_tables")"

  logger "DEBUG: Running query:\n$create_tables"
  execute_hive "$bench_name" "-f '$local_file_path'" "time"
}

redpajama_set_name: RedPajamaGithub


text:
class FixBattleStats < ActiveRecord::Migration
  def up
    remove_column :trainer_pokemons, :battle_status
    add_column :trainer_pokemons, :battle_stats, :string
  end

  def down
    remove_column :trainer_pokemons, :battle_stats
    add_column :trainer_pokemons, :battle_status, :string
  end
end


text:
Dear %NAME%,

You have registered with %SOC_NETWORK%.

Your temporary password now is: %PWD%

You can change this password here.

Sincerely,

The reFigure team.


text:
package libmachine

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/docker/machine/drivers"
	"github.com/docker/machine/utils"
)

type Provider struct {
	store Store
}

func New(store Store) (*Provider, error) {
	return &Provider{
		store: store,
	}, nil
}

func (provider *Provider) Create(name string, driverName string, hostOptions *HostOptions, driverConfig drivers.DriverOptions) (*Host, error) {
	validName := ValidateHostName(name)
	if !validName {
		return nil, ErrInvalidHostname
	}
	exists, err := provider.store.Exists(name)
	if err != nil {
		return nil, err
	}
	if exists {
		return nil, fmt.Errorf("Machine %s already exists", name)
	}

	hostPath := filepath.Join(utils.GetMachineDir(), name)

	host, err := NewHost(name, driverName, hostOptions)
	if err != nil {
		return host, err
	}
	if driverConfig != nil {
		if err := host.Driver.SetConfigFromFlags(driverConfig); err != nil {
			return host, err
		}
	}

	if err := host.Driver.PreCreateCheck(); err != nil {
		return nil, err
	}

	if err := os.MkdirAll(hostPath, 0700); err != nil {
		return nil, err
	}

	if err := host.SaveConfig(); err != nil {
		return host, err
	}

	if err := host.Create(name); err != nil {
		return host, err
	}

	return host, nil
}

func (provider *Provider) Exists(name string) (bool, error) {
	return provider.store.Exists(name)
}

func (provider *Provider) GetActive() (*Host, error) {
	return provider.store.GetActive()
}

func (provider *Provider) List() ([]*Host, error) {
	return provider.store.List()
}

func (provider *Provider) Get(name string) (*Host, error) {
	return provider.store.Get(name)
}

func (provider *Provider) Remove(name string, force bool) error {
	host, err := provider.store.Get(name)
	if err != nil {
		return err
	}
	if err := host.Remove(force); err != nil {
		if !force {
			return err
		}
	}
	return provider.store.Remove(name, force)
}


text:
package org.freshgrade.molr.interfaces;

import com.mongodb.client.MongoDatabase;

import org.bson.Document;
import org.bson.types.ObjectId;

/**
 * Created by ronbierman on 15-10-08.
 */
public interface MongoMigrator {
    /**
     * This will be called in case there's no previous migration run and allows
     * you to do an initial full sync before accepting individual oplog tails
     *
     */
    public void handleFullSync(MongoDatabase mongoClient);

    public void handleInsert(ObjectId objectId, Document document);

    public void handleUpdate(ObjectId objectId, Document document);

    public void handleDelete(ObjectId op);

    public String getCollectionName();
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Model extends CI_Model
{

    /**
     * The database table to use, only set if you want to bypass the magic.
     *
     * @var string
     */
    protected $_table;

    /**
     * The primary key, by default set to `id`, for use in some functions.
     *
     * @var string
     */
    protected $primary_key = 'id';

    /**
     * An array of functions to be called before a record is created.
     *
     * @var array
     */
    protected $before_create = array();

    /**
     * An array of functions to be called after a record is created.
     *
     * @var array
     */
    protected $after_create = array();

    /**
     * An array of validation rules
     *
     * @var array
     */
    protected $validate = array();

    /**
     * Skip the validation
     *
     * @var bool
     */
    protected $skip_validation = false;

    /**
     * The class constructor, tries to guess the table name.
     *
     * @author Jamie Rumbelow
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('inflector');
        $this->_fetch_table();
    }

    /**
     *
     * @todo Provide short description.
     *
     * @param string $method
     * @param array $arguments
     * @return \MY_Model
     * @throws Exception
     */
    public function __call($method, $arguments)
    {
        $db_method = array($this->db, $method);

        if (is_callable($db_method))
        {
            $result = call_user_func_array($db_method, $arguments);

            if (is_object($result) && $result === $this->db)
            {
                return $this;
            }

            return $result;
        }

        throw new Exception("class '".get_class($this)."' does not have a method '".$method."'");
    }

    /**
     * Get table name
     *
     * @param boolean $prefix Whether the table name should be prefixed or not.
     * @return string
     */
    public function table_name($prefix = true)
    {
        return $prefix ? $this->db->dbprefix($this->_table) : $this->_table;
    }

    /**
     * Set table name
     *
     * @param string $name The name for the table.
     * @return string
     */
    public function set_table_name($name = null)
    {
        return $this->_table = $name;
    }

    /**
     * Set table name
     *
     * This method is the same as the set_table_name() method with one difference,
     * it returns the object to allow method chaining.
     *
     * @author  Cosmo Mathieu <cosmo@cosmointeractive.co>
     * @param string $name The name for the table.
     * @return void
     */
    public function table($name = null)
    {
        $this->_table = $name;

        return $this;
    }

    /**
     * Get a single record by creating a WHERE clause with a value for your
     * primary key.
     *
     * @author Phil Sturgeon
     * @param string $id The value of your primary key
     * @return object
     */
    public function get($id)
    {
        return $this->db->where($this->primary_key, $id)
                        ->get($this->_table)
                        ->row();
    }

    /**
     * Get a single record by creating a WHERE clause with the key of $key and
     * the value of $val.
     *
     * @todo What are the ghost parameters this accepts?
     *
     * @author Phil Sturgeon
     * @return object
     */
    public function get_by($key = null, $value = null)
    {
        $where = func_get_args();
        $this->_set_where($where);

        return $this->db->get($this->_table)
                        ->row();
    }

    /**
     * Get many result objects in an array.
     *
     * Similar to get(), but returns a result array of many result objects.
     *
     * @author Phil Sturgeon
     * @param string $primary_value The value of your primary key
     * @return array
     */
    public function get_many($primary_value)
    {
        $this->db->where($this->primary_key, $primary_value);
        return $this->get_all();
    }

    /**
     * Similar to get_by(), but returns a result array of many result objects.
     *
     * The function accepts ghost parameters, fetched via func_get_args().
     * Those are:
     *  1. string `$key` The key to search by.
     *  2. string `$value` The value of that key.
     *
     * They are used in the query in the where statement something like:
     *   [...] WHERE {$key}={$value} [...]
     *
     * @author Phil Sturgeon
     * @return array
     */
    public function get_many_by()
    {
        $where = func_get_args();
        $this->_set_where($where);

        return $this->get_all();
    }

    /**
     * Get all records in the database
     *
     * @author Jamie Rumbelow
     * @return object
     */
    public function get_all()
    {
        return $this->db->get($this->_table)->result();
    }

    /**
     * Similar to get_by(), but returns a result array of many result objects.
     *
     * The function accepts ghost parameters, fetched via func_get_args().
     * Those are:
     *  1. string `$key` The key to search by.
     *  2. string `$value` The value of that key.
     *
     * They are used in the query in the where statement something like:
     *   [...] WHERE {$key}={$value} [...]
     *
     * @author Phil Sturgeon
     * @return array
     */
    public function count_by()
    {
        $where = func_get_args();
        $this->_set_where($where);

        return $this->db->count_all_results($this->_table);
    }

    /**
     * Get all records in the database
     *
     * @author Phil Sturgeon
     * @return array
     */
    public function count_all()
    {
        return $this->db->count_all($this->_table);
    }

    /**
     * Insert a new record into the database, calling the before and after
     * create callbacks.
     *
     * @author Jamie Rumbelow
     * @author Dan Horrigan
     * @param array $data Information
     * @param boolean $skip_validation Whether we should skip the validation of the data.
     * @return integer|true The insert ID
     */
    public function insert($data, $skip_validation = false)
    {
        if ($skip_validation === false)
        {
            if ( ! $this->_run_validation($data))
            {
                return false;
            }
        }

        $data = $this->_run_before_create($data);
        $this->db->insert($this->_table, $data);
        $this->_run_after_create($data, $this->db->insert_id());

        $this->skip_validation = false;

        return $this->db->insert_id();
    }

    /**
     * Insert multiple rows at once.
     *
     * Similar to insert(), just passing an array to insert multiple rows at
     * once.
     *
     * @author Jamie Rumbelow
     * @param array $data Array of arrays to insert
     * @param boolean $skip_validation Whether we should skip the validation of the data.
     * @return array An array of insert IDs.
     */
    public function insert_many($data, $skip_validation = false)
    {
        $ids = array();

        foreach ($data as $row)
        {
            if ($skip_validation === false)
            {
                if ( ! $this->_run_validation($row))
                {
                    $ids[] = false;

                    continue;
                }
            }

            $data = $this->_run_before_create($row);
            $this->db->insert($this->_table, $row);
            $this->_run_after_create($row, $this->db->insert_id());

            $ids[] = $this->db->insert_id();
        }

        $this->skip_validation = false;
        return $ids;
    }

    /**
     * Update a record, specified by an ID.
     *
     * @author Jamie Rumbelow
     * @param integer $primary_value The primary key basically the row's ID.
     * @param array $data The data to update.
     * @param boolean $skip_validation Whether we should skip the validation of the data.
     * @return boolean
     */
    public function update($primary_value, $data, $skip_validation = false)
    {
        if ($skip_validation === false)
        {
            if ( ! $this->_run_validation($data))
            {
                return false;
            }
        }

        $this->skip_validation = false;

        return $this->db->where($this->primary_key, $primary_value)
                        ->set($data)
                        ->update($this->_table);
    }

    /**
     * Update a record, specified by $key and $val.
     *
     * The function accepts ghost parameters, fetched via func_get_args().
     * Those are:
     *  1. string `$key` The key to update with.
     *  2. string `$value` The value to match.
     *  3. array  `$data` The data to update with.
     * The first two are used in the query in the where statement something like:
     *   UPDATE {table} SET {$key}={$data} WHERE {$key}={$value}
     *
     * @author Jamie Rumbelow
     * @return boolean
     */
    public function update_by()
    {
        $args = func_get_args();
        $data = array_pop($args);
        $this->_set_where($args);

        if (!$this->_run_validation($data))
        {
            return false;
        }

        $this->skip_validation = false;

        return $this->db->set($data)
                        ->update($this->_table);
    }

    /**
     * Updates many records, specified by an array of IDs.
     *
     * @author Phil Sturgeon
     * @param array $primary_values The array of IDs
     * @param array $data The data to update
     * @param boolean $skip_validation Whether we should skip the validation of the data.
     * @return boolean
     */
    public function update_many($primary_values, $data, $skip_validation = false)
    {
        if ($skip_validation === false)
        {
            if ( ! $this->_run_validation($data))
            {
                return false;
            }
        }

        $this->skip_validation = false;

        return $this->db->where_in($this->primary_key, $primary_values)
                        ->set($data)
                        ->update($this->_table);
    }

    /**
     * Updates all records
     *
     * @author Phil Sturgeon
     * @param array $data The data to update
     * @return bool
     */
    public function update_all($data)
    {
        return $this->db
                        ->set($data)
                        ->update($this->_table);
    }

    /**
     * Delete a row from the database table by ID.
     *
     * @author Jamie Rumbelow
     * @param integer $id
     * @return bool
     */
    public function delete($id)
    {
        return $this->db->where($this->primary_key, $id)
                        ->delete($this->_table);
    }

    /**
     * Delete a row from the database table by the key and value.
     *
     * @author Phil Sturgeon
     * @return bool
     */
    public function delete_by()
    {
        $where = func_get_args();
        $this->_set_where($where);

        return $this->db->delete($this->_table);
    }

    /**
     * Delete many rows from the database table by an array of IDs passed.
     *
     * @author Phil Sturgeon
     * @param array $primary_values
     * @return bool
     */
    public function delete_many($primary_values)
    {
        return $this->db->where_in($this->primary_key, $primary_values)
                        ->delete($this->_table);
    }

    /**
     * Generate the dropdown options.
     *
     * @return array The options for the dropdown.
     */
    function dropdown()
    {
        $args = func_get_args();

        if (count($args) == 2)
        {
            list($key, $value) = $args;
        }
        else
        {
            $key = $this->primary_key;
            $value = $args[0];
        }

        $query = $this->db->select(array($key, $value))
                ->get($this->_table);

        $options = array();
        foreach ($query->result() as $row)
        {
            $options[$row->{$key}] = $row->{$value};
        }

        return $options;
    }

    /**
     * Orders the result set by the criteria, using the same format as
     * CodeIgniter's AR library.
     *
     * @author Jamie Rumbelow
     * @param string $criteria The criteria to order by
     * @param string $order the order direction
     * @return \MY_Model
     */
    public function order_by($criteria, $order = 'ASC')
    {
        $this->db->order_by($criteria, $order);
        return $this;
    }

    /**
     * Limits the result set.
     *
     * Pass an integer to set the actual result limit.
     * Pass a second integer set the offset.
     *
     * @author Jamie Rumbelow
     * @param int $limit The number of rows
     * @param int $offset The offset
     * @return \MY_Model
     */
    public function limit($limit, $offset = 0)
    {
        $limit = func_get_args();
        $this->_set_limit($limit);
        return $this;
    }

    /**
     * Removes duplicate entries from the result set.
     *
     * @author Phil Sturgeon
     * @return \MY_Model
     */
    public function distinct()
    {
        $this->db->distinct();
        return $this;
    }

    /**
     * Run validation only using the
     * same rules as insert/update will
     *
     * @param array $data
     *
     * @return bool
     */
    public function validate($data)
    {
        return $this->_run_validation($data);
    }

    /**
     * Return only the keys from the validation array
     *
     * @return array
     */
    public function fields()
    {
        $keys = array();

        if ($this->validate)
        {
            foreach ($this->validate as $key)
            {
                $keys[] = $key['field'];
            }
        }

        return $keys;
    }

    /**
     * Runs the before create actions.
     *
     * @author Jamie Rumbelow
     * @param array $data The array of actions
     * @return mixed
     */
    private function _run_before_create($data)
    {
        foreach ($this->before_create as $method)
        {
            $data = call_user_func_array(array($this, $method), array($data));
        }

        return $data;
    }

    /**
     * Runs the after create actions.
     *
     * @author Jamie Rumbelow
     * @param array $data The array of actions
     * @param int $id
     */
    private function _run_after_create($data, $id)
    {
        foreach ($this->after_create as $method)
        {
            call_user_func_array(array($this, $method), array($data, $id));
        }
    }

    /**
     * Runs validation on the passed data.
     *
     * @author Dan Horrigan
     * @author Jerel Unruh
     * @param array $data
     * @return boolean
     */
    private function _run_validation($data)
    {
        if ($this->skip_validation)
        {
            return true;
        }

        if (empty($this->validate))
        {
            return true;
        }

        $this->load->library('form_validation');

        // only set the model if it can be used for callbacks
        if ($class = get_class($this) and $class !== 'MY_Model')
        {
            // make sure their MY_Form_validation is set up for it
            if (method_exists($this->form_validation, 'set_model'))
            {
                $this->form_validation->set_model($class);
            }
        }

        $this->form_validation->set_data($data);

        if (is_array($this->validate))
        {
            $this->form_validation->set_rules($this->validate);
            return $this->form_validation->run();
        }

        return $this->form_validation->run($this->validate);
    }

    /**
     * Fetches the table from the pluralised model name.
     *
     * @author Jamie Rumbelow
     */
    private function _fetch_table()
    {
        if ($this->_table == null)
        {
            $class = preg_replace('/(_m|_model)?$/', '', get_class($this));
            $this->_table = plural(strtolower($class));
        }
    }

    /**
     * Sets where depending on the number of parameters
     *
     * @author Phil Sturgeon
     * @param array $params
     */
    private function _set_where($params)
    {
        if (count($params) == 1)
        {
            $this->db->where($params[0]);
        }
        else
        {
            $this->db->where($params[0], $params[1]);
        }
    }

    /**
     * Sets limit depending on the number of parameters
     *
     * @author Phil Sturgeon
     * @param array $params
     */
    private function _set_limit($params)
    {
        if (count($params) == 1)
        {
            if (is_array($params[0]))
            {
                $this->db->limit($params[0][0], $params[0][1]);
            }
            else
            {
                $this->db->limit($params[0]);
            }
        }
        else
        {
            $this->db->limit((int) $params[0], (int) $params[1]);
        }
    }

}


text:
<!DOCTYPE html>

    <title>DomDiff example</title>
    <meta charset="utf-8" />


text:
{% extends "base_form_delete.html" %}

{% block title %}Delete Skill Tree Branch{% endblock %}

{% block confirm_delete %}
    <p>Are you sure you want to delete {{ skilltreebranch.name }}?
{% endblock %}


text:
package org.xllapp.portal.weixin.service;

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xllapp.portal.weixin.service.WeixinConfigHolder.WeixinConfig;

@Service
public class WxService extends WxMpServiceImpl implements InitializingBean {

	private boolean httpProxySet=false;

	private String httpProxyHost;

	private int httpProxyPort;

	private String httpProxyUserName;

	private String httpProxyPassword;

	private WxMpConfigStorage wxMpConfigStorage;

	@Override
	public void afterPropertiesSet() throws Exception {

		WeixinConfig weixinConfig=WeixinConfigHolder.getWeixinConfig();

		WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();

		config.setAppId(weixinConfig.getAppId());
		config.setSecret(weixinConfig.getAppSecret());
		config.setAesKey(weixinConfig.getAesKey());
		config.setToken(weixinConfig.getToken());

		if(this.httpProxySet){
			config.setHttp_proxy_host(this.httpProxyHost);
			config.setHttp_proxy_port(this.httpProxyPort);
			config.setHttp_proxy_username(this.httpProxyUserName);
			config.setHttp_proxy_password(this.httpProxyPassword);
		}

		this.setWxMpConfigStorage(config);
		this.wxMpConfigStorage = config;

	}

	public WxMpConfigStorage getWxMpConfigStorage() {
		return this.wxMpConfigStorage;
	}

	@Value("${http.proxySet:false}")
	public void setHttpProxySet(boolean httpProxySet) {
		this.httpProxySet = httpProxySet;
	}

	@Value("${http.proxyHost:}")
	public void setHttpProxyHost(String httpProxyHost) {
		this.httpProxyHost = httpProxyHost;
	}

	@Value("${http.proxyPort:0}")
	public void setHttpProxyPort(int httpProxyPort) {
		this.httpProxyPort = httpProxyPort;
	}

	@Value("${http.proxyUserName:}")
	public void setHttpProxyUserName(String httpProxyUserName) {
		this.httpProxyUserName = httpProxyUserName;
	}

	@Value("${http.proxyPassword:}")
	public void setHttpProxyPassword(String httpProxyPassword) {
		this.httpProxyPassword = httpProxyPassword;
	}

}


text:
package org.relib.http.json;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.relib.util.Strings;

/**
 * Handles manipulating object data into JavaScript Object Notation (JSON).
 *
 *

 * {
 * 	@code
 * 	String json = Json.toJson(new Object());
 * }
 *

 *
 *

 * Handles parsing a JSON string into the equivalent request parameter map
 *
 *

 *
 * Map<String, String[]> map = Json.toParameterMap("{}");
 *
 *

 *
 * @author Troy Histed
 */
public class Json {

	private static final Json JSON = new Json();

	/**
	 * Constructs a JSON representation of the specified object in a String.
	 *
	 *

	 * Uses reflection to traverse the object tree.
	 *
	 * @param object
	 *            the object to convert to a json string
	 * @return non-null string containing json
	 */
	public static String toJson(Object object) {
		return JSON.build(object);
	}

	/**
	 * Parses a JSON string into a map of parameters.
	 *
	 * @param json
	 *            string of json data to parse
	 * @return non-null map containing converted json data
	 */
	public static Map<String, String[]> toParameterMap(String json) {
		return JsonToParameterMap.toParameterMap(json);
	}

	/**
	 * Builds the string representation.
	 *
	 * @param object
	 *            the object to build json with
	 * @return string
	 */
	public String build(Object object) {
		if (object == null) {
			return "null";
		} else if (object instanceof String) {
			return "\"" + object + "\"";
		} else if (object instanceof Enum) {
			return "\"" + ((Enum<?>) object).name() + "\"";
		} else if (object instanceof Boolean || object instanceof Number) {
			return object.toString();
		} else if (object instanceof Character) {
			return "\'" + object + "\'";
		} else if (object instanceof Object[]) {
			return this.handleObjectArray((Object[]) object);
		} else if (object instanceof byte[]) {
			return this.handleByteArray((byte[]) object);
		} else if (object instanceof short[]) {
			return this.handleShortArray((short[]) object);
		} else if (object instanceof int[]) {
			return this.handleIntArray((int[]) object);
		} else if (object instanceof long[]) {
			return this.handleLongArray((long[]) object);
		} else if (object instanceof float[]) {
			return this.handleFloatArray((float[]) object);
		} else if (object instanceof double[]) {
			return this.handleDoubleArray((double[]) object);
		} else if (object instanceof boolean[]) {
			return this.handleBooleanArray((boolean[]) object);
		} else if (object instanceof char[]) {
			return this.handleCharArray((char[]) object);
		} else if (object instanceof Date) {
			return this.handleDate((Date) object);
		} else if (object instanceof Calendar) {
			return this.handleCalendar((Calendar) object);
		} else if (object instanceof DynaClass && object instanceof DynaBean) {
			return this.handleDynaBeanClass((DynaClass) object);
		} else {
			return this.handleOtherObject(object);
		}
	}

	/**
	 * Handles generating json from any other object type.
	 *
	 * @param object
	 *            the object to convert
	 * @return string containing json
	 */
	private String handleOtherObject(Object object) {

		final StringBuilder buffer = new StringBuilder();
		buffer.append("{");
		String delimiter = "";

		final Method[] methods = object.getClass().getMethods();
		Arrays.sort(methods, new MethodOrder());
		for (final Method method : methods) {
			final String methodName = method.getName();
			if (method.getParameterTypes().length == 0) {
				String fieldName;
				if (methodName.startsWith("get")) {
					fieldName = Strings.unCapitalize(methodName.substring(3));
				} else if (methodName.startsWith("is")) {
					fieldName = Strings.unCapitalize(methodName.substring(2));
				} else {
					continue;
				}

				if (fieldName.equals("class")) {
					continue;
				}

				buffer.append(delimiter);
				buffer.append("\"").append(fieldName).append("\":");

				Object fieldValue;
				try {
					fieldValue = method.invoke(object);
				} catch (final IllegalAccessException e) {
					continue;
				} catch (final IllegalArgumentException e) {
					continue;
				} catch (final InvocationTargetException e) {
					continue;
				}

				if (object != fieldValue) {
					buffer.append(this.build(fieldValue));
				} else {
					buffer.append("match!");
				}
				delimiter = ", ";
			}
		}

		buffer.append("}");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of Objects.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleObjectArray(Object[] objects) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final Object item : objects) {
			buffer.append(delim).append(this.build(item));
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of bytes.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleByteArray(byte[] bytes) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final byte item : bytes) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of shorts.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleShortArray(short[] shorts) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final short item : shorts) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of ints.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleIntArray(int[] ints) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final int item : ints) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of longs.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleLongArray(long[] longs) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final long item : longs) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of floats.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleFloatArray(float[] floats) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final float item : floats) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of doubles.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleDoubleArray(double[] doubles) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final double item : doubles) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of booleans.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleBooleanArray(boolean[] booleans) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final boolean item : booleans) {
			buffer.append(delim).append(item);
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting an array of chars.
	 *
	 * @param objects
	 *            the objects to convert
	 * @return string containing json
	 */
	private String handleCharArray(char[] chars) {
		final StringBuilder buffer = new StringBuilder("[");
		String delim = "";
		for (final char item : chars) {
			buffer.append(delim).append("'").append(item).append("'");
			delim = ", ";
		}
		buffer.append("]");
		return buffer.toString();
	}

	/**
	 * Handles converting a Date.
	 *
	 * @param date
	 *            the object to convert
	 * @return string containing json
	 */
	private String handleDate(Date date) {
		return String.valueOf(date.getTime());
	}

	/**
	 * Handles converting a Calendar.
	 *
	 * @param calendar
	 *            the object to convert
	 * @return string containing json
	 */
	private String handleCalendar(Calendar calendar) {
		return String.valueOf(calendar.getTimeInMillis());
	}

	/**
	 * Handles the special DynaBean and DynaClass conversion to json.
	 *
	 * @param dynaClass
	 *            the object to convert
	 * @return string containing json
	 */
	private String handleDynaBeanClass(DynaClass dynaClass) {

		final DynaProperty[] dynaProperties = dynaClass.getDynaProperties();

		final StringBuilder buffer = new StringBuilder("{");
		String delim = "";

		if (dynaProperties != null) {
			for (final DynaProperty dynaProperty : dynaProperties) {
				if (dynaProperty != null) {
					final String propertyName = dynaProperty.getName();
					buffer.append(delim).append("\"").append(propertyName).append("\":");
					final String value = this.build(((DynaBean) dynaClass).get(propertyName));
					buffer.append(value);
					delim = ", ";
				}
			}
		}
		buffer.append("}");
		return buffer.toString();
	}

	/**
	 * Defines how to compare methods by using the method name.
	 *
	 * @author Troy Histed
	 */
	private static class MethodOrder implements Comparator<Method>, Serializable {
		public int compare(Method method1, Method method2) {
			return method1.getName().compareTo(method2.getName());
		}
	}

}


text:
( function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} ( function( $ ) {

$.ui = $.ui || {};

return $.ui.version = "1.12.1";

} ) );

( function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} ( function( $ ) {
return $.ui.safeBlur = function( element ) {

	// Support: IE9 - 10 only
	// If the <body> is blurred, IE will switch windows, see #9420
	if ( element && element.nodeName.toLowerCase() !== "body" ) {
		$( element ).trigger( "blur" );
	}
};

} ) );


text:
// Styles
import './VBtn.sass'

// Extensions
import VSheet from '../VSheet'

// Components
import VProgressCircular from '../VProgressCircular'

// Mixins
import { factory as GroupableFactory } from '../../mixins/groupable'
import { factory as ToggleableFactory } from '../../mixins/toggleable'
import Elevatable from '../../mixins/elevatable'
import Positionable from '../../mixins/positionable'
import Routable from '../../mixins/routable'
import Sizeable from '../../mixins/sizeable'

// Utilities
import mixins, { ExtractVue } from '../../util/mixins'
import { breaking } from '../../util/console'

// Types
import { VNode } from 'vue'
import { PropValidator, PropType } from 'vue/types/options'
import { RippleOptions } from '../../directives/ripple'

const baseMixins = mixins(
  VSheet,
  Routable,
  Positionable,
  Sizeable,
  GroupableFactory('btnToggle'),
  ToggleableFactory('inputValue')
  /* @vue/component */
)
interface options extends ExtractVue<typeof baseMixins> {
  $el: HTMLElement
}

export default baseMixins.extend<options>().extend({
  name: 'v-btn',

  props: {
    activeClass: {
      type: String,
      default (): string | undefined {
        if (!this.btnToggle) return ''

        return this.btnToggle.activeClass
      },
    } as any as PropValidator<string>,
    block: Boolean,
    depressed: Boolean,
    fab: Boolean,
    icon: Boolean,
    loading: Boolean,
    outlined: Boolean,
    plain: Boolean,
    retainFocusOnClick: Boolean,
    rounded: Boolean,
    tag: {
      type: String,
      default: 'button',
    },
    text: Boolean,
    tile: Boolean,
    type: {
      type: String,
      default: 'button',
    },
    value: null as any as PropType<any>,
  },

  data: () => ({
    proxyClass: 'v-btn--active',
  }),

  computed: {
    classes (): any {
      return {
        'v-btn': true,
        ...Routable.options.computed.classes.call(this),
        'v-btn--absolute': this.absolute,
        'v-btn--block': this.block,
        'v-btn--bottom': this.bottom,
        'v-btn--disabled': this.disabled,
        'v-btn--is-elevated': this.isElevated,
        'v-btn--fab': this.fab,
        'v-btn--fixed': this.fixed,
        'v-btn--has-bg': this.hasBg,
        'v-btn--icon': this.icon,
        'v-btn--left': this.left,
        'v-btn--loading': this.loading,
        'v-btn--outlined': this.outlined,
        'v-btn--plain': this.plain,
        'v-btn--right': this.right,
        'v-btn--round': this.isRound,
        'v-btn--rounded': this.rounded,
        'v-btn--router': this.to,
        'v-btn--text': this.text,
        'v-btn--tile': this.tile,
        'v-btn--top': this.top,
        ...this.themeClasses,
        ...this.groupClasses,
        ...this.elevationClasses,
        ...this.sizeableClasses,
      }
    },
    computedElevation (): string | number | undefined {
      if (this.disabled) return undefined

      return Elevatable.options.computed.computedElevation.call(this)
    },
    computedRipple (): RippleOptions | boolean {
      const defaultRipple = this.icon || this.fab ? { circle: true } : true
      if (this.disabled) return false
      else return this.ripple ?? defaultRipple
    },
    hasBg (): boolean {
      return !this.text && !this.plain && !this.outlined && !this.icon
    },
    isElevated (): boolean {
      return Boolean(
        !this.icon &&
        !this.text &&
        !this.outlined &&
        !this.depressed &&
        !this.disabled &&
        !this.plain &&
        (this.elevation == null || Number(this.elevation) > 0)
      )
    },
    isRound (): boolean {
      return Boolean(
        this.icon ||
        this.fab
      )
    },
    styles (): object {
      return {
        ...this.measurableStyles,
      }
    },
  },

  created () {
    const breakingProps = [
      ['flat', 'text'],
      ['outline', 'outlined'],
      ['round', 'rounded'],
    ]

    /* istanbul ignore next */
    breakingProps.forEach(([original, replacement]) => {
      if (this.$attrs.hasOwnProperty(original)) breaking(original, replacement, this)
    })
  },

  methods: {
    click (e: MouseEvent): void {
      // TODO: Remove this in v3
      !this.retainFocusOnClick && !this.fab && e.detail && this.$el.blur()
      this.$emit('click', e)

      this.btnToggle && this.toggle()
    },
    genContent (): VNode {
      return this.$createElement('span', {
        staticClass: 'v-btn__content',
      }, this.$slots.default)
    },
    genLoader (): VNode {
      return this.$createElement('span', {
        class: 'v-btn__loader',
      }, this.$slots.loader || [this.$createElement(VProgressCircular, {
        props: {
          indeterminate: true,
          size: 23,
          width: 2,
        },
      })])
    },
  },

  render (h): VNode {
    const children = [
      this.genContent(),
      this.loading && this.genLoader(),
    ]
    const { tag, data } = this.generateRouteLink()
    const setColor = this.hasBg
      ? this.setBackgroundColor
      : this.setTextColor

    if (tag === 'button') {
      data.attrs!.type = this.type
      data.attrs!.disabled = this.disabled
    }
    data.attrs!.value = ['string', 'number'].includes(typeof this.value)
      ? this.value
      : JSON.stringify(this.value)

    return h(tag, this.disabled ? data : setColor(this.color, data), children)
  },
})


text:
goog.module('goog.ui.editor.plugins.LinkDialogTest');
goog.setTestOnly();

const AbstractDialog = goog.require('goog.ui.editor.AbstractDialog');
const BrowserFeature = goog.require('goog.editor.BrowserFeature');
const Command = goog.require('goog.editor.Command');
const DomHelper = goog.require('goog.dom.DomHelper');
const Field = goog.require('goog.editor.Field');
const FieldMock = goog.require('goog.testing.editor.FieldMock');
const Link = goog.require('goog.editor.Link');
const LinkDialog = goog.require('goog.ui.editor.LinkDialog');
const LinkDialogPlugin = goog.require('goog.editor.plugins.LinkDialogPlugin');
const MockControl = goog.require('goog.testing.MockControl');
const NodeType = goog.require('goog.dom.NodeType');
const SafeHtml = goog.require('goog.html.SafeHtml');
const TagName = goog.require('goog.dom.TagName');
const TestHelper = goog.require('goog.testing.editor.TestHelper');
const Unicode = goog.require('goog.string.Unicode');
const dom = goog.require('goog.dom');
const editorDom = goog.require('goog.testing.editor.dom');
const events = goog.require('goog.testing.events');
const googString = goog.require('goog.string');
const mockmatchers = goog.require('goog.testing.mockmatchers');
const testSuite = goog.require('goog.testing.testSuite');
const userAgent = goog.require('goog.userAgent');

let plugin;
let anchorElem;
let extraAnchors;
let isNew;
let testDiv;

let mockCtrl;
let mockField;
let mockLink;
let mockAlert;

const OLD_LINK_TEXT = 'old text';
const OLD_LINK_URL = 'http://old.url/';
const NEW_LINK_TEXT = 'My Link Text';
const NEW_LINK_URL = 'http://my.link/url/';

let fieldElem;
let fieldObj;
let linkObj;

function setUpAnchor(
    text, href, isNew = undefined, target = undefined, rel = undefined) {
  setUpGivenAnchor(anchorElem, text, href, isNew, target, rel);
}

function setUpGivenAnchor(anchor, text, href, opt_isNew, opt_target, opt_rel) {
  anchor.innerHTML = text;
  anchor.href = href;
  isNew = !!opt_isNew;
  if (opt_target) {
    anchor.target = opt_target;
  }
  if (opt_rel) {
    anchor.rel = opt_rel;
  }
}

/**
 * @suppress {missingProperties,checkTypes} suppression added to enable type
 * checking
 */
function verifyRelNoFollow(noFollow, originalRel, expectedRel) {
  mockLink.placeCursorRightOf();
  mockField.dispatchSelectionChangeEvent();
  mockField.dispatchChange();
  mockField.focus();
  mockCtrl.$replayAll();

  plugin = new LinkDialogPlugin();
  plugin.registerFieldObject(mockField);
  plugin.showRelNoFollow();
  /**
   * @suppress {visibility,checkTypes} suppression added to enable type
   * checking
   */
  plugin.currentLink_ = mockLink;

  setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL, true, null, originalRel);
  /** @suppress {visibility} suppression added to enable type checking */
  const dialog = plugin.createDialog(new DomHelper(), mockLink);
  dialog.dispatchEvent(
      new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL, false, noFollow));
  assertEquals(expectedRel, anchorElem.rel);

  mockCtrl.$verifyAll();
}

/**
 * Setup a real editable field (instead of a mock) and register the plugin to
 * it.
 */
function setUpRealEditableField() {
  fieldElem = dom.createElement(TagName.DIV);
  fieldElem.id = 'myField';
  document.body.appendChild(fieldElem);
  fieldElem.appendChild(anchorElem);
  fieldObj = new Field('myField', document);
  fieldObj.makeEditable();
  /** @suppress {checkTypes} suppression added to enable type checking */
  linkObj = new Link(fieldObj.getElement().firstChild, isNew);
  // Register the plugin to that field.
  plugin = new LinkDialogPlugin();
  fieldObj.registerPlugin(plugin);
}

/** Tear down the real editable field. */
function tearDownRealEditableField() {
  if (fieldObj) {
    fieldObj.makeUneditable();
    fieldObj.dispose();
    fieldObj = null;
  }
  dom.removeNode(fieldElem);
}
testSuite({
  /**
     @suppress {missingProperties} suppression added to enable type
     checking
   */
  setUp() {
    testDiv = dom.getDocument().getElementById('test');
    dom.setTextContent(testDiv, 'Some preceding text');

    anchorElem = dom.createElement(TagName.A);
    anchorElem.href = 'http://www.google.com/';
    dom.setTextContent(anchorElem, 'anchor text');
    dom.appendChild(testDiv, anchorElem);
    extraAnchors = [];

    mockCtrl = new MockControl();
    mockField = new FieldMock();
    mockCtrl.addMock(mockField);
    mockLink = mockCtrl.createLooseMock(Link);
    mockAlert = mockCtrl.createGlobalFunctionMock('alert');

    isNew = false;
    mockLink.isNew().$anyTimes().$does(() => isNew);
    mockLink.setTextAndUrl(mockmatchers.isString, mockmatchers.isString)
        .$anyTimes()
        .$does((text, url) => {
          anchorElem.innerHTML = text;
          anchorElem.href = url;
        });
    mockLink.getAnchor().$anyTimes().$returns(anchorElem);
    mockLink.getExtraAnchors().$anyTimes().$returns(extraAnchors);
  },

  tearDown() {
    plugin.dispose();
    tearDownRealEditableField();
    dom.removeChildren(testDiv);
    mockCtrl.$tearDown();
  },

  /**
     Tests that the plugin's dialog is properly created.
     @suppress {checkTypes} suppression added to enable type checking
   */
  testCreateDialog() {
    // Note: this tests simply creating the dialog because that's the only
    // functionality added to this class. Opening or closing effects
    // (editing the actual link) is tested in linkdialog_test.html, but
    // should be moved here if that functionality gets refactored from the
    // dialog to the plugin.
    mockCtrl.$replayAll();

    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);

    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);
    assertTrue(
        'Dialog should be of type goog.ui.editor.LinkDialog',
        dialog instanceof LinkDialog);

    mockCtrl.$verifyAll();
  },

  /**
     Tests that when the OK event fires the link is properly updated.
     @suppress {missingProperties,checkTypes} suppression added to enable
     type checking
   */
  testOk() {
    mockLink.placeCursorRightOf();
    mockField.dispatchSelectionChangeEvent();
    mockField.dispatchChange();
    mockField.focus();
    mockCtrl.$replayAll();

    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL);
    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);
    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);

    // Mock of execCommand + clicking OK without actually opening the
    // dialog.
    /**
     * @suppress {visibility,checkTypes} suppression added to enable type
     * checking
     */
    plugin.currentLink_ = mockLink;
    dialog.dispatchEvent(new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL));

    assertEquals('Display text incorrect', NEW_LINK_TEXT, anchorElem.innerHTML);
    assertEquals(
        'Anchor element href incorrect', NEW_LINK_URL, anchorElem.href);

    mockCtrl.$verifyAll();
  },

  /**
     Tests that when the Cancel event fires the link is unchanged.
     @suppress {checkTypes} suppression added to enable type checking
   */
  testCancel() {
    mockCtrl.$replayAll();

    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL);
    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);
    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);

    // Mock of execCommand + cancel without actually opening the dialog.
    /**
     * @suppress {visibility,checkTypes} suppression added to enable type
     * checking
     */
    plugin.currentLink_ = mockLink;
    dialog.dispatchEvent(AbstractDialog.EventType.CANCEL);

    assertEquals(
        'Display text should not be changed', OLD_LINK_TEXT,
        anchorElem.innerHTML);
    assertEquals(
        'Anchor element href should not be changed', OLD_LINK_URL,
        anchorElem.href);

    mockCtrl.$verifyAll();
  },

  /**
     Tests that when the Cancel event fires for a new link it gets removed.
     @suppress {missingProperties,checkTypes} suppression added to enable
     type checking
   */
  testCancelNew() {
    mockField.dispatchChange();  // Should be fired because link was removed.
    mockCtrl.$replayAll();

    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL, true);
    const prevSib = anchorElem.previousSibling;
    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);
    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);

    // Mock of execCommand + cancel without actually opening the dialog.
    /**
     * @suppress {visibility,checkTypes} suppression added to enable type
     * checking
     */
    plugin.currentLink_ = mockLink;
    dialog.dispatchEvent(AbstractDialog.EventType.CANCEL);

    assertNotEquals(
        'Anchor element should be removed from document body', testDiv,
        anchorElem.parentNode);
    const newElem = prevSib.nextSibling;
    assertEquals(
        'Link should be replaced by text node', NodeType.TEXT,
        newElem.nodeType);
    assertEquals(
        'Original text should be left behind', OLD_LINK_TEXT,
        newElem.nodeValue);

    mockCtrl.$verifyAll();
  },

  /**
     Tests that when the Cancel event fires for a new link it gets removed.
     @suppress {missingProperties,checkTypes} suppression added to enable
     type checking
   */
  testCancelNewMultiple() {
    mockField.dispatchChange();  // Should be fired because link was removed.
    mockCtrl.$replayAll();

    const anchorElem1 = anchorElem;
    const parent1 = dom.createDom(TagName.DIV, null, anchorElem1);
    dom.appendChild(testDiv, parent1);
    setUpGivenAnchor(
        anchorElem1, `${OLD_LINK_TEXT}1`, `${OLD_LINK_URL}1`, true);

    let anchorElem2 = dom.createDom(TagName.A);
    const parent2 = dom.createDom(TagName.DIV, null, anchorElem2);
    dom.appendChild(testDiv, parent2);
    setUpGivenAnchor(
        anchorElem2, `${OLD_LINK_TEXT}2`, `${OLD_LINK_URL}2`, true);
    extraAnchors.push(anchorElem2);

    let anchorElem3 = dom.createDom(TagName.A);
    const parent3 = dom.createDom(TagName.DIV, null, anchorElem3);
    dom.appendChild(testDiv, parent3);
    setUpGivenAnchor(
        anchorElem3, `${OLD_LINK_TEXT}3`, `${OLD_LINK_URL}3`, true);
    extraAnchors.push(anchorElem3);

    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);
    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);

    // Mock of execCommand + cancel without actually opening the dialog.
    /**
     * @suppress {visibility,checkTypes} suppression added to enable type
     * checking
     */
    plugin.currentLink_ = mockLink;
    dialog.dispatchEvent(AbstractDialog.EventType.CANCEL);

    assertNotEquals(
        'Anchor 1 element should be removed from document body', parent1,
        anchorElem1.parentNode);
    assertNotEquals(
        'Anchor 2 element should be removed from document body', parent2,
        anchorElem2.parentNode);
    assertNotEquals(
        'Anchor 3 element should be removed from document body', parent3,
        anchorElem3.parentNode);

    assertEquals(
        'Link 1 should be replaced by text node', NodeType.TEXT,
        parent1.firstChild.nodeType);
    assertEquals(
        'Link 2 should be replaced by text node', NodeType.TEXT,
        parent2.firstChild.nodeType);
    assertEquals(
        'Link 3 should be replaced by text node', NodeType.TEXT,
        parent3.firstChild.nodeType);

    assertEquals(
        'Original text 1 should be left behind', `${OLD_LINK_TEXT}1`,
        parent1.firstChild.nodeValue);
    assertEquals(
        'Original text 2 should be left behind', `${OLD_LINK_TEXT}2`,
        parent2.firstChild.nodeValue);
    assertEquals(
        'Original text 3 should be left behind', `${OLD_LINK_TEXT}3`,
        parent3.firstChild.nodeValue);

    mockCtrl.$verifyAll();
  },

  /**
     Tests that when the Cancel event fires for a new link it gets removed.
     @suppress {missingProperties,checkTypes} suppression added to enable
     type checking
   */
  testOkNewMultiple() {
    mockLink.placeCursorRightOf();
    mockField.dispatchSelectionChangeEvent();
    mockField.dispatchChange();
    mockField.focus();
    mockCtrl.$replayAll();

    const anchorElem1 = anchorElem;
    setUpGivenAnchor(
        anchorElem1, `${OLD_LINK_TEXT}1`, `${OLD_LINK_URL}1`, true);

    let anchorElem2 = dom.createElement(TagName.A);
    dom.appendChild(testDiv, anchorElem2);
    setUpGivenAnchor(
        anchorElem2, `${OLD_LINK_TEXT}2`, `${OLD_LINK_URL}2`, true);
    extraAnchors.push(anchorElem2);

    let anchorElem3 = dom.createElement(TagName.A);
    dom.appendChild(testDiv, anchorElem3);
    setUpGivenAnchor(
        anchorElem3, `${OLD_LINK_TEXT}3`, `${OLD_LINK_URL}3`, true);
    extraAnchors.push(anchorElem3);

    const prevSib = anchorElem1.previousSibling;
    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);
    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);

    // Mock of execCommand + clicking OK without actually opening the
    // dialog.
    /**
     * @suppress {visibility,checkTypes} suppression added to enable type
     * checking
     */
    plugin.currentLink_ = mockLink;
    dialog.dispatchEvent(new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL));

    assertEquals(
        'Display text 1 must update', NEW_LINK_TEXT, anchorElem1.innerHTML);
    assertEquals(
        'Display text 2 must not update', `${OLD_LINK_TEXT}2`,
        anchorElem2.innerHTML);
    assertEquals(
        'Display text 3 must not update', `${OLD_LINK_TEXT}3`,
        anchorElem3.innerHTML);

    assertEquals(
        'Anchor element 1 href must update', NEW_LINK_URL, anchorElem1.href);
    assertEquals(
        'Anchor element 2 href must update', NEW_LINK_URL, anchorElem2.href);
    assertEquals(
        'Anchor element 3 href must update', NEW_LINK_URL, anchorElem3.href);

    mockCtrl.$verifyAll();
  },

  /**
   * Tests the anchor's target is correctly modified with the "open in new
   * window" feature on.
   * @suppress {missingProperties,checkTypes} suppression added to enable
   * type checking
   */
  testOkOpenInNewWindow() {
    mockLink.placeCursorRightOf().$anyTimes();
    mockField.dispatchSelectionChangeEvent().$anyTimes();
    mockField.dispatchChange().$anyTimes();
    mockField.focus().$anyTimes();
    mockCtrl.$replayAll();

    plugin = new LinkDialogPlugin();
    plugin.registerFieldObject(mockField);
    plugin.showOpenLinkInNewWindow(false);
    /**
     * @suppress {visibility,checkTypes} suppression added to enable type
     * checking
     */
    plugin.currentLink_ = mockLink;

    // Edit a link that doesn't open in a new window and leave it as such.
    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL);
    /** @suppress {visibility} suppression added to enable type checking */
    let dialog = plugin.createDialog(new DomHelper(), mockLink);
    dialog.dispatchEvent(
        new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL, false, false));
    assertEquals(
        'Target should not be set for link that doesn\'t open in new window',
        '', anchorElem.target);
    assertFalse(
        'Checked state should stay false',
        plugin.getOpenLinkInNewWindowCheckedState());

    // Edit a link that doesn't open in a new window and toggle it on.
    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL);
    /** @suppress {visibility} suppression added to enable type checking */
    dialog = plugin.createDialog(new DomHelper(), mockLink);
    dialog.dispatchEvent(
        new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL, true));
    assertEquals(
        'Target should be set to _blank for link that opens in new window',
        '_blank', anchorElem.target);
    assertTrue(
        'Checked state should be true after toggling a link on',
        plugin.getOpenLinkInNewWindowCheckedState());

    // Edit a link that doesn't open in a named window and don't touch it.
    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL, false, 'named');
    /** @suppress {visibility} suppression added to enable type checking */
    dialog = plugin.createDialog(new DomHelper(), mockLink);
    dialog.dispatchEvent(
        new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL, false));
    assertEquals(
        'Target should keep its original value', 'named', anchorElem.target);
    assertFalse(
        'Checked state should be false again',
        plugin.getOpenLinkInNewWindowCheckedState());

    // Edit a link that opens in a new window and toggle it off.
    setUpAnchor(OLD_LINK_TEXT, OLD_LINK_URL, false, '_blank');
    /** @suppress {visibility} suppression added to enable type checking */
    dialog = plugin.createDialog(new DomHelper(), mockLink);
    dialog.dispatchEvent(
        new LinkDialog.OkEvent(NEW_LINK_TEXT, NEW_LINK_URL, false));
    assertEquals(
        'Target should not be set for link that doesn\'t open in new window',
        '', anchorElem.target);

    mockCtrl.$verifyAll();
  },

  testOkNoFollowEnabled() {
    verifyRelNoFollow(true, null, 'nofollow');
  },

  testOkNoFollowInUppercase() {
    verifyRelNoFollow(true, 'NOFOLLOW', 'NOFOLLOW');
  },

  testOkNoFollowEnabledHasMoreRelValues() {
    verifyRelNoFollow(true, 'author', 'author nofollow');
  },

  testOkNoFollowDisabled() {
    verifyRelNoFollow(false, null, '');
  },

  testOkNoFollowDisabledHasMoreRelValues1() {
    verifyRelNoFollow(false, 'author', 'author');
  },

  testOkNoFollowDisabledHasMoreRelValues2() {
    verifyRelNoFollow(false, 'author nofollow', 'author ');
  },

  testOkNoFollowInUppercaseWithMoreValues() {
    verifyRelNoFollow(true, 'NOFOLLOW author', 'NOFOLLOW author');
  },

  /**
   * Tests that the selection is cleared when the dialog opens and is
   * correctly restored after cancel is clicked.
   * @suppress {visibility} suppression added to enable type checking
   */
  testRestoreSelectionOnOk() {
    setUpAnchor('12345', '/');
    setUpRealEditableField();

    const elem = fieldObj.getElement();
    const helper = new TestHelper(elem);
    helper.select('12345', 1, '12345', 4);  // Selects '234'.

    assertEquals(
        'Incorrect text selected before dialog is opened', '234',
        fieldObj.getRange().getText());
    plugin.execCommand(Command.MODAL_LINK_EDITOR, linkObj);
    if (!userAgent.IE && !userAgent.OPERA) {
      // IE returns some bogus range when field doesn't have selection.
      // You can't remove the selection from a whitebox field in Opera.
      assertNull(
          'There should be no selection while dialog is open',
          fieldObj.getRange());
    }
    events.fireClickSequence(plugin.dialog_.getOkButtonElement());
    assertEquals(
        'No text should be selected after clicking ok', '',
        fieldObj.getRange().getText());

    // Test that the caret is placed at the end of the link text.
    editorDom.assertRangeBetweenText(
        // If the browser gets stuck in links, an nbsp was added after the
        // link to avoid that, otherwise we just look for the 5.
        BrowserFeature.GETS_STUCK_IN_LINKS ? Unicode.NBSP : '5', '',
        fieldObj.getRange());

    // NOTE(user): The functionality to avoid getting stuck in
    // links is tested in editablelink_test.html::testPlaceCursorRightOf().
  },

  /**
   * Tests that the selection is cleared when the dialog opens and is
   * correctly restored after cancel is clicked.
   * @param {boolean=} isNew Whether to test behavior when creating a new
   *     link (cancelling will flatten it).
   * @suppress {visibility} suppression added to enable type checking
   */
  testRestoreSelectionOnCancel(isNew = undefined) {
    setUpAnchor('12345', '/', isNew);
    setUpRealEditableField();

    const elem = fieldObj.getElement();
    const helper = new TestHelper(elem);
    helper.select('12345', 1, '12345', 4);  // Selects '234'.

    assertEquals(
        'Incorrect text selected before dialog is opened', '234',
        fieldObj.getRange().getText());
    plugin.execCommand(Command.MODAL_LINK_EDITOR, linkObj);
    if (!userAgent.IE && !userAgent.OPERA) {
      // IE returns some bogus range when field doesn't have selection.
      // You can't remove the selection from a whitebox field in Opera.
      assertNull(
          'There should be no selection while dialog is open',
          fieldObj.getRange());
    }
    events.fireClickSequence(plugin.dialog_.getCancelButtonElement());
    assertEquals(
        'Incorrect text selected after clicking cancel', '234',
        fieldObj.getRange().getText());
  },

  /**
   * Tests that the selection is cleared when the dialog opens and is
   * correctly restored after cancel is clicked and the new link is removed.
   */
  testRestoreSelectionOnCancelNew() {
    this.testRestoreSelectionOnCancel(true);
  },

  /**
   * Tests that the BeforeTestLink event is suppressed for invalid url
   * schemes.
   * @suppress {checkTypes} suppression added to enable type checking
   */
  testTestLinkDisabledForInvalidScheme() {
    mockAlert(mockmatchers.isString);
    mockCtrl.$replayAll();

    const invalidUrl = 'javascript:document.write(\'hello\');';

    plugin = new LinkDialogPlugin();
    /** @suppress {visibility} suppression added to enable type checking */
    const dialog = plugin.createDialog(new DomHelper(), mockLink);

    // Mock of execCommand + clicking test without actually opening the
    // dialog.
    const dispatched =
        dialog.dispatchEvent(new LinkDialog.BeforeTestLinkEvent(invalidUrl));

    assertFalse(dispatched);
    mockCtrl.$verifyAll();
  },

  /** @suppress {visibility} suppression added to enable type checking */
  testIsSafeSchemeToOpen() {
    plugin = new LinkDialogPlugin();
    // Urls with no scheme at all are ok too since 'http://' will be
    // prepended.
    const good = [
      'http://google.com',
      'http://google.com/',
      'https://google.com',
      'null@google.com',
      'http://www.google.com',
      'http://site.com',
      'google.com',
      'google',
      'http://google',
      'HTTP://GOOGLE.COM',
      'HtTp://www.google.com',
    ];

    const bad = [
      'javascript:google.com',
      'httpp://google.com',
      'data:foo',
      'javascript:alert(\'hi\');',
      'abc:def',
    ];

    let i;
    for (i = 0; i < good.length; i++) {
      assertTrue(
          good[i] + ' should have a safe scheme',
          plugin.isSafeSchemeToOpen_(good[i]));
    }

    for (i = 0; i < bad.length; i++) {
      assertFalse(
          bad[i] + ' should have an unsafe scheme',
          plugin.isSafeSchemeToOpen_(bad[i]));
    }
  },

  /** @suppress {visibility} suppression added to enable type checking */
  testShouldOpenWithWhitelist() {
    plugin.setSafeToOpenSchemes(['abc']);

    assertTrue(
        'Scheme should be safe', plugin.shouldOpenUrl('abc://google.com'));
    assertFalse(
        'Scheme should be unsafe', plugin.shouldOpenUrl('http://google.com'));

    plugin.setBlockOpeningUnsafeSchemes(false);
    assertTrue(
        'Non-whitelisted should now be safe after disabling blocking',
        plugin.shouldOpenUrl('http://google.com'));
  },

  /**
   * Regression test for http://b/issue?id=1607766 . Without the fix, this
   * should give an Invalid Argument error in IE, because the editable field
   * caches a selection util that has a reference to the node of the link
   * text before it is edited (which gets replaced by a new node for the new
   * text after editing).
   * @suppress {visibility} suppression added to enable type checking
   */
  testBug1607766() {
    setUpAnchor('abc', 'def');
    setUpRealEditableField();

    const elem = fieldObj.getElement();
    const helper = new TestHelper(elem);
    helper.select('abc', 1, 'abc', 2);  // Selects 'b'.
    // Dispatching a selection event causes the field to cache a selection
    // util, which is the root of the bug.
    plugin.fieldObject.dispatchSelectionChangeEvent();

    plugin.execCommand(Command.MODAL_LINK_EDITOR, linkObj);
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.TEXT_TO_DISPLAY).value = 'Abc';
    events.fireClickSequence(plugin.dialog_.getOkButtonElement());

    // In IE the unit test somehow doesn't cause a browser focus event, so
    // we need to manually invoke this, which is where the bug happens.
    plugin.fieldObject.dispatchFocus_();
  },

  /** Regression test for http://b/issue?id=2215546 . */
  testBug2215546() {
    setUpRealEditableField();

    const elem = fieldObj.getElement();
    fieldObj.setSafeHtml(
        false,
        SafeHtml.create('div', {}, SafeHtml.create('a', {'href': '/'}, '')));
    anchorElem = elem.firstChild.firstChild;
    linkObj = new Link(anchorElem, true);

    const helper = new TestHelper(elem);
    // Select "</a>" in a way, simulating what IE does if you hit enter
    // twice, arrow up into the blank line and open the link dialog.
    helper.select(anchorElem, 0, elem.firstChild, 1);

    plugin.execCommand(Command.MODAL_LINK_EDITOR, linkObj);
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.TEXT_TO_DISPLAY).value = 'foo';
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.ON_WEB_INPUT).value = 'foo';
    /** @suppress {visibility} suppression added to enable type checking */
    const okButton = plugin.dialog_.getOkButtonElement();
    okButton.disabled = false;
    events.fireClickSequence(okButton);

    assertEquals(
        'Link text should have been inserted', 'foo', anchorElem.innerHTML);
  },

  /**
   * Test that link insertion doesn't scroll the field to the top
   * after clicking Cancel or OK.
   */
  testBug7279077ScrollOnFocus() {
    if (userAgent.IE) {
      return;  // TODO(user): take this out once b/7279077 fixed for IE
               // too.
    }
    setUpAnchor('12345', '/');
    setUpRealEditableField();

    // Make the field scrollable and kinda small.
    const elem = fieldObj.getElement();
    elem.style.overflow = 'auto';
    elem.style.height = '40px';
    elem.style.width = '200px';
    elem.style.contenteditable = 'true';

    // Add a bunch of text before the anchor tag.
    const longTextElem = dom.createElement(TagName.SPAN);
    longTextElem.innerHTML = googString.repeat('All work and no play.<p>', 20);
    elem.insertBefore(longTextElem, elem.firstChild);

    const helper = new TestHelper(elem);
    helper.select('12345', 1, '12345', 4);  // Selects '234'.

    // Scroll down.
    elem.scrollTop = 60;

    // Bring up the link insertion dialog, then cancel.
    plugin.execCommand(Command.MODAL_LINK_EDITOR, linkObj);
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.TEXT_TO_DISPLAY).value = 'foo';
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.ON_WEB_INPUT).value = 'foo';
    /** @suppress {visibility} suppression added to enable type checking */
    const cancelButton = plugin.dialog_.getCancelButtonElement();
    events.fireClickSequence(cancelButton);

    assertEquals(
        'Field should not have scrolled after cancel', 60, elem.scrollTop);

    // Now let's try it with clicking the OK button.
    plugin.execCommand(Command.MODAL_LINK_EDITOR, linkObj);
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.TEXT_TO_DISPLAY).value = 'foo';
    /**
     * @suppress {visibility,strictMissingProperties} suppression added to
     * enable type checking
     */
    dom.getElement(LinkDialog.Id_.ON_WEB_INPUT).value = 'foo';
    /** @suppress {visibility} suppression added to enable type checking */
    const okButton = plugin.dialog_.getOkButtonElement();
    events.fireClickSequence(okButton);

    assertEquals('Field should not have scrolled after OK', 60, elem.scrollTop);
  },
});


text:
package com.intellij.codeInspection.longLine;

import com.intellij.application.options.CodeStyle;
import com.intellij.application.options.CodeStyleSchemesConfigurable;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.ide.DataManager;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.options.ex.Settings;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiFile;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;

public class LongLineInspection extends LocalInspectionTool {
  @Nullable
  @Override
  public JComponent createOptionsPanel() {
    final HyperlinkLabel codeStyleHyperlink = new HyperlinkLabel("Edit Code Style settings");
    codeStyleHyperlink.addHyperlinkListener(new HyperlinkListener() {
      @Override
      public void hyperlinkUpdate(HyperlinkEvent e) {
        DataManager.getInstance().getDataContextFromFocus().doWhenDone((Consumer<DataContext>)context -> {
          if (context != null) {
            final Settings settings = Settings.KEY.getData(context);
            if (settings != null) {
              settings.select(settings.find(CodeStyleSchemesConfigurable.class));
            }
            else {
              ShowSettingsUtil.getInstance()
                .showSettingsDialog(CommonDataKeys.PROJECT.getData(context), CodeStyleSchemesConfigurable.class);
            }
          }
        });
      }
    });
    final JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(codeStyleHyperlink, BorderLayout.NORTH);
    return panel;
  }

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
    PsiFile file = holder.getFile();
    final int codeStyleRightMargin = CodeStyle.getSettings(file).getRightMargin(file.getLanguage());

    final VirtualFile vFile = file.getVirtualFile();
    if (vFile instanceof VirtualFileWindow) {
      return PsiElementVisitor.EMPTY_VISITOR;
    }
    final Document document = FileDocumentManager.getInstance().getDocument(vFile);
    if (document == null) {
      return PsiElementVisitor.EMPTY_VISITOR;
    }

    return new PsiElementVisitor() {
      @Override
      public void visitElement(@NotNull PsiElement element) {
        int length = element.getTextLength();
        if (element.getTextLength() != 0 && element.getFirstChild() == null && !ignoreFor(element)) {
          int offset = element.getTextOffset();
          int endOffset = offset + length;

          int startLine = document.getLineNumber(offset);
          if (offset > document.getLineStartOffset(startLine) + codeStyleRightMargin) {
            startLine++;
          }

          int endLine = document.getLineNumber(endOffset - 1);

          for (int l = startLine; l <= endLine; l++) {
            int lineEndOffset = document.getLineEndOffset(l);
            int lineMarginOffset = document.getLineStartOffset(l) + codeStyleRightMargin;
            if (lineEndOffset > lineMarginOffset) {
              int highlightingStartOffset = lineMarginOffset - offset;
              int highlightingEndOffset = Math.min(endOffset, lineEndOffset) - offset;
              if (highlightingStartOffset < highlightingEndOffset) {
                TextRange exceedingRange = new TextRange(highlightingStartOffset, highlightingEndOffset);
                holder.registerProblem(element,
                                       exceedingRange,
                                       String.format("Line is longer than allowed by code style (> %s columns)", codeStyleRightMargin));
              }
            }
          }
        }
      }
    };
  }

  private static boolean ignoreFor(@Nullable PsiElement element) {
    return element != null &&
           LongLineInspectionPolicy.EP_NAME.getExtensionList().stream().anyMatch(policy -> policy.ignoreLongLineFor(element));
  }
}