text:
using namespace llvm;
using namespace llvm::msf;
using namespace llvm::pdb;
using namespace llvm::codeview;

struct llvm::pdb::GSIHashStreamBuilder {
  struct SymbolDenseMapInfo {
    static inline CVSymbol getEmptyKey() {
      static CVSymbol Empty;
      return Empty;
    }
    static inline CVSymbol getTombstoneKey() {
      static CVSymbol Tombstone(
          DenseMapInfo<ArrayRef<uint8_t>>::getTombstoneKey());
      return Tombstone;
    }
    static unsigned getHashValue(const CVSymbol &Val) {
      return xxHash64(Val.RecordData);
    }
    static bool isEqual(const CVSymbol &LHS, const CVSymbol &RHS) {
      return LHS.RecordData == RHS.RecordData;
    }
  };

  std::vector<CVSymbol> Records;
  llvm::DenseSet<CVSymbol, SymbolDenseMapInfo> SymbolHashes;
  std::vector<PSHashRecord> HashRecords;
  std::array<support::ulittle32_t, (IPHR_HASH + 32) / 32> HashBitmap;
  std::vector<support::ulittle32_t> HashBuckets;

  uint32_t calculateSerializedLength() const;
  uint32_t calculateRecordByteSize() const;
  Error commit(BinaryStreamWriter &Writer);

  void finalizeBuckets(uint32_t RecordZeroOffset);

  // Finalize public symbol buckets.
  void finalizeBuckets(uint32_t RecordZeroOffset,
                       std::vector<BulkPublic> &&Publics);

  template <typename T> void addSymbol(const T &Symbol, MSFBuilder &Msf) {
    T Copy(Symbol);
    addSymbol(SymbolSerializer::writeOneSymbol(Copy, Msf.getAllocator(),
                                               CodeViewContainer::Pdb));
  }
  void addSymbol(const CVSymbol &Symbol);
};

void GSIHashStreamBuilder::addSymbol(const codeview::CVSymbol &Symbol) {
  // Ignore duplicate typedefs and constants.
  if (Symbol.kind() == S_UDT || Symbol.kind() == S_CONSTANT) {
    auto Iter = SymbolHashes.insert(Symbol);
    if (!Iter.second)
      return;
  }
  Records.push_back(Symbol);
}

namespace {
LLVM_PACKED(struct PublicSym32Layout {
  RecordPrefix Prefix;
  PublicSym32Header Pub;
  // char Name[];
});
}

// Calculate how much memory this public needs when serialized.
static uint32_t sizeOfPublic(const BulkPublic &Pub) {
  uint32_t NameLen = Pub.NameLen;
  NameLen = std::min(NameLen,
                     uint32_t(MaxRecordLength - sizeof(PublicSym32Layout) - 1));
  return alignTo(sizeof(PublicSym32Layout) + NameLen + 1, 4);
}

static CVSymbol serializePublic(uint8_t *Mem, const BulkPublic &Pub) {
  // Assume the caller has allocated sizeOfPublic bytes.
  uint32_t NameLen = std::min(
      Pub.NameLen, uint32_t(MaxRecordLength - sizeof(PublicSym32Layout) - 1));
  size_t Size = alignTo(sizeof(PublicSym32Layout) + NameLen + 1, 4);
  assert(Size == sizeOfPublic(Pub));
  auto *FixedMem = reinterpret_cast<PublicSym32Layout *>(Mem);
  FixedMem->Prefix.RecordKind = static_cast<uint16_t>(codeview::S_PUB32);
  FixedMem->Prefix.RecordLen = static_cast<uint16_t>(Size - 2);
  FixedMem->Pub.Flags = Pub.Flags;
  FixedMem->Pub.Offset = Pub.Offset;
  FixedMem->Pub.Segment = Pub.U.Segment;
  char *NameMem = reinterpret_cast<char *>(FixedMem + 1);
  memcpy(NameMem, Pub.Name, NameLen);
  // Zero the null terminator and remaining bytes.
  memset(&NameMem[NameLen], 0, Size - sizeof(PublicSym32Layout) - NameLen);
  return CVSymbol(makeArrayRef(reinterpret_cast<uint8_t *>(Mem), Size));
}

uint32_t GSIHashStreamBuilder::calculateSerializedLength() const {
  uint32_t Size = sizeof(GSIHashHeader);
  Size += HashRecords.size() * sizeof(PSHashRecord);
  Size += HashBitmap.size() * sizeof(uint32_t);
  Size += HashBuckets.size() * sizeof(uint32_t);
  return Size;
}

uint32_t GSIHashStreamBuilder::calculateRecordByteSize() const {
  uint32_t Size = 0;
  for (const auto &Sym : Records)
    Size += Sym.length();
  return Size;
}

Error GSIHashStreamBuilder::commit(BinaryStreamWriter &Writer) {
  GSIHashHeader Header;
  Header.VerSignature = GSIHashHeader::HdrSignature;
  Header.VerHdr = GSIHashHeader::HdrVersion;
  Header.HrSize = HashRecords.size() * sizeof(PSHashRecord);
  Header.NumBuckets = HashBitmap.size() * 4 + HashBuckets.size() * 4;

  if (auto EC = Writer.writeObject(Header))
    return EC;

  if (auto EC = Writer.writeArray(makeArrayRef(HashRecords)))
    return EC;
  if (auto EC = Writer.writeArray(makeArrayRef(HashBitmap)))
    return EC;
  if (auto EC = Writer.writeArray(makeArrayRef(HashBuckets)))
    return EC;
  return Error::success();
}

static bool isAsciiString(StringRef S) {
  return llvm::all_of(S, [](char C) { return unsigned(C) < 0x80; });
}

// See `caseInsensitiveComparePchPchCchCch` in gsi.cpp
static int gsiRecordCmp(StringRef S1, StringRef S2) {
  size_t LS = S1.size();
  size_t RS = S2.size();
  // Shorter strings always compare less than longer strings.
  if (LS != RS)
    return LS - RS;

  // If either string contains non ascii characters, memcmp them.
  if (LLVM_UNLIKELY(!isAsciiString(S1) || !isAsciiString(S2)))
    return memcmp(S1.data(), S2.data(), LS);

  // Both strings are ascii, perform a case-insenstive comparison.
  return S1.compare_lower(S2.data());
}

void GSIHashStreamBuilder::finalizeBuckets(uint32_t RecordZeroOffset) {
  // Build up a list of globals to be bucketed. This repurposes the BulkPublic
  // struct with different meanings for the fields to avoid reallocating a new
  // vector during public symbol table hash construction.
  std::vector<BulkPublic> Globals;
  Globals.resize(Records.size());
  uint32_t SymOffset = RecordZeroOffset;
  for (size_t I = 0, E = Records.size(); I < E; ++I) {
    StringRef Name = getSymbolName(Records[I]);
    Globals[I].Name = Name.data();
    Globals[I].NameLen = Name.size();
    Globals[I].SymOffset = SymOffset;
    SymOffset += Records[I].length();
  }

  finalizeBuckets(RecordZeroOffset, std::move(Globals));
}

void GSIHashStreamBuilder::finalizeBuckets(uint32_t RecordZeroOffset,
                                           std::vector<BulkPublic> &&Globals) {
  // Hash every name in parallel. The Segment field is no longer needed, so
  // store the BucketIdx in a union.
  parallelForEachN(0, Globals.size(), [&](size_t I) {
    Globals[I].U.BucketIdx = hashStringV1(Globals[I].Name) % IPHR_HASH;
  });

  // Parallel sort by bucket index, then name within the buckets. Within the
  // buckets, sort each bucket by memcmp of the symbol's name.  It's important
  // that we use the same sorting algorithm as is used by the reference
  // implementation to ensure that the search for a record within a bucket can
  // properly early-out when it detects the record won't be found.  The
  // algorithm used here corredsponds to the function
  // caseInsensitiveComparePchPchCchCch in the reference implementation.
  auto BucketCmp = [](const BulkPublic &L, const BulkPublic &R) {
    if (L.U.BucketIdx != R.U.BucketIdx)
      return L.U.BucketIdx < R.U.BucketIdx;
    int Cmp = gsiRecordCmp(L.getName(), R.getName());
    if (Cmp != 0)
      return Cmp < 0;
    // This comparison is necessary to make the sorting stable in the presence
    // of two static globals with the same name. The easiest way to observe
    // this is with S_LDATA32 records.
    return L.SymOffset < R.SymOffset;
  };
  parallelSort(Globals, BucketCmp);

  // Zero out the bucket index bitmap.
  for (ulittle32_t &Word : HashBitmap)
    Word = 0;

  // Compute the three tables: the hash records in bucket and chain order, the
  // bucket presence bitmap, and the bucket chain start offsets.
  HashRecords.reserve(Globals.size());
  uint32_t LastBucketIdx = ~0U;
  for (const BulkPublic &Global : Globals) {
    // If this is a new bucket, add it to the bitmap and the start offset map.
    uint32_t BucketIdx = Global.U.BucketIdx;
    if (LastBucketIdx != BucketIdx) {
      HashBitmap[BucketIdx / 32] |= 1U << (BucketIdx % 32);

      // Calculate what the offset of the first hash record in the chain would
      // be if it were inflated to contain 32-bit pointers. On a 32-bit system,
      // each record would be 12 bytes. See HROffsetCalc in gsi.h.
      const int SizeOfHROffsetCalc = 12;
      ulittle32_t ChainStartOff =
          ulittle32_t(HashRecords.size() * SizeOfHROffsetCalc);
      HashBuckets.push_back(ChainStartOff);
      LastBucketIdx = BucketIdx;
    }

    // Create the hash record. Add one when writing symbol offsets to disk.
    // See GSI1::fixSymRecs. Always use a refcount of 1 for now.
    PSHashRecord HRec;
    HRec.Off = Global.SymOffset + 1;
    HRec.CRef = 1;
    HashRecords.push_back(HRec);
  }
}

GSIStreamBuilder::GSIStreamBuilder(msf::MSFBuilder &Msf)
    : Msf(Msf), PSH(std::make_unique<GSIHashStreamBuilder>()),
      GSH(std::make_unique<GSIHashStreamBuilder>()) {}

GSIStreamBuilder::~GSIStreamBuilder() {}

uint32_t GSIStreamBuilder::calculatePublicsHashStreamSize() const {
  uint32_t Size = 0;
  Size += sizeof(PublicsStreamHeader);
  Size += PSH->calculateSerializedLength();
  Size += PubAddrMap.size() * sizeof(uint32_t); // AddrMap
  // FIXME: Add thunk map and section offsets for incremental linking.

  return Size;
}

uint32_t GSIStreamBuilder::calculateGlobalsHashStreamSize() const {
  return GSH->calculateSerializedLength();
}

Error GSIStreamBuilder::finalizeMsfLayout() {
  // First we write public symbol records, then we write global symbol records.
  uint32_t PublicsSize = PSH->calculateRecordByteSize();
  uint32_t GlobalsSize = GSH->calculateRecordByteSize();
  GSH->finalizeBuckets(PublicsSize);

  Expected<uint32_t> Idx = Msf.addStream(calculateGlobalsHashStreamSize());
  if (!Idx)
    return Idx.takeError();
  GlobalsStreamIndex = *Idx;

  Idx = Msf.addStream(calculatePublicsHashStreamSize());
  if (!Idx)
    return Idx.takeError();
  PublicsStreamIndex = *Idx;

  uint32_t RecordBytes = PublicsSize + GlobalsSize;

  Idx = Msf.addStream(RecordBytes);
  if (!Idx)
    return Idx.takeError();
  RecordStreamIndex = *Idx;
  return Error::success();
}

void GSIStreamBuilder::addPublicSymbols(std::vector<BulkPublic> &&Publics) {
  // Sort the symbols by name. PDBs contain lots of symbols, so use parallelism.
  parallelSort(Publics, [](const BulkPublic &L, const BulkPublic &R) {
    return L.getName() < R.getName();
  });

  // Assign offsets and allocate one contiguous block of memory for all public
  // symbols.
  uint32_t SymOffset = 0;
  for (BulkPublic &Pub : Publics) {
    Pub.SymOffset = SymOffset;
    SymOffset += sizeOfPublic(Pub);
  }
  uint8_t *Mem =
      reinterpret_cast<uint8_t *>(Msf.getAllocator().Allocate(SymOffset, 4));

  // Instead of storing individual CVSymbol records, store them as one giant
  // buffer.
  // FIXME: This is kind of a hack. This makes Records.size() wrong, and we have
  // to account for that elsewhere.
  PSH->Records.push_back(CVSymbol(makeArrayRef(Mem, SymOffset)));

  // Serialize them in parallel.
  parallelForEachN(0, Publics.size(), [&](size_t I) {
    const BulkPublic &Pub = Publics[I];
    serializePublic(Mem + Pub.SymOffset, Pub);
  });

  // Re-sort the publics by address so we can build the address map. We no
  // longer need the original ordering.
  auto AddrCmp = [](const BulkPublic &L, const BulkPublic &R) {
    if (L.U.Segment != R.U.Segment)
      return L.U.Segment < R.U.Segment;
    if (L.Offset != R.Offset)
      return L.Offset < R.Offset;
    // parallelSort is unstable, so we have to do name comparison to ensure
    // that two names for the same location come out in a determinstic order.
    return L.getName() < R.getName();
  };
  parallelSort(Publics, AddrCmp);

  // Fill in the symbol offsets in the appropriate order.
  PubAddrMap.reserve(Publics.size());
  for (const BulkPublic &Pub : Publics)
    PubAddrMap.push_back(ulittle32_t(Pub.SymOffset));

  // Finalize public symbol buckets immediately after they have been added.
  // They should all be warm in the cache at this point, so go ahead and do it
  // now.
  PSH->finalizeBuckets(0, std::move(Publics));
}

void GSIStreamBuilder::addGlobalSymbol(const ProcRefSym &Sym) {
  GSH->addSymbol(Sym, Msf);
}

void GSIStreamBuilder::addGlobalSymbol(const DataSym &Sym) {
  GSH->addSymbol(Sym, Msf);
}

void GSIStreamBuilder::addGlobalSymbol(const ConstantSym &Sym) {
  GSH->addSymbol(Sym, Msf);
}

void GSIStreamBuilder::addGlobalSymbol(const codeview::CVSymbol &Sym) {
  GSH->addSymbol(Sym);
}

static Error writeRecords(BinaryStreamWriter &Writer,
                          ArrayRef<CVSymbol> Records) {
  BinaryItemStream<CVSymbol> ItemStream(support::endianness::little);
  ItemStream.setItems(Records);
  BinaryStreamRef RecordsRef(ItemStream);
  return Writer.writeStreamRef(RecordsRef);
}

Error GSIStreamBuilder::commitSymbolRecordStream(
    WritableBinaryStreamRef Stream) {
  BinaryStreamWriter Writer(Stream);

  // Write public symbol records first, followed by global symbol records.  This
  // must match the order that we assume in finalizeMsfLayout when computing
  // PSHZero and GSHZero.
  if (auto EC = writeRecords(Writer, PSH->Records))
    return EC;
  if (auto EC = writeRecords(Writer, GSH->Records))
    return EC;

  return Error::success();
}

Error GSIStreamBuilder::commitPublicsHashStream(
    WritableBinaryStreamRef Stream) {
  BinaryStreamWriter Writer(Stream);
  PublicsStreamHeader Header;

  // FIXME: Fill these in. They are for incremental linking.
  Header.SymHash = PSH->calculateSerializedLength();
  Header.AddrMap = PubAddrMap.size() * 4;
  Header.NumThunks = 0;
  Header.SizeOfThunk = 0;
  Header.ISectThunkTable = 0;
  memset(Header.Padding, 0, sizeof(Header.Padding));
  Header.OffThunkTable = 0;
  Header.NumSections = 0;
  if (auto EC = Writer.writeObject(Header))
    return EC;

  if (auto EC = PSH->commit(Writer))
    return EC;

  if (auto EC = Writer.writeArray(makeArrayRef(PubAddrMap)))
    return EC;

  return Error::success();
}

Error GSIStreamBuilder::commitGlobalsHashStream(
    WritableBinaryStreamRef Stream) {
  BinaryStreamWriter Writer(Stream);
  return GSH->commit(Writer);
}

Error GSIStreamBuilder::commit(const msf::MSFLayout &Layout,
                               WritableBinaryStreamRef Buffer) {
  auto GS = WritableMappedBlockStream::createIndexedStream(
      Layout, Buffer, getGlobalsStreamIndex(), Msf.getAllocator());
  auto PS = WritableMappedBlockStream::createIndexedStream(
      Layout, Buffer, getPublicsStreamIndex(), Msf.getAllocator());
  auto PRS = WritableMappedBlockStream::createIndexedStream(
      Layout, Buffer, getRecordStreamIndex(), Msf.getAllocator());

  if (auto EC = commitSymbolRecordStream(*PRS))
    return EC;
  if (auto EC = commitGlobalsHashStream(*GS))
    return EC;
  if (auto EC = commitPublicsHashStream(*PS))
    return EC;
  return Error::success();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- disabled state -->
    <item android:drawable="@drawable/attachment_menu_effect_two" android:state_enabled="false"/>

    <!-- enabled and pressed state -->
    <item android:drawable="@drawable/attachment_menu_effect_two" android:state_enabled="true" android:state_pressed="true"/>

    <!-- enabled and focused state -->
    <item android:drawable="@drawable/attachment_menu_effect_two" android:state_enabled="true" android:state_focused="true"/>

    <!-- enabled state -->
    <item android:drawable="@drawable/attachment_menu_effect_one" android:state_enabled="true"/>

</selector>

redpajama_set_name: RedPajamaGithub


text:
def get_include_dirs():
    from sysconfig import get_paths
    import numpy,os,sys

    package_dir = os.path.dirname(os.path.realpath(__file__))
    data_path = get_paths()["data"]

    package_dir = os.path.expandvars(package_dir)
    data_path = os.path.expandvars(data_path)

    include_dirs = [numpy.get_include()]
    include_dirs.append(os.path.join(package_dir,"source"))
    if sys.platform == "win32":
        include_dirs.append(os.path.join(data_path,"Library","include"))
    else:
        include_dirs.append(os.path.join(data_path,"include"))

    return include_dirs

def cython_files():
    import os,glob
    from Cython.Build import cythonize

    package_dir = os.path.dirname(os.path.realpath(__file__))
    package_dir = os.path.expandvars(package_dir)

    cython_src = glob.glob(os.path.join(package_dir,"*.pyx"))
    # cython_src = [os.path.join(package_dir,"spinless_fermion_core.pyx")]
    # cython_src = [os.path.join(package_dir,"hcb_core.pyx")]
    # cython_src = [os.path.join(package_dir,"general_basis_utils.pyx")]

    include_dir = os.path.join(package_dir,"source")
    cythonize(cython_src,include_path=get_include_dirs())

def configuration(parent_package='', top_path=None):
    import numpy,os,sys,glob
    from numpy.distutils.misc_util import Configuration
    config = Configuration('_basis_general_core',parent_package, top_path)

    cython_files()

    if sys.platform == "win32":
        extra_compile_args=[]
    else:
        extra_compile_args=["-fno-strict-aliasing","-Wno-unused-variable","-Wno-unknown-pragmas","-std=c++11"]

    extra_link_args=[]

    if sys.platform == "darwin":
        extra_compile_args.append("-std=c++11")

    package_dir = os.path.dirname(os.path.realpath(__file__))
    package_dir = os.path.expandvars(package_dir)

    depends = glob.glob(os.path.join(package_dir,"source","*.h"))

    all_headers = set(glob.glob(os.path.join(package_dir,"source","*.h")))

    src_spec_headers = set(glob.glob(os.path.join(package_dir,"source","*_basis_core.h")))
    # needed for utils.
    src_spec_headers.add(os.path.join(package_dir,"source","general_basis_bitops.h"))
    # remove as it is actually a global header.
    src_spec_headers.remove(os.path.join(package_dir,"source","general_basis_core.h"))

    # remove specific headers from all the headers to get the shared headers.

    global_headers = list(all_headers - src_spec_headers)

    extension_kwargs = dict(include_dirs=get_include_dirs(),
                            extra_compile_args=extra_compile_args,
                            extra_link_args=extra_link_args,
                            language="c++")

    hcp_src = os.path.join(package_dir,"hcb_core.cpp")
    hcp_src_header = os.path.join(package_dir,"source","hcb_basis_core.h")
    depends = global_headers+[hcp_src_header]
    config.add_extension('hcb_core',sources=hcp_src,
        depends=depends,**extension_kwargs)

    higher_spin_src = os.path.join(package_dir,"higher_spin_core.cpp")
    higher_spin_src_header = os.path.join(package_dir,"source","higher_spin_basis_core.h")
    depends = global_headers+[higher_spin_src_header]
    config.add_extension('higher_spin_core',sources=higher_spin_src,
        depends=depends,**extension_kwargs)

    boson_src = os.path.join(package_dir,"boson_core.cpp")
    boson_src_header = os.path.join(package_dir,"source","boson_basis_core.h")
    depends = global_headers+[boson_src_header]
    config.add_extension('boson_core',sources=boson_src,
        depends=depends,**extension_kwargs)

    spinless_fermion_src = os.path.join(package_dir,"spinless_fermion_core.cpp")
    spinless_fermion_src_header = os.path.join(package_dir,"source","spinless_fermion_basis_core.h")
    depends = global_headers+[spinless_fermion_src_header]
    config.add_extension('spinless_fermion_core',sources=spinless_fermion_src,
        depends=depends,**extension_kwargs)

    spinful_fermion_src = os.path.join(package_dir,"spinful_fermion_core.cpp")
    spinful_fermion_src_header = os.path.join(package_dir,"source","spinful_fermion_basis_core.h")
    depends = global_headers+[spinful_fermion_src_header]
    config.add_extension('spinful_fermion_core',sources=spinful_fermion_src,
        depends=depends,**extension_kwargs)

    user_src = os.path.join(package_dir,"user_core.cpp")
    user_src_header = os.path.join(package_dir,"source","user_basis_core.h")
    depends = global_headers+[user_src_header]
    config.add_extension('user_core',sources=user_src,depends=depends,**extension_kwargs)

    utils_src = os.path.join(package_dir,"general_basis_utils.cpp")
    utils_src_header = os.path.join(package_dir,"source","general_basis_bitops.h")
    depends = global_headers+[utils_src_header]
    config.add_extension('general_basis_utils',sources=utils_src,
        depends=depends,**extension_kwargs)

    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())


text:
describe('messages', function () {

  var $scope = null;
  var messages = null;

  beforeEach(function () {

    module('app');

    inject(function ($rootScope, messagesFactory) {

      $scope = $rootScope.$new();
      messages = new messagesFactory();

    });

  });

  describe('addMessage', function () {

    it('should add message', function () {

      messages.addMessage('someone', 'something');

      expect(messages.messages.length).to.eql(1);

    });

  });

  describe('getMessages', function () {

    it('should get messages', function (done) {

      messages.addMessage('0', 'someone', 'something');
      messages.addMessage('1', 'someone', 'something');

      messages.getMessages('roomId', '0', function (err, messages) {

        expect(err).to.eql(null);
        expect(messages.length).to.eql(1);

        done();

      });

    });

  });

});


text:
package org.krysalis.barcode4j.impl.code93;

import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.krysalis.barcode4j.ChecksumMode;
import org.krysalis.barcode4j.impl.ConfigurableBarcodeGenerator;
import org.krysalis.barcode4j.tools.Length;

/**
 * This class is an implementation of the Code93 barcode.
 *
 * @author Jeremias Maerki
 * @version $Id$
 */
public class Code93 extends ConfigurableBarcodeGenerator
            implements Configurable {

    /** Create a new instance. */
    public Code93() {
        this.bean = new Code93Bean();
    }

    /**
     * @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
     */
    public void configure(Configuration cfg) throws ConfigurationException {
        //Module width (MUST ALWAYS BE FIRST BECAUSE QUIET ZONE MAY DEPEND ON IT)
        Length mw = new Length(cfg.getChild("module-width").getValue("0.19mm"), "mm");
        getCode93Bean().setModuleWidth(mw.getValueAsMillimeter());

        super.configure(cfg);

        //Checksum mode
        getCode93Bean().setChecksumMode(ChecksumMode.byName(
            cfg.getChild("checksum").getValue(ChecksumMode.CP_AUTO.getName())));

        if (cfg.getChild("extended-charset", false) != null) {
            getCode93Bean().setExtendedCharSetEnabled(
                    cfg.getChild("extended-charset").getValueAsBoolean());
        }

        Configuration hr = cfg.getChild("human-readable", false);
        if (hr != null) {
            //Display start/stop character and checksum in hr-message or not
            getCode93Bean().setDisplayStartStop(
                    hr.getChild("display-start-stop").getValueAsBoolean(false));
            getCode93Bean().setDisplayChecksum(
                    hr.getChild("display-checksum").getValueAsBoolean(false));
        }
    }

    /**
     * @return the underlying Code93Bean
     */
    public Code93Bean getCode93Bean() {
        return (Code93Bean)getBean();
    }

}


text:
import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
} from 'react-native';

import I18n from 'react-native-i18n'

class Register extends Component{
  constructor() {
    super();

    this.state = {
      name: "",
      username: "",
      location: "",
      bio: "",
      preferred_contact: "",
      skills: "",
      seeking: "",
      resource_request: "",
      errors: [],
    }
  }

  async _onPressRegister(){
    try {
      let response = await fetch('http:///simulnos.herokuapp.com/api/users', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          user: {
            name: this.state.name,
            username: this.state.username,
            location: this.state.location,
            bio: this.state.bio,
            preferred_contact: this.state.preferred_contact,
            skills: this.state.skills,
            seeking: this.state.seeking,
            resource_request: this.state.resource_request,
          }
        })
      });

      let res = await response.text();
      console.log("res is: " + res)
    } catch(errors){
    }
  }

  render() {

    return (
      <View style={styles.container}>
        <Text style={styles.header}>
        {I18n.t('createAccount')}
        </Text>
        <TextInput
          onChangeText={ (val)=> this.setState({name: val}) }
          style={styles.input} placeholder={I18n.t('name')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({username: val}) }
          style={styles.input} placeholder={I18n.t('username')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({location: val}) }
          style={styles.input} placeholder={I18n.t('location')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({bio: val}) }
          style={styles.input} placeholder={I18n.t('bio')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({preferred_contact: val}) }
          style={styles.input} placeholder={I18n.t('contactInformation')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({skills: val}) }
          style={styles.input} placeholder={I18n.t('skills')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({seeking: val}) }
          style={styles.input} placeholder={I18n.t('seeking')}
        />
        <TextInput
          onChangeText={ (val)=> this.setState({seeking: val}) }
          style={styles.input} placeholder={I18n.t('resourceRequest')}
        />
        <TouchableHighlight onPress={this._onPressRegister.bind(this)} style={styles.button}>
          <Text style={styles.buttonText}>
          {I18n.t('register')}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 30,
    backgroundColor: "#29c5da",

  },
  title: {
   fontSize: 20,
   alignSelf: 'center',
   margin: 40,
  },
  input: {
    height: 50,
    marginTop: 10,
    padding: 4,
    fontSize: 15,
    borderWidth: 1,
    borderColor: 'white',
    color: 'white',
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  header: {
    color: 'white',
    fontSize: 18,
  }
});

module.exports = Register;


text:
// Package webserver implements a superset wrapper of http.Server.
//
// Among other things, it can throttle its connections, inherit its
// listening socket from a file descriptor in the environment, and
// log all activity.
package webserver // import "perkeep.org/pkg/webserver"

import (
	"crypto/rand"
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"perkeep.org/pkg/webserver/listen"

	"go4.org/net/throttle"
	"go4.org/wkfs"
	"golang.org/x/net/http2"
)

type Server struct {
	mux      *http.ServeMux
	listener net.Listener
	verbose  bool // log HTTP requests and response codes

	Logger *log.Logger // or nil.

	// H2Server is the HTTP/2 server config.
	H2Server http2.Server

	// enableTLS sets the Server up for listening to HTTPS connections.
	enableTLS bool
	// tlsCertFile (tlsKeyFile) is the path to the HTTPS certificate (key) file.
	tlsCertFile, tlsKeyFile string
	// certManager is set as GetCertificate in the tls.Config of the listener. But tlsCertFile takes precedence.
	certManager func(*tls.ClientHelloInfo) (*tls.Certificate, error)

	mu   sync.Mutex
	reqs int64
}

func New() *Server {
	verbose, _ := strconv.ParseBool(os.Getenv("CAMLI_HTTP_DEBUG"))
	return &Server{
		mux:     http.NewServeMux(),
		verbose: verbose,
	}
}

func (s *Server) printf(format string, v ...interface{}) {
	if s.Logger != nil {
		s.Logger.Printf(format, v...)
		return
	}
	log.Printf(format, v...)
}

func (s *Server) fatalf(format string, v ...interface{}) {
	if s.Logger != nil {
		s.Logger.Fatalf(format, v...)
		return
	}
	log.Fatalf(format, v...)
}

// TLSSetup specifies how the server gets its TLS certificate.
type TLSSetup struct {
	// Certfile is the path to the TLS certificate file. It takes precedence over CertManager.
	CertFile string
	// KeyFile is the path to the TLS key file.
	KeyFile string
	// CertManager is the tls.GetCertificate of the tls Config. But CertFile takes precedence.
	CertManager func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error)
}

func (s *Server) SetTLS(setup TLSSetup) {
	s.enableTLS = true
	s.certManager = setup.CertManager
	s.tlsCertFile = setup.CertFile
	s.tlsKeyFile = setup.KeyFile
}

func (s *Server) ListenURL() string {
	scheme := "http"
	if s.enableTLS {
		scheme = "https"
	}
	if s.listener != nil {
		if taddr, ok := s.listener.Addr().(*net.TCPAddr); ok {
			if taddr.IP.IsUnspecified() {
				return fmt.Sprintf("%s://localhost:%d", scheme, taddr.Port)
			}
			return fmt.Sprintf("%s://%s", scheme, s.listener.Addr())
		}
	}
	return ""
}

func (s *Server) HandleFunc(pattern string, fn func(http.ResponseWriter, *http.Request)) {
	s.mux.HandleFunc(pattern, fn)
}

func (s *Server) Handle(pattern string, handler http.Handler) {
	s.mux.Handle(pattern, handler)
}

func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	var n int64
	if s.verbose {
		s.mu.Lock()
		s.reqs++
		n = s.reqs
		s.mu.Unlock()
		s.printf("Request #%d: %s %s (from %s) ...", n, req.Method, req.RequestURI, req.RemoteAddr)
		rw = &trackResponseWriter{ResponseWriter: rw}
	}
	s.mux.ServeHTTP(rw, req)
	if s.verbose {
		tw := rw.(*trackResponseWriter)
		s.printf("Request #%d: %s %s = code %d, %d bytes", n, req.Method, req.RequestURI, tw.code, tw.resSize)
	}
}

type trackResponseWriter struct {
	http.ResponseWriter
	code    int
	resSize int64
}

func (tw *trackResponseWriter) WriteHeader(code int) {
	tw.code = code
	tw.ResponseWriter.WriteHeader(code)
}

func (tw *trackResponseWriter) Write(p []byte) (int, error) {
	if tw.code == 0 {
		tw.code = 200
	}
	tw.resSize += int64(len(p))
	return tw.ResponseWriter.Write(p)
}

// Listen starts listening on the given host:port addr.
func (s *Server) Listen(addr string) error {
	if s.listener != nil {
		return nil
	}

	if addr == "" {
		return fmt.Errorf("<host>:<port> needs to be provided to start listening")
	}

	var err error
	s.listener, err = listen.Listen(addr)
	if err != nil {
		return fmt.Errorf("Failed to listen on %s: %v", addr, err)
	}
	base := s.ListenURL()
	s.printf("Starting to listen on %s\n", base)

	doEnableTLS := func() error {
		config := &tls.Config{
			Rand:       rand.Reader,
			Time:       time.Now,
			NextProtos: []string{http2.NextProtoTLS, "http/1.1"},
			MinVersion: tls.VersionTLS12,
		}
		if s.tlsCertFile == "" && s.certManager != nil {
			config.GetCertificate = s.certManager
			s.listener = tls.NewListener(s.listener, config)
			return nil
		}

		config.Certificates = make([]tls.Certificate, 1)
		config.Certificates[0], err = loadX509KeyPair(s.tlsCertFile, s.tlsKeyFile)
		if err != nil {
			return fmt.Errorf("Failed to load TLS cert: %v", err)
		}
		s.listener = tls.NewListener(s.listener, config)
		return nil
	}
	if s.enableTLS {
		if err := doEnableTLS(); err != nil {
			return err
		}
	}

	if strings.HasSuffix(base, ":0") {
		s.printf("Now listening on %s\n", s.ListenURL())
	}

	return nil
}

func (s *Server) throttleListener() net.Listener {
	kBps, _ := strconv.Atoi(os.Getenv("DEV_THROTTLE_KBPS"))
	ms, _ := strconv.Atoi(os.Getenv("DEV_THROTTLE_LATENCY_MS"))
	if kBps == 0 && ms == 0 {
		return s.listener
	}
	rate := throttle.Rate{
		KBps:    kBps,
		Latency: time.Duration(ms) * time.Millisecond,
	}
	return &throttle.Listener{
		Listener: s.listener,
		Down:     rate,
		Up:       rate, // TODO: separate rates?
	}
}

func (s *Server) Serve() {
	if err := s.Listen(""); err != nil {
		s.fatalf("Listen error: %v", err)
	}
	go runTestHarnessIntegration(s.listener)

	srv := &http.Server{
		Handler: s,
	}
	// TODO: allow configuring src.ErrorLog (and plumb through to
	// Google Cloud Logging when run on GCE, eventually)

	// Setup the NPN NextProto map for HTTP/2 support:
	http2.ConfigureServer(srv, &s.H2Server)

	err := srv.Serve(s.throttleListener())
	if err != nil {
		s.printf("Error in http server: %v\n", err)
		os.Exit(1)
	}
}

// Signals the test harness that we've started listening.
// TODO: write back the port number that we randomly selected?
// For now just writes back a single byte.
func runTestHarnessIntegration(listener net.Listener) {
	addr := os.Getenv("CAMLI_SET_BASE_URL_AND_SEND_ADDR_TO")
	c, err := net.Dial("tcp", addr)
	if err == nil {
		fmt.Fprintf(c, "%s\n", listener.Addr())
		c.Close()
	}
}

// loadX509KeyPair is a copy of tls.LoadX509KeyPair but using wkfs.
func loadX509KeyPair(certFile, keyFile string) (cert tls.Certificate, err error) {
	certPEMBlock, err := wkfs.ReadFile(certFile)
	if err != nil {
		return
	}
	keyPEMBlock, err := wkfs.ReadFile(keyFile)
	if err != nil {
		return
	}
	return tls.X509KeyPair(certPEMBlock, keyPEMBlock)
}


text:
package org.apache.olingo.commons.core.edm.primitivetype;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.junit.Test;

public class UInt7Test extends PrimitiveTypeBaseTest {

  @Test
  public void compatibility() {
    assertTrue(Uint7.getInstance().isCompatible(Uint7.getInstance()));
    assertFalse(Uint7.getInstance().isCompatible(
        EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.String)));
  }
}


text:
import webapp2

class LazyHandler(webapp2.RequestHandler):
    def get(self, **kwargs):
        self.response.out.write('I am a laaazy view.')

class CustomMethodHandler(webapp2.RequestHandler):
    def custom_method(self):
        self.response.out.write('I am a custom method.')

def handle_exception(request, response, exception):
    return webapp2.Response(body='Hello, custom response world!')


text:
/* EXPERIMENTAL (really) */
/* Copyright (c) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api;

import org.json.me.JSONObject;

/**
 * Converts a json to an {@link ActivityEntry}.
 *
 * @author Sachin Shenoy
 */
class ActivityConverter extends Converter {

  Object convert(JSONObject json) {
    String activityType = getTypeOf(json);

    if (ActivityEntry.ActivityType.FRIEND_ADD.equals(activityType)) {
      return new FriendAddActivity(json);
    }
    if (ActivityEntry.ActivityType.MAKAMAKA.equals(activityType)) {
      return new MakamakaActivity(json);
    }
    if (ActivityEntry.ActivityType.PHOTO_COMMENT.equals(activityType)) {
      return new PhotoCommentActivity(json);
    }
    if (ActivityEntry.ActivityType.PROFILE_UPDATE.equals(activityType)) {
      return new ProfileUpdateActivity(json);
    }
    if (ActivityEntry.ActivityType.SCRAP.equals(activityType)) {
      return new ScrapActivity(json);
    }
    if (ActivityEntry.ActivityType.SOCIAL_EVENTS_CREATION.equals(activityType)) {
      return new SocialEventActivity(json);
    }
    if (ActivityEntry.ActivityType.STATUS_MSG.equals(activityType)) {
      return new StatusMessageActivity(json);
    }
    if (ActivityEntry.ActivityType.TESTIMONIAL.equals(activityType)) {
      return new TestimonialActivity(json);
    }
    if (ActivityEntry.ActivityType.VIDEO.equals(activityType)) {
      return new VideoShareActivity(json);
    }
    if (ActivityEntry.ActivityType.PHOTO.equals(activityType)) {
      return new PhotoShareActivity(json);
    }

    return new GenericActivity(json);
  }

  /** Type of the activity one from the {@link ActivityEntry.ActivityType}. */
  static String getTypeOf(JSONObject json) {
    JSONObject templateParams = json.optJSONObject(Fields.TEMPLATE_PARAMS);
    if (templateParams == null) {
      return "";
    }
    return templateParams.optString(Fields.ACTIVITY_TYPE);
  }
}


text:
Dummy::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  Fabrication.configure do |config|
  #config.fabricator_dir = File.expand_path( File.join(File.dirname(__FILE__), 'spec/fabricators') )
    config.fabricator_dir = "../fabricators"
  end

  # In the development environment your application's code is reloaded on
  # every request.  This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Log error messages when you accidentally call methods on nil.
  config.whiny_nils = true

  # Show full error reports and disable caching
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send
  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.default_url_options = { :host => 'iugusdk.dev:3000' }

  # Print deprecation notices to the Rails logger
  config.active_support.deprecation = :log

  # Only use best-standards-support built into browsers
  config.action_dispatch.best_standards_support = :builtin

  # Do not compress assets
  config.assets.compress = false

  # Expands the lines which load the assets
  config.assets.debug = true
end


text:
package useless.type_traits;

public class IsVoid
{
	public static <T> boolean invoke( Class<T> type )
	{
		return ( type == Void.class || type == void.class );
	}
}


text:
order: 2
title:
  zh-CN: 箭头
  en-US: Arrow
---

## zh-CN

可以展示一个箭头。

## en-US

You could display an arrow.

```tsx
import { Button, Dropdown, Menu } from 'antd';
import React from 'react';

const menu = (
  <Menu
    items={[
      {
        key: '1',
        label: (
          <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
            1st menu item
          </a>
        ),
      },
      {
        key: '2',
        label: (
          <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
            2nd menu item
          </a>
        ),
      },
      {
        key: '3',
        label: (
          <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
            3rd menu item
          </a>
        ),
      },
    ]}
  />
);

const App: React.FC = () => (
  <>
    <Dropdown overlay={menu} placement="bottomLeft" arrow>
      <Button>bottomLeft</Button>
    </Dropdown>
    <Dropdown overlay={menu} placement="bottom" arrow>
      <Button>bottom</Button>
    </Dropdown>
    <Dropdown overlay={menu} placement="bottomRight" arrow>
      <Button>bottomRight</Button>
    </Dropdown>
    <br />
    <Dropdown overlay={menu} placement="topLeft" arrow>
      <Button>topLeft</Button>
    </Dropdown>
    <Dropdown overlay={menu} placement="top" arrow>
      <Button>top</Button>
    </Dropdown>
    <Dropdown overlay={menu} placement="topRight" arrow>
      <Button>topRight</Button>
    </Dropdown>
  </>
);

export default App;
```

```css
#components-dropdown-demo-arrow .ant-btn {
  margin-right: 8px;
  margin-bottom: 8px;
}
.ant-row-rtl #components-dropdown-demo-arrow .ant-btn {
  margin-right: 0;
  margin-bottom: 8px;
  margin-left: 8px;
}
```


text:
package org.ovirt.engine.core.vdsbroker.vdsbroker;

import org.ovirt.engine.core.common.vdscommands.PauseVDSCommandParameters;

public class PauseVDSCommand<P extends PauseVDSCommandParameters> extends VmReturnVdsBrokerCommand<P> {
    public PauseVDSCommand(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeVdsBrokerCommand() {
        vmReturn = getBroker().pause(vmId.toString());
        proceedProxyReturnValue();
        setReturnValue(VdsBrokerObjectsBuilder.buildVMDynamicData(vmReturn.vm, getVds()).getStatus());
    }
}


text:
flowclass:
  - Application
  - Experience
description: Learn more about the Losant Create Experience User Node.
---

# Create Experience User Node

The Create Experience User Node allows a workflow to create a new [Experience User](/experiences/users/) inside the current application, and optionally add the new user to the current workflow payload.

![Create Experience User Node](/images/workflows/experience/create-user-node.png "Create Experience User Node")

## Configuration

There are three different ways to configure input data for the Create Experience User Node - "JSON Template", "Payload Path", and "Individual Fields". The first two are more complicated to use, but are very powerful because they give you full control over the user being created, while the third choice is the more common option for simple situations.

![Create Experience User Node Configuration](/images/workflows/experience/create-user-node-config.png "Create Experience User Node Configuration")

For "JSON Template", the input must be a [JSON template string](/workflows/accessing-payload-data/#json-templates) that can be parsed into a JSON object that validates against the [Experience User Post](/rest-api/schemas/#experience-user-post) schema. For "Payload Path", the input must be a [payload path](/workflows/accessing-payload-data/#payload-paths) that points to an object on the current workflow payload that, again, validates against the [Experience User Post](/rest-api/schemas/#experience-user-post) schema.

For "Individual Fields", the most common method to use and the one shown in the example above, the user is broken into multiple fields that can be filled in using individual [string templates](/workflows/accessing-payload-data/#string-templates). In this case, email and password are required, first and last name are optional (same as when creating an [Experience User](/experiences/users/) normally).

![Create Experience User Node More Configuration](/images/workflows/experience/create-user-node-more-config.png "Create Experience User Node More Configuration")

The "Individual Field" configuration continues down into allowing you to select groups for this new user to become a part of. In the example above, we are not choosing to add this new user to any groups. In the "Individual Field" case, selecting groups is not templatable - in order to dynamically select groups as part of user creation, you would need to use the "JSON Template" or "Payload Path" methods of entry.

Finally, the "Individual Field" configuration also allows you to set user tags, following the same rules as when creating an [Experience User](/experiences/users/) normally. In the example above, one tag will be added to this new user - a tag with the key `externalId` and the value brought in as a [string templates](/workflows/accessing-payload-data/#string-templates) (both the keys and values here are templatable).

![Create Experience User Node Result](/images/workflows/experience/create-user-node-result.png "Create Experience User Node Result")

Optionally you can provide a payload path in the "Result Path" field so that the created experience user can be placed at that path on the current workflow payload. In the case of a successful user creation, this will be the user object, and in the case of a failed user creation this will be an object of any errors about the creation of the user. For instance, given the example node configuration in the screenshots above, this is a possible result for a successful user creation:

```json
{
  "data": {
    "body": {
      "systemId": "myExternalSystemId",
      "newUser": {
        "email": "test@example.com",
        "password": "myFakePassword",
        "name": "myName"
      }
      ...
    },
    "createdUser": {
      "email": "test@example.com",
      "lastName": "myName",
      "applicationId": "58dc4ec29e8df60001fbea01",
      "creationDate": "2017-03-30T00:18:23.902Z",
      "lastUpdated": "2017-03-30T00:18:23.902Z",
      "userTags": {
        "externalId": "myExternalSystemId"
      },
      "passwordLastUpdated": "2017-03-30T00:18:23.903Z",
      "experienceUserId": "58dc4ecf9e8df60001fbea0a",
      "id": "58dc4ecf9e8df60001fbea0a",
      "experienceGroups": []
    },
    ...
  },
  ...
}
```

And again, given the example above, this is a possible result for a failed creation, where the email address was already in use for an existing experience user:

```json
{
  "data": {
    "body": {
      "systemId": "myExternalSystemId",
      "newUser": {
        "email": "test@example.com",
        "password": "myFakePassword",
        "name": "myName"
      }
      ...
    },
    "createdUser": {
      "error": {
        "type": "AlreadyExists",
        "message": "Email address \"test@example.com\" already exists"
      }
    },
    ...
  },
  ...
}
```


text:
// @flow

import alaska, { Sled } from 'alaska';

/**
 * 注销
 */
export default class Logout extends Sled {
  /**
   * @param {Object} params
   *                 params.ctx
   */
  async exec(params: { ctx:Alaska$Context }) {
    let autoLogin = alaska.main.getConfig('autoLogin');
    if (autoLogin && autoLogin.key) {
      params.ctx.cookies.set(autoLogin.key, '', autoLogin);
    }
    delete params.ctx.session.userId;
  }
}