text:
<?xml version="1.0" encoding = "iso-8859-1" standalone="no"?>

<!DOCTYPE faqs SYSTEM "sbk:/style/dtd/faqs.dtd">

<faqs title="Programming/Parsing FAQs">

  <faq title="Does &XercesCName; support Schema?">

    <q> Does &XercesCName; support Schema?</q>

Yes.  The &XercesCName; &XercesCVersion; contains an implementation
         of the W3C XML Schema Language, a recommendation of the Worldwide Web Consortium
         available in three parts:
         <jump href="http://www.w3.org/TR/xmlschema-0/">XML Schema: Primer</jump> and
         <jump href="http://www.w3.org/TR/xmlschema-1/">XML Schema: Structures</jump> and
         <jump href="http://www.w3.org/TR/xmlschema-2/">XML Schema: Datatypes</jump>.
         We consider this implementation complete.  See
         <jump href="schema.html#limitation">the Schema page</jump> for limitations.

  </faq>

  <faq title="Why &XercesCName; does not support this particular Schema feature?">

    <q> Why &XercesCName; does not support this particular Schema feature?</q>

The &XercesCName; &XercesCVersion; contains an implementation
         of the W3C XML Schema Language, a recommendation of the Worldwide Web Consortium
         available in three parts:
         <jump href="http://www.w3.org/TR/xmlschema-0/">XML Schema: Primer</jump> and
         <jump href="http://www.w3.org/TR/xmlschema-1/">XML Schema: Structures</jump> and
         <jump href="http://www.w3.org/TR/xmlschema-2/">XML Schema: Datatypes</jump>.
         We consider this implementation complete.  See
         <jump href="schema.html#limitation">the Schema page</jump> for limitations.

If you find any Schema feature which is specified in the W3C XML Schema Language
         Recommendation does not work with &XercesCName; &XercesCVersion;, we encourage
         the submission of bugs as described in
         <jump href="bug-report.html">Bug Reporting</jump> page.

  </faq>

  <faq title="Why does my application crash when instantiating the parser?">

    <q>Why does my application crash when instantiating the parser?</q>

In order to work with the &XercesCName; parser, you have to first
        initialize the XML subsystem. The most common mistake is to forget this
        initialization. Before you make any calls to &XercesCName; APIs, you must
        call XMLPlatformUtils::Initialize():

<source>
try {
   XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch) {
   // Do your failure processing here
}</source>

This initializes the &XercesCProjectName; system and sets its internal
        variables. Note that you must the include xercesc/util/PlatformUtils.hpp file for this to work.

  </faq>

  <faq title="Is it OK to call the XMLPlatformUtils::Initialize/Terminate pair of routines multiple times in one program?">
    <q>Is it OK to call the XMLPlatformUtils::Initialize/Terminate pair of routines multiple times in one program?</q>

Yes.  Since &XercesCName; &XercesCVersion152;, the code has been enhanced so that
         calling XMLPlatformUtils::Initialize/Terminate pair of routines
         multiple times in one process is now allowed.

But the application needs to guarantee that only one thread has entered either the
        method XMLPlatformUtils::Initialize() or the method XMLPlatformUtils::Terminate() at any
        one time.

If you are calling XMLPlatformUtils::Initialize() a number of times, and then follow with
         XMLPlatformUtils::Terminate() the same number of times, only the first XMLPlatformUtils::Initialize()
         will do the initialization, and only the last XMLPlatformUtils::Terminate() will clean up
         the memory.  The other calls are ignored.

To ensure all the memory held by the parser are freed, the number of XMLPlatformUtils::Terminate() calls
         should match the number of XMLPlatformUtils::Initialize() calls.

         Consider the following code snippets (for illustration simplicity the following
         sample code is not coded in try/catch clause):

<source>
// The XMLPlatformUtils::Initialize/Terminate calls are paired.
{
    // Initialize the parser
    XMLPlatformUtils::Initialize();

    SAXParser* parser = new SAXParser;
    parser->parse(xmlFile);
    delete parser;

    // Free all memory that was being held by the parser
    XMLPlatformUtils::Terminate();

    // Initialize the parser
    XMLPlatformUtils::Initialize();

    parser = new SAXParser;
    parser->parse(xmlFile);
    delete parser;

    // Free all memory that was being held by the parser
    XMLPlatformUtils::Terminate();
}
</source>

<source>
// calls XMLPlatformUtils::Initialize() three times
// then calls XMLPlatformUtils::Terminate() numerous times
{
    // Initialize the parser
    XMLPlatformUtils::Initialize();

    // The next two calls are no-op
    XMLPlatformUtils::Initialize();
    XMLPlatformUtils::Initialize();

    SAXParser* parser = new SAXParser;
    parser->parse(xmlFile);
    delete parser;

    // The first two XMLPlatformUtils::Terminate() calls are no-op
    XMLPlatformUtils::Terminate();
    XMLPlatformUtils::Terminate();

    // This third XMLPlatformUtils::Terminate() will free all memory that was being held by the parser
    XMLPlatformUtils::Terminate();

    // This extra fourth XMLPlatformUtils::Terminate() call is no-op.
    // However calling XMLPlatformUtils::Terminate() without a matching XMLPlatformUtils::Initialize()
    // is dangerous and should be avoided.
    XMLPlatformUtils::Terminate();
}
</source>

  </faq>

  <faq title="Why does my application crash or hang if XMLPlatformUtils::Initialize()/Terminate() pair is called more than once?">

    <q>Why does my application crash or hang if XMLPlatformUtils::Initialize()/Terminate() pair is called more than once?</q>

Please make sure you are using the &XercesCName; &XercesCVersion152; or up.

Earlier version of &XercesCName; does not allow XMLPlatformUtils::Initialize()/Terminate()
         pair to be called more than once or has a problem.

  </faq>

  <faq title="Why does my application crash after calling XMLPlatformUtils::Terminate()?">

    <q>Why does my application crash after calling XMLPlatformUtils::Terminate()?</q>

Please make sure the XMLPlatformUtils::Terminate() is the last &XercesCName; function to be called
         in your program.  NO explicit nor implicit &XercesCName; destructor (those local data that are
         destructed when going out of scope) should be called after XMLPlatformUtils::Terminate().

         For example consider the following code snippets which is incorrect
         (for illustration simplicity the following sample code is not coded in try/catch clause):

<source>
1: {
2:    XMLPlatformUtils::Initialize();
3:    DOMString c("hello");
4:    XMLPlatformUtils::Terminate();
5: }
</source>

The DOMString object "c" is destructed when going out of scope at line 5 before the closing
         brace.  As a result, DOMString destructor is called at line 5 after
         XMLPlatformUtils::Terminate() which is wrong.  Correct code should be:

<source>
1: {
2:    XMLPlatformUtils::Initialize();
2a:    {
3:           DOMString c("hello");
3a:    }
4:    XMLPlatformUtils::Terminate();
5: }
</source>

The extra pair of braces (line 2a and 3a) ensures that all implicit destructors are called
         before terminating &XercesCName;.

In addition the application also needs to guarantee that only one thread has entered either the
        method XMLPlatformUtils::Initialize() or the method XMLPlatformUtils::Terminate() at any
        one time.

  </faq>

  <faq title="I'm suddenly getting segfaults with Xerces-C 2.3.0;
    why might this be?">

    <q>I'm suddenly getting segfaults with Xerces-C 2.3.0;
        why might this be?</q>

The introduction of pluggable memory management into
        Xerces-C, one of the main features of 2.3.0, means that
        application writers have to be more conscious about
        destructors being invoked implicitly after a call to
        XMLPlatformUtils::Terminate().  For example, the
        following code is guaranteed to produce a segmentation
        fault under Xerces-C 2.3.0, while it happened to work
        under previous versions (in fact, this was how our
        SAXPrint sample was formerly written;
        try-catch blocks removed for brevity):

<source>
void myParsingFunction()
{
    XMLPlatformUtils::Initialize();
    SAXParser parser;
    //parser.various method calls
    XMLPlatformUtils::Terminate();
} // seg fault here!
</source>

The reason this will produce a segmentation fault is
        that any dynamic memory the SAXParser (or any other of
        Xerces's parsers) needs to allocate is now allocated
        by default by a static object owned by XMLPlatformUtils.
        When the XMLPlatformUtils::Terminate() call is made, this
        object is destroyed--and, consequently, so are all the
        objects that it directly created.  This includes all the
        objects dynamically allocated by the SAXParser.  When the
        parser object goes out of scope, its destructor is
        invoked, and this attempts to destroy all the objects
        that it created--which have of course just been destroyed
        by the static MemoryManager in XMLPlatformUtils.

        To avoid this, one must either explicitly scope the
        parser object inside calls to
        XMLPlatformUtils::Initialize() and
        XMLPlatformUtils::Terminate(), or dynamically allocate
        the parser object and destroy it explicitly before the
        call to XMLPlatformUtils::Terminate() is made.

Another way of producing segmentation faults--that again,
      unfortunately, was employed by some of our
      samples--is to have calls to XMLPlatformUtils::Terminate()
      in a catch block that catches any of Xerces's exceptions.
      Since the destructor of the exception will implicitly be
      invoked upon exit from the catch block, and since some of
      the exceptions' destructors call on Xerces's
      default memory manager to destroy dynamically-allocated
      objects, their destruction will provoke a segmentation
      fault even if a return statement is placed in the catch
      block since the default memory manager will no longer exist.
      This practice is now avoided in all our samples.

  </faq>

  <faq title="Is &XercesCName; thread-safe?">

    <q>Is &XercesCName; thread-safe?</q>

This is not a question that has a simple yes/no answer. Here are the
        rules for using &XercesCName; in a multi-threaded environment:

Within an address space, an instance of the parser may be used without
        restriction from a single thread, or an instance of the parser can be accessed
        from multiple threads, provided the application guarantees that only one thread
        has entered a method of the parser at any one time.

When two or more parser instances exist in a process, the instances can
        be used concurrently, without external synchronization. That is, in an
        application containing two parsers and two threads, one parser can be running
        within the first thread concurrently with the second parser running within the
        second thread.

The same rules apply to &XercesCName; DOM documents. Multiple document
        instances may be concurrently accessed from different threads, but any given
        document instance can only be accessed by one thread at a time.

DOMStrings allow multiple concurrent readers. All DOMString const
        methods are thread safe, and can be concurrently entered by multiple threads.
        Non-const DOMString methods, such as appendData(), are not thread safe and the application must guarantee that no other
        methods (including const methods) are executed concurrently with them.

The application also needs to guarantee that only one thread has entered either the
        method XMLPlatformUtils::Initialize() or the method XMLPlatformUtils::Terminate() at any
        one time.

  </faq>

  <faq title="I am seeing memory leaks in &XercesCName;. Are they real?">

    <q>I am seeing memory leaks in &XercesCName;. Are they real?</q>

The &XercesCName; library allocates and caches some commonly reused
        items. The storage for these may be reported as memory leaks by some heap
        analysis tools; to avoid the problem, call the function XMLPlatformUtils::Terminate() before your application exits. This will free all memory that was being
        held by the library.

For most applications, the use of Terminate() is optional. The system will recover all memory when the application
        process shuts down. The exception to this is the use of &XercesCName; from DLLs
        that will be repeatedly loaded and unloaded from within the same process. To
        avoid memory leaks with this kind of use, Terminate() must be called before unloading the &XercesCName; library

To ensure all the memory held by the parser are freed, the number of XMLPlatformUtils::Terminate() calls
         should match the number of XMLPlatformUtils::Initialize() calls.

If you are using XML4C where ICU is used, you may call ICU function u_cleanup() to clean up
         ICU static data.  Please see <jump href="http://oss.software.ibm.com/icu/">ICU documentation</jump>
         for details.

  </faq>

  <faq title="I find memory leaks in &XercesCName;. How do I eliminate it?">

    <q>I find memory leaks in &XercesCName;. How do I eliminate it?</q>

The "leaks" that are reported through a leak-detector or heap-analysis
        tools aren't really leaks in most application, in that the memory usage does
        not grow over time as the XML parser is used and re-used.

What you are seeing as leaks are actually lazily evaluated data
        allocated into static variables. This data gets released when the application
        ends. You can make a call to XMLPlatformUtil::terminate() to release all the lazily allocated variables before you exit your
        program.

To ensure all the memory held by the parser are freed, the number of XMLPlatformUtils::Terminate() calls
         should match the number of XMLPlatformUtils::Initialize() calls.

If you are using XML4C where ICU is used, you may call ICU function u_cleanup() to clean up
         ICU static data.  Please see <jump href="http://oss.software.ibm.com/icu/">ICU documentation</jump>
         for details.

  </faq>

  <faq title="Can &XercesCName; create an XML skeleton based on a DTD">

    <q>Is there a function that I have totally missed that creates
      an XML file from a DTD, (obviously with the values missing, a skeleton, as it
      were)?</q>

No.  This is not supported.

  </faq>

  <faq title="Can I use &XercesCName; to perform write validation">

    <q>Can I use &XercesCName; to perform "write validation" (which is having an
      appropriate Grammar and being able to add elements to the DOM whilst validating
      against the grammar)?</q>

No.  This is not supported.

The best you can do for now is to create the DOM document, write it back
        as XML and re-parse it.

  </faq>

  <faq title="Can I validate the data contained in a DOM tree?">

    <q>Is there a facility in &XercesCName; to validate the data contained in a
      DOM tree? That is, without saving and re-parsing the source document?</q>

No. The best option for now is to generate XML source from the DOM and feed that back
        into the parser.

  </faq>

  <faq title="How to write out a DOM tree into a string or an XML file?">
     <q>How to write out a DOM tree into a string or an XML file?</q>

Please make sure you are using &XercesCName; &XercesCVersion; or up.

You can use
         the DOMWriter::writeToString, or DOMWriter::writeNode to serialize a DOM tree.
         Please refer to the sample DOMPrint or the API documentation for more details of
         DOMWriter.

  </faq>

  <faq title="Why does DOMNode::cloneNode() not clone the pointer assigned to a DOMNode via DOMNode::setUserData()?">
    <q>Why does DOMNode::cloneNode() not clone the pointer assigned to a DOMNode via DOMNode::setUserData()?</q>

&XercesCName; supports the DOMNode::userData specified
      in <jump href="http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3A0ED0A4">
      the DOM level 3 Node interface</jump>.  As
      is made clear in the description of the behaviour of
      cloneNode(), userData that has been set on the
      Node is not cloned.  Thus, if the userData is to be copied
      to the new Node, this copy must be effected manually.
      Note further that the operation of importNode()
      is specified similarly.

  </faq>

  <faq title="How are entity reference nodes handled in DOM?">

    <q>How are entity reference nodes handled in DOM?</q>

If you are using the native DOM classes, the function setCreateEntityReferenceNodes
        controls how entities appear in the DOM tree. When
        setCreateEntityReferenceNodes is set to true (the default), an occurrence of an
        entity reference in the XML document will be represented by a subtree with an
        EntityReference node at the root whose children represent the entity expansion.
        Entity expansion will be a DOM tree representing the structure of the entity
        expansion, not a text node containing the entity expansion as text.

If setCreateEntityReferenceNodes is false, an entity reference in the XML
        document is represented by only the nodes that represent the entity expansion.
        The DOM tree will not contain any entityReference nodes.

  </faq>

  <faq title="What kinds of URLs are currently supported in &XercesCName;?">

    <q>What kinds of URLs are currently supported in &XercesCName;?</q>

The XMLURL class provides for limited URL support. It understands the file://, http://, and ftp:// URL types, and is capable or parsing them into their constituent
        components, and normalizing them. It also supports the commonly required action
        of conglomerating a base and relative URL into a single URL. In other words, it
        performs the limited set of functions required by an XML parser.

Another thing that URLs commonly do are to create an input stream that
        provides access to the entity referenced. The parser, as shipped, only supports
        this functionality on URLs in the form file:/// and file://localhost/, i.e. only when the URL refers to a local file.

You may enable support for HTTP and FTP URLs by implementing and
        installing a NetAccessor object. When a NetAccessor object is installed, the
        URL class will use it to create input streams for the remote entities referred
        to by such URLs.

  </faq>

  <faq title="How can I add support for URLs with HTTP/FTP protocols?">

    <q>How can I add support for URLs with HTTP/FTP protocols?</q>

Support for the http: protocol is now included by default on all
        platforms.

To address the need to make remote connections to resources specified
        using additional protocols, ftp for example, &XercesCName; provides the NetAccessor interface. The header file is src/xercesc/util/XMLNetAccessor.hpp. This interface allows you to plug in your own implementation of URL
        networking code into the &XercesCName; parser.

  </faq>

  <faq title="Can I use &XercesCName; to parse HTML?">

    <q>Can I use &XercesCName; to parse HTML?</q>

Yes, but only if the HTML follows the rules given in the
        <jump href="http://www.w3.org/TR/REC-xml">XML specification</jump>. Most HTML,
        however, does not follow the XML rules, and will generate XML well-formedness
        errors.

  </faq>

  <faq title="I keep getting an error: "invalid UTF-8 character". What's wrong?">

    <q>I keep getting an error: "invalid UTF-8 character". What's wrong?</q>

Most commonly, the XML encoding = declaration is either incorrect or missing. Without a declaration, XML
        defaults to the use utf-8 character encoding, which is not compatible with the
        default text file encoding on most systems.

The XML declaration should look something like this:

<?xml version="1.0" encoding="iso-8859-1"?>

Make sure to specify the encoding that is actually used by file. The
        encoding for "plain" text files depends both on the operating system and the
        locale (country and language) in use.

Another common source of problems is that some characters are not
        allowed in XML documents, according to the XML spec. Typical disallowed
        characters are control characters, even if you escape them using the Character
        Reference form. See the <jump href="http://www.w3.org/TR/REC-xml#charsets">XML
        spec</jump>, sections 2.2 and 4.1 for details. If the parser is generating an Invalid character (Unicode: 0x???) error, it is very likely that there's a character in there that you
        can't see. You can generally use a UNIX command like "od -hc" to find it.

  </faq>

  <faq title="What encodings are supported by Xerces-C / XML4C?">

    <q>What encodings are supported by Xerces-C / XML4C?</q>

Xerces-C has intrinsic support for ASCII, UTF-8, UTF-16 (Big/Small
        Endian), UCS4 (Big/Small Endian), EBCDIC code pages IBM037, IBM1047 and IBM1140
        encodings, ISO-8859-1 (aka Latin1) and Windows-1252. This means that it can
        parse input XML files in these above mentioned encodings.

XML4C -- the version of Xerces-C available from IBM -- combines Xerces-C
         and <jump href="http://oss.software.ibm.com/icu/">
         International Components for Unicode (ICU)</jump> and
         extends the encoding support to over 100 different encodings that are allowed
         by ICU.  In particular, all the encodings registered with the
         <jump href="http://www.iana.org/assignments/character-sets">
         Internet Assigned Numbers Authority (IANA) </jump> are supported in XML4C.

Some implementations or ports of Xerces-C provide support for
        additional encodings. The exact set will depend on the supplier of the parser
        and on the character set transcoding services in use.

  </faq>

  <faq   title="What character encoding should I use when creating XML documents?">

    <q>What character encoding should I use when creating XML documents?</q>

The best choice in most cases is either utf-8 or utf-16. Advantages of
        these encodings include:

The best portability. These encodings are more widely supported by
          XML processors than any others, meaning that your documents will have the best
          possible chance of being read correctly, no matter where they end up.

Full international character support. Both utf-8 and utf-16 cover the
          full Unicode character set, which includes all of the characters from all major
          national, international and industry character sets.

Efficient. utf-8 has the smaller storage requirements for documents
          that are primarily composed of characters from the Latin alphabet. utf-16 is
          more efficient for encoding Asian languages. But both encodings cover all
          languages without loss.

The only drawback of utf-8 or utf-16 is that they are not the native
        text file format for most systems, meaning that common text file editors and
        viewers can not be directly used.

A second choice of encoding would be any of the others listed in the
        table above. This works best when the xml encoding is the same as the default
        system encoding on the machine where the XML document is being prepared,
        because the document will then display correctly as a plain text file. For UNIX
        systems in countries speaking Western European languages, the encoding will
        usually be iso-8859-1.

The versions of Xerces distributed by IBM, both C and Java (known
        respectively as XML4C and XML4J), include all of the encodings listed in the
        above table, on all platforms.

A word of caution for Windows users: The default character set on
        Windows systems is windows-1252, not iso-8859-1. While &XercesCName; does
        recognize this Windows encoding, it is a poor choice for portable XML data
        because it is not widely recognized by other XML processing tools. If you are
        using a Windows-based editing tool to generate XML, check which character set
        it generates, and make sure that the resulting XML specifies the correct name
        in the encoding="..." declaration.

  </faq>

  <faq title="Is EBCDIC supported?">

    <q>Is EBCDIC supported?</q>

Yes, &XercesCName; supports EBCDIC with the ibm1140, ibm037 and ibm1047 encodings.
        When creating EBCDIC encoded XML data, the preferred encoding is ibm1140. The ibm037 encoding,
        and its alternate name, ebcdic-cp-us, is almost the same as ibm1140, but
        it lacks the Euro symbol.

These three encodings, ibm1140, ibm037 and ibm1047, are available on both
        Xerces-C and IBM XML4C, on all platforms.

On IBM System 390, XML4C also supports three alternative forms,
        ibm037-s390, ibm1140-s390, and ibm1047-s390. These are similar to the base ibm037, ibm1140, and ibm1047
        encodings, but with alternate mappings of the EBCDIC new-line character, which
        allows them to appear as normal text files on System 390. These encodings are
        not supported on other platforms, and should not be used for portable data.

XML4C on System 390 and AS/400 also provides additional EBCDIC
        encodings, including those for the character sets of different countries. The
        exact set supported will be platform dependent, and these encodings are not
        recommended for portable XML data.

  </faq>

  <faq title="Why does deleting a transcoded string result in assertion on windows?">
    <q>Why does deleting a transcoded string result in assertion on windows?</q>

Both your application program and the &XercesCName; DLL must use the same *DLL* version of the
         runtime library.  If either statically links to the runtime library, the
		 problem will still occur.

For example, for a Win32/VC6 build, the runtime library build setting MUST
		 be "Multithreaded DLL" for release builds and "Debug Multithreaded DLL" for
		 debug builds.

Or for example for a Win32/BCB6 build, application need to switch to Multithreaded
         runtime to avoid such memory access violation.

To bypass such problem, instead of calling operator delete[] directly, you can use the
         provided function XMLString::release to delete any string that was allocated by the parser.
         This will ensure the string is allocated and deleted by the same DLL and such assertion
         problem should be resolved.

  </faq>

  <faq title="How do I transcode to/from something besides the local code page?">
    <q>How do I transcode to/from something besides the local code page?</q>

XMLString::transcode() will transcode from XMLCh to the local code page, and
         other APIs which take a char* assume that the source text is in the local
         code page. If this is not true, you must transcode the text yourself. You
         can do this using local transcoding support on your OS, such as Iconv on
         Unix or IBM's ICU package. However, if your transcoding needs are simple,
         you can achieve some better portability by using the &XercesCName; parser's
         transcoder wrappers. You get a transcoder like this:

            Call XMLPlatformUtils::fgTransServer->MakeNewTranscoderFor() and provide
            the name of the encoding you wish to create a transcoder for. This will
            return a transcoder to you, which you own and must delete when you are
            through with it.

           NOTE: You must provide a maximum block size that you will pass to the transcoder
           at one time, and you must pass blocks of characters of this count or smaller when
           you do your transcoding. The reason for this is that this is really an
           internal API and is used by the parser itself to do transcoding. The parser
           always does transcoding in known block sizes, and this allows transcoders to
           be much more efficient for internal use since it knows the max size it will
           ever have to deal with and can set itself up for that internally. In
           general, you should stick to block sizes in the 4 to 64K range.

            The returned transcoder is something derived from XMLTranscoder, so they
            are all returned to you via that interface.

            This object is really just a wrapper around the underlying transcoding
            system actually in use by your version of Xerces, and does whatever is
            necessary to handle differences between the XMLCh representation and the
            representation used by that underlying transcoding system.

            The transcoder object has two primary APIs, transcodeFrom() and
            transcodeTo(). These transcode between the XMLCh format and the encoding you
            indicated.

            These APIs will transcode as much of the source data as will fit into the
            outgoing buffer you provide. They will tell you how much of the source they
            ate and how much of the target they filled. You can use this information to
            continue the process until all source is consumed.

            char* data is always dealt with in terms of bytes, and XMLCh data is
            always dealt with in terms of characters. Don't mix up which you are dealing
            with or you will not get the correct results, since many encodings don't
            have a one to one relationship of characters to bytes.

            When transcoding from XMLCh to the target encoding, the transcodeTo()
            method provides an 'unrepresentable flag' parameter, which tells the
            transcoder how to deal with an XMLCh code point that cannot be converted
            legally to the target encoding, which can easily happen since XMLCh is
            Unicode and can represent thousands of code points. The options are to use a
            default replacement character (which the underlying transcoding service will
            choose, and which is guaranteed to be legal for the target encoding), or to
            throw an exception.

Here is an example:

<source>
// create an XMLTranscoder that is able to transcode between Unicode and Big5
// ASSUMPTION: assumes your underlying transcoding utility supports this encoding Big5
XMLTranscoder* t =
    XMLPlatformUtils::fgTransService->makeNewTranscoderFor("Big5", failReason, 16*1024, MemoryManager);

// source string is in Unicode, wanna to transcode to Big5
t->transcodeTo(source_unicode, length, result_Big5, length, charsEaten, XMLTranscoder::UnRep_Throw );

// source string in Big5, wanna to transcode to Unicode
t->transcodeFrom(source_Big5, length, result_unicode, length, bytesEaten, (unsigned char*)charSz);
</source>

  </faq>

  <faq title="Why does setProperty not work?">

    <q>Why does setProperty not work?</q>

The function SAX2XMLReader::setProperty(const XMLCh* const name, void* value)
         and DOMBuilder::setProperty(const XMLCh* const name, void* value)
         takes a void pointer for the property value.  Application is required to initialize this void pointer
         to a correct type.  See <jump href="program-sax2.html#SAX2Properties">SAX2 Programming Guide</jump>
         and <jump href="program-dom.html#DOMBuilderProperties">DOM Programming Guide</jump>
         to learn exactly what type of property value that each property expects for processing.
         Passing a void pointer that was initialized with a wrong type will lead to unexpected result.

  </faq>

  <faq title="Why does getProperty not work?">

    <q>Why does getProperty not work?</q>

The function void* SAX2XMLReader::getProperty(const XMLCh* const name)
         and void* DOMBuilder::getProperty(const XMLCh* const name)
         returns a void pointer for the property value.  See
         <jump href="program-sax2.html#SAX2Properties">SAX2 Programming Guide</jump> and
         exactly what type of object each property returns.

The parser owns the returned pointer.  The memory allocated for
         the returned pointer will be destroyed when the parser is deleted.
         To ensure accessibility of the returned information after the parser
         is deleted, callers need to copy and store the returned information
         somewhere else; otherwise you may get unexpected result.  Since the returned
         pointer is a generic void pointer, see
         <jump href="program-sax2.html#SAX2Properties">SAX2 Programming Guide</jump> and
         <jump href="program-dom.html#DOMBuilderProperties">DOM Programming Guide</jump> to learn
         exactly what type of property value each property returns for replication.

  </faq>

  <faq title="Why does the parser still try to locate the DTD even validation is turned off
       and how to ignore external DTD reference?">

    <q>Why does the parser still try to locate the DTD even validation is turned off
       and how to ignore external DTD reference?</q>

When DTD is referenced, the parser will try to read it, because DTDs can
         provide a lot more information than just validation. It defines entities and
         notations, external unparsed entities, default attributes, character
         entities, etc... So it will always try to read it if present, even if
         validation is turned off.

To ignore the DTD, with &XercesCName; &XercesCVersion; or up, you can call
         setLoadExternalDTD(false) (or
         setFeature(XMLUni::fgXercesLoadExternalDTD, false)
         to disable the loading of external DTD.   The parser will then ignore
         any external DTD completely if the validationScheme is set to Val_Never.

Note: This flag is ignored if the validationScheme is set to Val_Always or Val_Auto.

To ignore the DTD in earlier version of &XercesCName;, the
         only way to get around this is to install an EntityResolver
         (see the Redirect sample for an example of how this is done), and reset the
         DTD file to "".

  </faq>

  <faq title="Why do I get segmentation fault when running on Redhat Linux?">

    <q>Why do I get segmentation fault when running on Redhat Linux?</q>

There were some problems with Redhat Linux 7.x with C++ exception handling across shared
         libraries.  More details can be found
         <jump href="http://rhn.redhat.com/errata/RHBA-2002-055.html">here</jump>.
         Please try to upgrade your Redhat Linux gcc to the latest patch level and see if it helps.

  </faq>

  <faq title="Why does the XML data generated by the DOMWriter does not match my original XML input?">

    <q>Why does the XML data generated by the DOMWriter does not match my original XML input?</q>

If you parse an xml document using XercesDOMParser or DOMBuilder and pass such DOMNode
         to DOMWriter for serialization, you may not get something that is exactly the same
         as the original XML data.   The parser may have done normalization, end of line conversion,
         or has expanded the entity reference as per the XML 1.0 spec, 4.4 XML Processor Treatment of
         Entities and References.   From DOMWriter perspective, it does not know what the original
         string was, all it sees is a processed DOMNode generated by the parser.
         But since the DOMWriter is supposed to generate something that is parsable if sent
         back to the parser, it will not print the DOMNode node value as is.    The DOMWriter
         may do some "touch up" to the output data for it to be parsable.

See <jump href="program-dom.html#DOMWriterEntityRef">How does DOMWriter handle built-in entity
         Reference in node value?</jump> to understand further how DOMWriter touches up the entity reference.

  </faq>

  <faq title="Why does my application crash when deleting the parser after releasing a document?">

    <q>Why does my application crash when deleting the parser after releasing a document?</q>

In most cases, the parser handles deleting documents when the parser gets deleted.  However, if an application
         needs to release a document, it shall adopt the document before releasing it, so that the parser
         knows that the ownership of this particular document is transfered to the application and will not
         try to delete it once the parser gets deleted.

<source>
XercesDOMParser *parser = new XercesDOMParser;
...
try
{
    parser->parse(gXmlFile);
}
catch ()
{
...
}
DOMNode *doc = parser->getDocument();
...
parser->adoptDocument();
doc->release();
...
delete parser;
</source>

The alternative to release document is to call parser's resetDocumentPool(), which releases
         all the documents parsed.

  </faq>

  <faq title="Why do we have two versions of some XMLString methods (one with memory manager and one without)?">

    <q>Why do we have two versions of some XMLString methods (one with memory manager and one without)?</q>

With the introduction of the configurable memory manager, we didn't want to break users by
         changing the signature of the existing methods (for example, transcode and replicate). Also,
         we did not want to provide a default memory
         manager as it would introduce a side effect with users experiencing some strange core dumps.
         The latter will occur when the scope of the string allocated is beyond that of
         XMLPlatformUtils::Terminate (i.e. a string is allocated using the default memory manager
         which is deleted when XMLPlatformUtils::Terminate is called, but the allocated string is
         deleted later). We plan to deprecate the methods without a memory manager in a later release.

  </faq>

</faqs>


text:
#import <Foundation/Foundation.h>
#import "NTGMemberArticle.h"
#import "NTGPage.h"

/**
 * Entity - 个人中心  文章详情
 *
 * @author wangwei
 * @version 1.0
 */
@interface NTGMemberArticleContent : NSObject

/** 文章 */
@property(nonatomic,strong) NTGMemberArticle *article;

/** 用户评论 NTGPage中content数组的元素为 :MemberCommentBean */
@property(nonatomic,strong) NTGPage *memberComments;

@end

redpajama_set_name: RedPajamaGithub


text:
package com.xth.intelligentassistant.main;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.xth.intelligentassistant.R;
import com.xth.intelligentassistant.db.Device;
import com.xth.intelligentassistant.db.OperateDB;
import com.xth.intelligentassistant.internetapi.OneNet;
import com.xth.intelligentassistant.util.Constant;
import com.xth.intelligentassistant.util.LogUtil;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by XTH on 2017/5/31.
 */

public class ExpandableListFragment extends Fragment implements ExpandableListView.OnGroupClickListener, ExpandableListView.OnChildClickListener {

    private int groupPosition;

    private Context context;
    private Map<String, Object> expandMenuItemMap;//子项列表内容
    private List<Map<String, Object>> groupList;//父项列表
    private ArrayList<List<Map<String, Object>>> groupChildLists;//子项列表
    private MyBaseExpandableListAdapter adapter;
    private ExpandableListView expandableListView;

    private PopupList popupList;
    private List<String> popupMenuItemList;

    public void setGroupList(List<Map<String, Object>> groupList) {
        this.groupList = groupList;
    }

    public List<Map<String, Object>> getGroupList() {
        return groupList;
    }

    public int getGroupPosition() {
        return groupPosition;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        groupChildLists = new ArrayList<>();
        for (int i = 0; i < groupList.size(); i++) {
            List<Map<String, Object>> expandMenuItemList = new ArrayList<>();
            List<Device> deviceList = DataSupport.findAll(Device.class);
            boolean flag = false;
            for (Device device : deviceList) {
                if (groupList.get(i).get(Constant.SWIPE_SENCE_KEY).toString().equals(device.getSenceName())) {
                    expandMenuItemMap = new HashMap<String, Object>();
                    expandMenuItemMap.put(Constant.SWIPE_DIVICE_KEY, device.getDeviceName());
                    expandMenuItemList.add(expandMenuItemMap);//子项列表添加内容
                    flag = true;
                } else {
                    if (flag) {
                        break;//检测到父项列出子项之后直接退出for循环
                    }
                }
            }
            groupChildLists.add(expandMenuItemList);
        }
    }

    private void setPopupListView() {
        popupMenuItemList = new ArrayList<>();
        popupMenuItemList.add(getString(R.string.update));
        popupMenuItemList.add(getString(R.string.delete));
        popupList = new PopupList(context);
        popupList.setTextSize(popupList.dp2px(30));
        popupList.bind(expandableListView, popupMenuItemList, new PopupList.PopupListListener() {
            @Override
            public boolean showPopupList(View adapterView, View contextView, int groupPos, int childPos) {
                return true;
            }

            @Override
            public void onPopupListClick(View contextView, int groupPos, int childPos, int position) {
                switch (position) {
                    case Constant.MODIFY://修改
                        expandMenuItemMap = groupChildLists.get(groupPos).get(childPos);
                        editName(expandMenuItemMap, groupPos, childPos);
                        break;
                    case Constant.DELETE://删除
                        new OneNet().deleteDevice((String) groupList.get(groupPos).get(Constant.SWIPE_SENCE_KEY), (String) groupChildLists.get(groupPos).get(childPos).get(Constant.SWIPE_DIVICE_KEY));
                        groupChildLists.get(groupPos).remove(childPos);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });
    }

    private void editName(final Map<String, Object> expandMenuItemMap, final int groupPos, final int childPos) {
        View view = View.inflate(context, R.layout.alert_dialog_layout, null);
        final EditText alertDialogEdit = (EditText) view.findViewById(R.id.alert_dialog_edit);
        final String oldName = (String) expandMenuItemMap.get(Constant.SWIPE_DIVICE_KEY);
        LogUtil.d(groupPos+":::::"+childPos+"::"+expandMenuItemMap.get(Constant.SWIPE_DIVICE_KEY));
        alertDialogEdit.setText(oldName);
        alertDialogEdit.setSelection(oldName.length());//将光标移至文字末尾
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(Constant.EDIT_DEVICE_NAME);//修改设备名称
        builder.setPositiveButton(Constant.CONFIRM, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String s = alertDialogEdit.getText().toString().replaceAll("\\s", "");
                if(s.equals(oldName)){

                }else if (!"".equals(s)) {
                    if (OperateDB.isHaveInDB((String) groupList.get(groupPosition).get(Constant.SWIPE_SENCE_KEY), s)!=null) {
                        Toast.makeText(context, Constant.ERROR_DEVICE_NAME, Toast.LENGTH_SHORT).show();
                    } else {
                        new OneNet().updateDevice((String) groupList.get(groupPos).get(Constant.SWIPE_SENCE_KEY),oldName,s);
                        expandMenuItemMap.put(Constant.SWIPE_DIVICE_KEY, s);
                        List<Map<String, Object>> expandMenuItemList = groupChildLists.get(groupPos);
                        expandMenuItemList.set(childPos, expandMenuItemMap);//子项列表中的子列表内容更新
                        groupChildLists.set(groupPos, expandMenuItemList);//子项列表更新其子列表
                        for (List<Map<String, Object>> list : groupChildLists) {
                            for (Map<String, Object> map : list) {
                                LogUtil.d((String) map.get(Constant.SWIPE_DIVICE_KEY));
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    Toast.makeText(context, Constant.ERROR_EMPTY_NAME, Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.setNegativeButton(Constant.CANCEL, null);
        AlertDialog tempDialog = builder.create();
        tempDialog.setView(view, 0, 0, 0, 0);
        /** 3.自动弹出软键盘 **/
        tempDialog.setOnShowListener(new AlertDialog.OnShowListener() {

            @Override
            public void onShow(DialogInterface dialog) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(alertDialogEdit, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        tempDialog.show();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.expand_list_view, container, false);
        expandableListView = (ExpandableListView) view.findViewById(R.id.main_expand_list_view);
        adapter = new MyBaseExpandableListAdapter(context, groupList, groupChildLists);
        expandableListView.setAdapter(adapter);
        expandableListView.setOnGroupClickListener(this);
        expandableListView.setOnChildClickListener(this);
        setPopupListView();
        return view;
    }

    //主列表为空,不能选择或者张开主列表;子列表应该区分开
    public void expandListViewAddItem(String key, Object value) {
        OperateDB.addName(new Device(), (String) groupList.get(groupPosition).get(Constant.SWIPE_SENCE_KEY), (String) value);
        expandMenuItemMap = new HashMap<String, Object>();
        expandMenuItemMap.put(key, value);
        groupChildLists.get(groupPosition).add(expandMenuItemMap);//子项列表添加内容

        adapter.notifyDataSetChanged();
        expandableListView.expandGroup(groupPosition);
        expandableListView.smoothScrollToPosition(groupPosition);
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        this.groupPosition = groupPosition;//获取父项的id
        return false;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        //groupPosition,childPosition,id 由0开始,childPosition和id值一样
        LogUtil.d("onChildClick" + groupPosition + "," + childPosition + "," + id);
        return false;
    }
}


text:
define([
  'controllers/module'
], function( exports ) {
  'use strict';
  exports.controller( 'ArticleCtrl', [ '$scope', '$rootScope', '$routeParams', '$location', 'article',
    function( $scope, $rootScope, $routeParams, $location, Article ) {
      var wikiApi,
          errorObj;

      errorObj = {
        content: {
          html: 'Sorry, there was an error retrieving your article',
          title: 'Error'
        }
      };

      $rootScope.page = 'article';

      $scope.$on( '$locationChangeStart', function() {
        $rootScope.$emit( 'article:changing' );
        $rootScope.articleLoaded = false;
      });

      $scope.wikiBaseHref = 'http://' + $routeParams.wiki + '.wikia.com/';
      if ($rootScope.wiki != $routeParams.wiki) {
        $rootScope.$emit('article:wikiChanging', $routeParams.wiki);
        $rootScope.wiki = $routeParams.wiki;
      }

      wikiApi = $scope.wikiBaseHref + 'api.php';
      $scope.article = null;
      $rootScope.headings = [];

      Article.get( wikiApi, $routeParams.name, function( data ) {
        if ( typeof data.content === 'object') {
          if ( data.content.redirect) {
            return $location.path( '/article/' + $routeParams.wiki + '/' + data.content.html );
          }
          $scope.article = data;
          $rootScope.$emit( 'article:changing' );
        } else {
          $scope.article = errorObj;
        }
      });

      $scope.$watch( 'article', function( newVal, oldVal ) {
        if ( newVal ) {
          var title = newVal.content.title;
          $scope.articleContent = newVal.content.html;
          $rootScope.$emit( 'article:newTitle', title );
          $rootScope.$emit( 'article:changed', newVal );
          if ( title && title !== 'Error' ) $rootScope.articleLoaded = true;
        }
      });
  }]);
});


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <log4cxx/logger.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/simplelayout.h>
#include <log4cxx/logmanager.h>
#include <iostream>
#include <locale.h>
#include <cstring>
#include <cstdio>
#ifndef WIN32
#include <stdint.h>
#endif

using namespace log4cxx;
using namespace log4cxx::helpers;

/**
 *   Configures console appender.
 *   @param err if true, use stderr, otherwise stdout.
 */
static void configure(bool err) {
    log4cxx::ConsoleAppenderPtr appender(new log4cxx::ConsoleAppender());
    if (err) {
        appender->setTarget(LOG4CXX_STR("System.err"));
    }
    log4cxx::LayoutPtr layout(new log4cxx::SimpleLayout());
    appender->setLayout(layout);
    log4cxx::helpers::Pool pool;
    appender->activateOptions(pool);
    log4cxx::Logger::getRootLogger()->addAppender(appender);
    LogManager::getLoggerRepository()->setConfigured(true);
}

/**
 *   Program to test compatibility of C RTL, C++ STL and log4cxx output to standard
 *       output and error streams.
 *
 *    See bug LOGCXX_126.
 *
 *
 */
int main(int argc, char** argv)
{
    setlocale(LC_ALL, "");
    if (argc <= 1) {
        puts("Console test program\nUsage: console [-err] [ puts | putws | cout | wcout | configure | log | wide | byte ]*\n");
    }
    bool configured = false;
    bool err = false;
    for (int i = 1; i < argc; i++) {
        if (strcmp("-err", argv[i]) == 0) {
            err = true;
        } else if (strcmp("puts", argv[i]) == 0) {
            fputs("Hello, fputs\n", err ? stderr : stdout);
#if LOG4CXX_WCHAR_T_API
        } else if (strcmp("putws", argv[i]) == 0) {
            fputws(L"Hello, fputws\n", err ? stderr : stdout);
#endif
        } else if (strcmp("cout", argv[i]) == 0) {
            if (err) {
                std::cerr << "Hello, cout" << std::endl;
            } else {
                std::cout << "Hello, cout" << std::endl;
            }
        } else if (strcmp("wcout", argv[i]) == 0) {
            if (err) {
            #if LOG4CXX_HAS_STD_WCOUT
                std::wcerr << L"Hello, wcout" << std::endl;
            #else
                std::cerr << "Log4cxx has not wcout" << std::endl;
            #endif
            } else {
            #if LOG4CXX_HAS_STD_WCOUT
                std::wcout << L"Hello, wcout" << std::endl;
            #else
                std::cout << "Log4cxx has not wcout" << std::endl;
            #endif
            }
        } else if (strcmp("configure", argv[i]) == 0) {
            configure(err);
            configured = true;
        } else if (strcmp("log", argv[i]) == 0) {
            if (!configured) {
                configure(err);
                configured = true;
            }
            log4cxx::Logger::getRootLogger()->info("Hello, log4cxx");
#if LOG4CXX_WCHAR_T_API
        } else if (strcmp("wide", argv[i]) == 0) {
            fwide(err ? stderr : stdout, 1);
        } else if (strcmp("byte", argv[i]) == 0) {
            fwide(err ? stderr : stdout, -1);
#endif
        } else {
            fputs("Unrecognized option: ", stderr);
            fputs(argv[i], stderr);
            fputs("\n", stderr);
            fflush(stderr);
        }
    }
    return 0;
}


text:
        {{ 'TRANSLATION_LANGUAGE' | translate | uppercase }}

                {{ lang.code | langName | translate }}

                    - {{ 'THIS_LANGUAGE_IS_DISABLED' | translate }}

                        {{ 'NO_TRANSLATION' | translate }}


text:
class GURL;

namespace phantomium {

// An application which implements a simple headless browser.
class PhantomiumPage : public headless::HeadlessWebContents::Observer,
                       public headless::inspector::ExperimentalObserver,
                       public headless::page::ExperimentalObserver {
 public:
  PhantomiumPage();
  ~PhantomiumPage() override;

  virtual void OnStart(HeadlessBrowser* browser);

  HeadlessDevToolsClient* devtools_client() const {
    return devtools_client_.get();
  }

 private:
  // HeadlessWebContents::Observer implementation:
  void DevToolsTargetReady() override;
  void OnTargetCrashed(const inspector::TargetCrashedParams& params) override;

  // page::Observer implementation:
  void OnLoadEventFired(const page::LoadEventFiredParams& params) override;

  // network::Observer implementation:
  void OnRequestIntercepted(
      const network::RequestInterceptedParams& params) override;

  virtual void Shutdown();

  void FetchTimeout();

  void PollReadyState();

  void OnReadyState(std::unique_ptr<runtime::EvaluateResult> result);

  void OnPageReady();

  void PrintToPDF();

  void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result);

  void WriteFile(const std::string& switch_string,
                 const std::string& default_file_name,
                 const std::string& base64_data);
  void OnFileOpened(const std::string& decoded_data,
                    const base::FilePath file_name,
                    base::File::Error error_code);
  void OnFileWritten(const base::FilePath file_name,
                     const size_t length,
                     base::File::Error error_code,
                     int write_result);
  void OnFileClosed(base::File::Error error_code);

  bool RemoteDebuggingEnabled() const;

  GURL url_;
  HeadlessBrowser* browser_;  // Not owned.
  std::unique_ptr<HeadlessDevToolsClient> devtools_client_;
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
  HeadlessWebContents* web_contents_;
  HeadlessBrowserContext* browser_context_;
#endif
  bool processed_page_ready_;
  scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
  std::unique_ptr<base::FileProxy> file_proxy_;
  std::unique_ptr<DeterministicDispatcher> deterministic_dispatcher_;
  base::WeakPtrFactory<HeadlessShell> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(HeadlessShell);
};

}  // namespace phantomium

#endif  // PHANTOMIUM_PAGE_H_


text:
ActiveRecord::Schema.define(version: 20160118144207) do

  create_table "candidates", force: :cascade do |t|
    t.string "name",        limit: 255,   null: false
    t.text   "description", limit: 65535, null: false
    t.string "image",       limit: 255,   null: false
  end

  create_table "votes", force: :cascade do |t|
    t.string   "subject",          limit: 255, null: false
    t.integer  "ammount",          limit: 4,   null: false
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.integer  "ip",               limit: 8
    t.integer  "candidate_id",     limit: 4
    t.string   "city_name",        limit: 255
    t.string   "real_region_name", limit: 255
    t.string   "country_name",     limit: 255
    t.string   "latitude",         limit: 255
    t.string   "longitude",        limit: 255
  end

  add_index "votes", ["candidate_id"], name: "index_votes_on_candidate_id", using: :btree
  add_index "votes", ["subject"], name: "index_votes_on_subject", using: :btree

end


text:
package com.github.dnvriend.dao

import akka.NotUsed
import akka.persistence.jdbc.config.JournalConfig
import akka.persistence.jdbc.dao.JournalDao
import akka.persistence.{ AtomicWrite, PersistentRepr }
import akka.serialization.Serialization
import akka.stream.Materializer
import akka.stream.scaladsl.{ Flow, Source }
import com.github.dnvriend.CounterActor.{ Decremented, Incremented }
import com.github.dnvriend.dao.CounterJournalTables.{ DecrementedRow, EventType, IncrementedRow, JournalRow }
import slick.driver.JdbcProfile
import slick.jdbc.JdbcBackend

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.{ Failure, Success, Try }

class CounterJournalDao(db: JdbcBackend#Database, val profile: JdbcProfile, journalConfig: JournalConfig, serialization: Serialization)(implicit ec: ExecutionContext, mat: Materializer) extends JournalDao with CounterJournalTables {

  import profile.api._

  override def delete(persistenceId: String, toSequenceNr: Long): Future[Unit] = ???

  override def messages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long): Source[Try[PersistentRepr], NotUsed] = {
    val messagesQuery = JournalTable
      .filter(_.persistenceId === persistenceId)
      .filter(_.sequenceNumber >= fromSequenceNr)
      .filter(_.sequenceNumber <= toSequenceNr)
      .sortBy(_.sequenceNumber.asc)
      .take(max)
    Source.fromPublisher(db.stream(messagesQuery.result))
      .mapAsync(1) {
        case JournalRow(pid, seqno, EventType.Incremented, _, _) ⇒
          db.run(IncrementedTable.filter(_.persistenceId === pid).filter(_.sequenceNumber === seqno).result)
            .map(_.head)
            .map(row ⇒ Success(PersistentRepr(Incremented(row.incrementedBy), seqno)))
        case JournalRow(pid, seqno, EventType.Decremented, _, _) ⇒
          db.run(DecrementedTable.filter(_.persistenceId === pid).filter(_.sequenceNumber === seqno).result)
            .map(_.head)
            .map(row ⇒ Success(PersistentRepr(Decremented(row.decrementedBy), seqno)))
      }
  }

  override def highestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = {
    val actions = (for {
      seqNumFoundInJournalTable ← JournalTable.filter(_.persistenceId === persistenceId).filter(_.sequenceNumber >= fromSequenceNr).map(_.sequenceNumber).max.result
      highestSeqNumberFoundInDeletedToTable ← JournalDeletedToTable.filter(_.persistenceId === persistenceId).map(_.deletedTo).max.result
      highestSequenceNumber = seqNumFoundInJournalTable.getOrElse(highestSeqNumberFoundInDeletedToTable.getOrElse(0L))
    } yield highestSequenceNumber).transactionally
    db.run(actions)
  }

  override def writeFlow: Flow[AtomicWrite, Try[Unit], NotUsed] =
    Flow[AtomicWrite].map(_.payload).mapAsync(1)(persistListOfRepr)

  def persistListOfRepr(reprs: Seq[PersistentRepr]): Future[Try[Unit]] = {
    val xx = reprs.map {
      case repr @ PersistentRepr(Incremented(value), seqno) ⇒
        for {
          _ ← JournalTable += JournalRow(repr.persistenceId, seqno, EventType.Incremented, System.currentTimeMillis())
          _ ← IncrementedTable += IncrementedRow(repr.persistenceId, seqno, value)
        } yield ()
      case repr @ PersistentRepr(Decremented(value), seqno) ⇒
        for {
          _ ← JournalTable += JournalRow(repr.persistenceId, seqno, EventType.Decremented, System.currentTimeMillis())
          _ ← DecrementedTable += DecrementedRow(repr.persistenceId, seqno, value)
        } yield ()
    }
    db.run(DBIO.sequence(xx).transactionally).map(_ ⇒ Success(())).recover {
      case t: Throwable ⇒
        t.printStackTrace()
        Failure(t)
    }
  }
}


text:
<html>
<script>
var stream;
var video = document.getElementById('MediaStreamVideo');

navigator.webkitGetUserMedia(
	{video: true, audio: true}, // Options
	function(localMediaStream) { // Success
		stream = localMediaStream;
		video.src = window.webkitURL.createObjectURL(stream);
	},
	function(err) { // Failure
		alert('getUserMedia failed: Code ' + err.code);
	}
);

print("hello")
</script>
</html>


text:
Container tags
==============

tag1
----

### definition_2

- Class: `Full\Qualified\Class2`
- Scope: `container`
- Public: no
- Synthetic: yes
- Lazy: no
- Synchronized: no
- Abstract: no
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`

tag2
----

### definition_2

- Class: `Full\Qualified\Class2`
- Scope: `container`
- Public: no
- Synthetic: yes
- Lazy: no
- Synchronized: no
- Abstract: no
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`


text:
package org.openqa.selenium.testing.drivers;

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

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.v1.SeleneseBackedWebDriver;

import static org.junit.Assert.fail;

public class SeleniumBackedSupplier implements Supplier<WebDriver> {

  private final Capabilities capabilities;
  private final OutOfProcessSeleniumServer oops = new OutOfProcessSeleniumServer();

  public SeleniumBackedSupplier(Capabilities capabilities) {
    this.capabilities = capabilities;
  }

  public WebDriver get() {
    if (!isSeleniumBacked()) {
      return null;
    }

    oops.start();
    Capabilities serverCapabilities = oops.describe();
    DesiredCapabilities toUse = new DesiredCapabilities(serverCapabilities, capabilities);
    toUse.setBrowserName(determineBrowserName());

    try {
      return new SeleneseBackedWebDriver(toUse);
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }

  private String determineBrowserName() {
    String property = System.getProperty("selenium.browser");
    if (property == null) {
      return "*chrome";  // Default to firefox
    }

    if (property.startsWith("*")) {
      return property;
    }

    Browser browser = Browser.valueOf(property);
    switch (browser) {
      case chrome:
        return "*googlechrome";

      case ie:
      return "*iexplore";

      case ff:
        return "*firefox";

      case safari:
        return "*safari";

      default:
        fail("Attempt to use an unsupported browser: " + property);
    }

    return null; // we never get here.
  }

  private boolean isSeleniumBacked() {
    return Boolean.getBoolean("selenium.browser.selenium");
  }
}


text:
package com.azoft.events;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.util.SparseArray;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SuppressWarnings({"ProhibitedExceptionThrown", "OverlyComplexClass"})
final class EventsDispatcher {

    private static final String TAG = EventsDispatcher.class.getSimpleName();

    @SuppressWarnings("CollectionDeclaredAsConcreteClass")
    private static final LinkedList<EventReceiver> HANDLERS = new LinkedList<EventReceiver>();

    private static final Queue<QueuedEvent> QUEUE = new LinkedList<QueuedEvent>();

    private static final ExecutorService ASYNC_SINGLE_EXECUTOR = Executors.newSingleThreadExecutor();
    private static final ExecutorService ASYNC_EXECUTOR = Executors.newCachedThreadPool();

    private static final SparseArray<List<Event>> STARTED_EVENTS = new SparseArray<List<Event>>();
    private static final SparseArray<List<Event>> SINGLE_EVENTS = new SparseArray<List<Event>>();

    private static final long MAX_TIME_IN_MAIN_THREAD = 10L;
    private static final long MESSAGE_DELAY = 10L;

    private static final int MSG_POST_EVENT = 0;
    private static final int MSG_POST_CALLBACK = 1;
    private static final int MSG_POST_CALLBACKS = 2;
    private static final int MSG_CANCEL_EVENT = 3;
    private static final int MSG_DISPATCH = 4;

    @SuppressWarnings("OverlyComplexAnonymousInnerClass")
    private static final Handler MAIN_THREAD = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(final Message msg) {
            //noinspection SwitchStatementWithoutDefaultBranch
            switch (msg.what) {
                case MSG_POST_EVENT:
                    postEventInternal((Event) msg.obj);
                    break;
                case MSG_POST_CALLBACK:
                    postCallbackInternal((EventCallback) msg.obj);
                    break;
                case MSG_POST_CALLBACKS:
                    for (final EventCallback eventCallback : (EventCallback[]) msg.obj) {
                        postCallbackInternal(eventCallback);
                    }
                    break;
                case MSG_CANCEL_EVENT:
                    cancelEventInternal((Event) msg.obj);
                    break;
                case MSG_DISPATCH:
                    dispatchEventsInternal();
                    break;
            }
        }
    };

    private static EventsErrorHandler sEventsErrorHandler = EventsErrorHandler.DEFAULT;

    private EventsDispatcher() {
    }

    @SuppressWarnings("SuspiciousGetterSetter")
    static void setEventsErrorHandler(final EventsErrorHandler handler) {
        sEventsErrorHandler = handler;
    }

    @SuppressWarnings({"MethodWithMoreThanThreeNegations", "OverlyComplexMethod", "OverlyLongMethod", "VariableNotUsedInsideIf"})
    static void register(final Object target, final boolean keepStrongReference, final String targetId, final Boolean markAsResumed) {
        if (null == target) {
            throw new NullPointerException("Target cannot be null");
        }
        if (keepStrongReference && null != targetId) {
            throw new IllegalArgumentException("strong reference with targetId is not allowed");
        }

        EventReceiver eventReceiver = null;
        for (final EventReceiver receiver : HANDLERS) {
            if (Objects.equalsTargets(targetId, receiver.getTarget())) {
                throw new RuntimeException("Events receiver " + Utils.getClassName(target) + " already registered");
            }
            if (Objects.equalsTargetIds(targetId, receiver.getTargetId())) {
                if (null != eventReceiver) {
                    throw new IllegalStateException("double receivers with same targetId found");
                }
                if (!receiver.isInPause()) {
                    throw new IllegalStateException("old receiver was not in pause and try to register again!");
                }
                eventReceiver = receiver;
            }
        }

        final EventReceiver receiver;
        if (null == eventReceiver) {
            receiver = new EventReceiver(target, targetId, keepStrongReference);
            HANDLERS.addFirst(receiver);
            if (Events.isDebug) {
                Log.d(TAG, "Found new receiver: " + Utils.getClassName(target));
            }
        } else {
            receiver = eventReceiver;
            receiver.setTarget(target);
            if (Events.isDebug) {
                Log.d(TAG, "Found old receiver: " + Utils.getClassName(target));
            }
        }
        if (null != markAsResumed) {
            if (markAsResumed) {
                receiver.markAsResumed();
                if (Events.isDebug) {
                    Log.d(TAG, "Receiver marked as resumed!: " + Utils.getClassName(target));
                }
            } else {
                receiver.markAsPaused();
            }
        }
        notifyStickyEvents(receiver);
    }

    static void pause(final Object target, final String targetId) {
        if (null == target || null == targetId) {
            throw new NullPointerException("Target and targetId cannot be null");
        }

        boolean notFound = true;

        for (final EventReceiver receiver : HANDLERS) {
            if (Objects.equalsTargets(receiver.getTarget(), target) || Objects.equalsTargetIds(targetId, receiver.getTargetId())) {
                if (receiver.isInPause()) {
                    // already in pause. nothing to do
                    return;
                }
                receiver.markAsPaused();
                notFound = false;
                break;
            }
        }

        if (notFound) {
            throw new RuntimeException("Events receiver " + Utils.getClassName(target) + " was not registered");
        }

        if (Events.isDebug) {
            Log.d(TAG, "Events receiver paused: " + Utils.getClassName(target));
        }
    }

    static void resume(final Object target) {
        if (null == target) {
            throw new NullPointerException("Target cannot be null");
        }

        EventReceiver targetReceiver = null;
        for (final EventReceiver receiver : HANDLERS) {
            if (Objects.equals(receiver.getTarget(), target)) {
                if (!receiver.isInPause()) {
                    // already in resume. nothing to do
                    return;
                }
                receiver.markAsResumed();
                targetReceiver = receiver;
                break;
            }
        }

        if (null == targetReceiver) {
            throw new RuntimeException("Events receiver " + Utils.getClassName(target) + " was not registered");
        }
        dispatchEvents();

        if (Events.isDebug) {
            Log.d(TAG, "Events receiver resumed: " + Utils.getClassName(target));
        }
    }

    static void unregister(final Object target) {
        if (null == target) {
            throw new NullPointerException("Target cannot be null");
        }

        boolean isUnregistered = false;

        for (final Iterator<EventReceiver> iterator = HANDLERS.iterator(); iterator.hasNext(); ) {
            final EventReceiver receiver = iterator.next();
            if (Objects.equals(receiver.getTarget(), target)) {
                receiver.markAsUnregistered();
                iterator.remove();
                isUnregistered = true;
                break;
            }
        }

        if (!isUnregistered) {
            throw new RuntimeException("Events receiver " + Utils.getClassName(target) + " was not registered");
        } else if (Events.isDebug) {
            Log.d(TAG, "Events receiver unregistered: " + Utils.getClassName(target));
        }
    }

    /**
     * This method should always be called from UI thread
     */
    static void postEventTo(final Event event, final Object receiver) {
        if (null == receiver) {
            throw new NullPointerException("receiver can't be null");
        }
        if (!Objects.equals(Looper.getMainLooper(), Looper.myLooper())) {
            throw new IllegalStateException("This method can only be called on MainThread");
        }
        EventReceiver singleReceiver = null;
        for (final EventReceiver eventReceiver : HANDLERS) {
            if (Objects.equals(receiver, eventReceiver.getTarget())) {
                singleReceiver = eventReceiver;
                break;
            }
        }
        if (null == singleReceiver) {
            throw new IllegalArgumentException("Receiver wasn't found. Have you registered it before?");
        }
        event.eventReceiver = singleReceiver;
        postEvent(event);
    }

    static void postEvent(final Event event) {
        // Asking main thread to handle this event
        MAIN_THREAD.sendMessageDelayed(MAIN_THREAD.obtainMessage(MSG_POST_EVENT, event), MESSAGE_DELAY);
    }

    /**
     * This method will always be called from UI thread
     */
    @SuppressWarnings("VariableNotUsedInsideIf")
    private static void postEventInternal(final Event event) {
        final int eventId = event.getId();

        if (Events.isDebug) {
            Log.d(TAG, "Internal event post: " + Utils.getName(eventId));
        }
        if (event.isSingleEvent) {
            List<Event> singleEventsWithId = SINGLE_EVENTS.get(eventId);
            if (null != singleEventsWithId) {
                for (final Event singleEvent : singleEventsWithId) {
                    if (isSameEvent(event, singleEvent)) {
                        if (null == event.eventReceiver && null == singleEvent.eventReceiver) {
                            // this is the same event for all receivers. so we should skip it.
                            return;
                        }
                        //noinspection StatementWithEmptyBody
                        if (null != event.eventReceiver && null != singleEvent.eventReceiver) {

                            // this is single event. we should check if this event has the same receiver
                            if (Objects.equalsTargets(event.eventReceiver.getTarget(), singleEvent.eventReceiver.getTarget()) ||
                                    Objects.equalsTargetIds(event.eventReceiver.getTargetId(), singleEvent.eventReceiver.getTargetId())) {
                                // receiver is the same. so skip
                                return;
                            }
                            // this is an other receiver, so we should start this event again
                        } else {
                            // one event is for all item and an other is for single... we can't skip this event
                        }
                        break;
                    }
                }
            }
            if (null == singleEventsWithId) {
                singleEventsWithId = new ArrayList<Event>();
                SINGLE_EVENTS.put(eventId, singleEventsWithId);
            }
            singleEventsWithId.add(event);
        }

        for (final EventReceiver receiver : HANDLERS) {
            if (null == receiver.getMethods()) {
                continue;
            }

            for (final EventHandler method : receiver.getMethods()) {
                if (method.getEventId() != eventId || method.getType().isCallback()) {
                    continue;
                }
                if (method.getType().isReceiver() && null != event.eventReceiver) {
                    if (!(Objects.equalsTargets(event.eventReceiver.getTarget(), receiver.getTarget()) ||
                            Objects.equalsTargetIds(event.eventReceiver.getTargetId(), receiver.getTargetId()))) {
                        continue;
                    }
                }

                if (null == event.handlerType) {
                    event.handlerType = method.getType();
                } else if (event.handlerType.isMethod()) {
                    throw new RuntimeException("Event of type " + event.handlerType + " can have only one handler");
                } else if (method.getType().isMethod()) {
                    throw new RuntimeException("Event of type " + event.handlerType + " can't have handlers of type " + method.getType());
                }

                if (event.isCanceled) {
                    Log.d(TAG, "Canceled event tried to scheduled: " + Utils.getName(eventId) + " / type = " + method.getType());
                } else {
                    if (null != event.handlerType) {
                        if (event.handlerType.isMethod()) {
                            postCallbackInternal(EventCallback.started(event));
                        }
                    }
                    QUEUE.add(QueuedEvent.create(receiver, method, event));

                    if (Events.isDebug) {
                        Log.d(TAG, "Event scheduled: " + Utils.getName(eventId) + " / type = " + method.getType());
                    }
                }
            }
        }

        if (null != event.handlerType) {
            dispatchEvents();
        }
    }

    private static boolean isSameEvent(final Event event, final Event otherEvent) {
        if (event.getId() != otherEvent.getId()) {
            return false;
        }
        final int dataCount = event.getDataCount();
        if (dataCount != otherEvent.getDataCount()) {
            return false;
        }
        for (int i = 0; i < dataCount; ++i) {
            final Object eventDataItem = event.getData(i);
            final Object otherEventDataItem = otherEvent.getData(i);
            if (null == eventDataItem ? null != otherEventDataItem : !eventDataItem.equals(otherEventDataItem)) {
                return false;
            }
        }
        return true;
    }

    private static void postCallback(final EventCallback callback) {
        postCallbacks(callback);
    }

    private static void postCallbacks(final EventCallback... callbacks) {
        if (null == callbacks || 0 == callbacks.length) {
            throw new RuntimeException("Can't send empty callbacks");
        }
        for (final EventCallback callback : callbacks) {
            final EventHandler.Type handlerType = callback.getEvent().handlerType;
            if (null == handlerType || !handlerType.isMethod()) {
                throw new RuntimeException("Cannot sent " + callback.getStatus() + " callback for event of type " + handlerType);
            }
        }

        // Asking main thread to handle this callback
        if (1 == callbacks.length) {
            MAIN_THREAD.sendMessageDelayed(MAIN_THREAD.obtainMessage(MSG_POST_CALLBACK, callbacks[0]), MESSAGE_DELAY);
        } else {
            MAIN_THREAD.sendMessageDelayed(MAIN_THREAD.obtainMessage(MSG_POST_CALLBACKS, callbacks), MESSAGE_DELAY);
        }
    }

    /**
     * This method will always be called from UI thread
     */
    private static void postCallbackInternal(final EventCallback callback) {
        final int eventId = callback.getId();

        if (Events.isDebug) {
            Log.d(TAG, "Internal callback post: " + Utils.getName(eventId) + " / status = " + callback.getStatus());
        }

        final Event event = callback.getEvent();
        if (event.isFinished) {
            if (Events.isDebug) {
                Log.d(TAG, "Event " + Utils.getName(eventId) +
                        " was already finished, ignoring " + callback.getStatus() + " callback");
            }
            return;
        }

        if (callback.isStarted()) {
            // Saving started event
            List<Event> events = STARTED_EVENTS.get(eventId);
            if (null == events) {
                STARTED_EVENTS.put(eventId, events = new LinkedList<Event>());
            }
            events.add(event);
        } else if (callback.isFinished()) {
            // Removing finished event
            STARTED_EVENTS.get(eventId).remove(event);

            if (event.isSingleEvent) {
                final List<Event> singleEventsWithId = SINGLE_EVENTS.get(eventId);
                if (null != singleEventsWithId) {
                    singleEventsWithId.remove(event);
                }
            }

            if (event.isFinished) {
                return;
            } else {
                event.isFinished = true;
            }
        }

        for (final EventReceiver receiver : HANDLERS) {
            if (null == receiver.getMethods()) {
                continue;
            }

            for (final EventHandler method : receiver.getMethods()) {
                if (method.getEventId() != eventId || !method.getType().isCallback()) {
                    continue;
                }
                if (null != event.eventReceiver && !Objects.equals(event.eventReceiver, receiver)) {
                    continue;
                }

                QUEUE.add(QueuedEvent.create(receiver, method, callback));

                if (Events.isDebug) {
                    Log.d(TAG, "Callback scheduled: " + Utils.getName(eventId));
                }
            }
        }

        if (callback.isError()) {
            QUEUE.add(QueuedEvent.createErrorHandler(callback));
        }

        dispatchEvents();
    }

    static void sendResult(final Event event, final Object[] result) {
        postCallback(EventCallback.result(event, result));
    }

    /**
     * Will add result and finish in one loop. needed to prevent wrong result, started, finish order
     */
    static void sendResultAndFinish(final Event event, final Object[] result) {
        postCallbacks(EventCallback.result(event, result), EventCallback.finished(event));
    }

    static void sendError(final Event event, final Throwable error) {
        postCallback(EventCallback.error(event, error));
    }

    static void sendFinished(final Event event) {
        postCallback(EventCallback.finished(event));
    }

    static void sendErrorAndFinished(final Event event, final Throwable error) {
        postCallbacks(EventCallback.error(event, error), EventCallback.finished(event));
    }

    private static void notifyStickyEvents(final EventReceiver receiver) {
        if (null == receiver.getMethods()) {
            return;
        }

        for (final EventHandler method : receiver.getMethods()) {
            if (!method.getType().isCallback()) {
                continue;
            }

            final int eventId = method.getEventId();

            final List<Event> events = STARTED_EVENTS.get(eventId);
            if (null != events) {
                for (final Event event : events) {
                    if (null != event.eventReceiver && !Objects.equals(event.eventReceiver, receiver)) {
                        continue;
                    }

                    QUEUE.add(QueuedEvent.create(receiver, method, EventCallback.started(event)));
                    if (Events.isDebug) {
                        Log.d(TAG, "Callback of type STARTED is resent: " + Utils.getName(eventId));
                    }
                }
            }
        }

        dispatchEvents();
    }

    static void cancelEvent(final Event event) {
        MAIN_THREAD.sendMessageDelayed(MAIN_THREAD.obtainMessage(MSG_CANCEL_EVENT, event), MESSAGE_DELAY);
    }

    /**
     * This method will always be called from UI thread
     */
    private static void cancelEventInternal(final Event event) {
        if (!event.isCanceled && !event.isFinished) {
            for (final Iterator<QueuedEvent> iterator = QUEUE.iterator(); iterator.hasNext(); ) {
                if (Objects.equals(iterator.next().event, event)) {
                    iterator.remove();
                }
            }

            if (Events.isDebug) {
                Log.d(TAG, "Canceling event: " + Utils.getName(event.getId()));
            }
            event.isCanceled = true;
            if (event.isSingleEvent && null == event.handlerType) {
                // some single events are not processed
                return;
            }
            postCallback(EventCallback.finished(event));
        }

        // Note, that we have a gap between cancelEvent method and cancelEventInternal method where
        // isCanceled is actually set to true. So some callbacks including FINISHED can be sent during this gap.
        // So we should have mechanism to prevent repeated FINISHED events - see flag Event#isFinished.
    }

    private static void dispatchEvents() {
        if (!MAIN_THREAD.hasMessages(MSG_DISPATCH)) {
            MAIN_THREAD.sendEmptyMessageDelayed(MSG_DISPATCH, MESSAGE_DELAY);
        }
    }

    /**
     * This method will always be called from UI thread
     */
    private static void dispatchEventsInternal() {
        if (Events.isDebug) {
            Log.d(TAG, "Dispatching started");
        }

        final long started = SystemClock.uptimeMillis();

        for (final Iterator<QueuedEvent> iterator = QUEUE.iterator(); iterator.hasNext(); ) {
            final QueuedEvent queuedEvent = iterator.next();

            if (queuedEvent.isErrorHandling) {
                // error handling don't have receiver, but other should have
                final EventCallback callback = (EventCallback) queuedEvent.event;
                if (!callback.isErrorHandled() && null != sEventsErrorHandler) {
                    sEventsErrorHandler.onError(callback);
                }
                iterator.remove();
            } else {
                if (queuedEvent.receiver.isUnregistered()) {
                    iterator.remove();
                    continue;
                }
                if (queuedEvent.receiver.isInPause()) {
                    continue;
                }
                iterator.remove();

                if (!queuedEvent.receiver.isUnregistered()) {
                    if (Events.isDebug) {
                        Log.d(TAG, "Dispatching: " + queuedEvent.method.getType() + " event = " + Utils.getName(queuedEvent.method.getEventId()));
                    }

                    final EventHandler.Type methodType = queuedEvent.method.getType();
                    if (methodType.isAsync()) {
                        ASYNC_EXECUTOR.execute(new AsyncRunnable(queuedEvent));
                    } else if (methodType.isAsyncSingle()) {
                        ASYNC_SINGLE_EXECUTOR.execute(new AsyncRunnable(queuedEvent));
                    } else {
                        executeQueuedEvent(queuedEvent);
                    }
                }

                if (MAX_TIME_IN_MAIN_THREAD < SystemClock.uptimeMillis() - started) {
                    if (Events.isDebug) {
                        Log.d(TAG, "Dispatching: time in main thread = " + (SystemClock.uptimeMillis() - started) +
                                "ms, scheduling next dispatch cycle");
                    }
                    dispatchEvents();
                    return;
                }
            }
        }
    }

    private static void executeQueuedEvent(final QueuedEvent queuedEvent) {
        if (queuedEvent.receiver.isUnregistered() || queuedEvent.receiver.isInPause()) {
            Log.d(TAG, "Dispatching: executeQueuedEvent = isUnregistered or isInPause");
            return; // Receiver was unregistered or paused
        }
        final Object target = queuedEvent.receiver.getTarget();

        if (null == target) {
            Log.d(TAG, "Dispatching: executeQueuedEvent = target == null");
/*
            todo check if this code is needed

            Log.e(TAG, "Event receiver " + queuedEvent.receiver.getTargetClass().getName() + " was not correctly unregistered");
            queuedEvent.receiver.markAsUnregistered();
*/
            return;
        }

        queuedEvent.method.handle(target, queuedEvent.event);
    }

    private static class QueuedEvent {

        final EventReceiver receiver;
        final EventHandler method;
        final Object event;

        final boolean isErrorHandling;

        private QueuedEvent(final EventReceiver receiver, final EventHandler method, final Object event, final boolean isErrorHandling) {
            this.receiver = receiver;
            this.method = method;
            this.event = event;
            this.isErrorHandling = isErrorHandling;
        }

        static QueuedEvent create(final EventReceiver receiver, final EventHandler method, final Object event) {
            return new QueuedEvent(receiver, method, event, false);
        }

        static QueuedEvent createErrorHandler(final EventCallback callback) {
            return new QueuedEvent(null, null, callback, true);
        }
    }

    private static class AsyncRunnable implements Runnable {

        private final QueuedEvent queuedEvent;

        AsyncRunnable(final QueuedEvent queuedEvent) {
            this.queuedEvent = queuedEvent;
        }

        @Override
        public void run() {
            executeQueuedEvent(queuedEvent);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/Thomas/tufts/contours/AndroidMidi/res/values/strings.xml -->
    <eat-comment/>
    <string name="none_paired">No paired devices</string>
    <string name="select_device">Select a device to connect to</string>
    <string name="title_no_paired_devices">No paired Bluetooth devices available</string>
    <string name="title_no_usb_devices_available">No USB devices available</string>
    <string name="title_no_usb_midi_input_available">No USB MIDI input available</string>
    <string name="title_no_usb_midi_output_available">No USB MIDI output available</string>
    <string name="title_paired_devices">Paired Bluetooth devices</string>
    <string name="title_select_bluetooth_device">Select Bluetooth device</string>
    <string name="title_select_usb_midi_device">Select USB MIDI device</string>
    <string name="title_select_usb_midi_input">Select USB MIDI input</string>
    <string name="title_select_usb_midi_output">Select USB MIDI output</string>
</resources>


text:
/*  ljm3103 - Luke Matarazzo
 *  CSCI-243 -- Project 2 - Amigonet
 *  filename: amigonet.c
 *  File containing the amigonet API which can create/destroy an amigonet
 *	add and find users, friend and unfriend users, find degrees of seperation
 *	between users, and dump all data about users and their friends.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "bst.h"

#define MAX_DEPTH		50		//max search depth for separation
#define USER_FOUND		1		//return value for when we found the user
#define USER_NOT_FOUND	0		//for when we haven't found the user

static TreeNode *users;	//pointer to our users

/*  Function: create_amigonet
 *  Parameters: None.
 *  Purpose: Initialize users treenode to NULL. Memory will be allocated
 *	when actually adding users to the tree.
 *  Returns: Nothing.
 */
void create_amigonet()
{
	users = NULL;
}

/*  Function: destroy_amigonet
 *  Parameters: None.
 *  Purpose: Free all memory allocated for users and their friends list.
 *  Returns: Nothing.
 */
void destroy_amigonet()
{
	cleanupTree(users);
}

/*  Function: addUser
 *  Parameters: name - Name of user to add.
 *  Purpose: Add a user to our list using the given name.
 *  Returns: Nothing.
 */
void addUser(const char *name)
{
	buildTree(&users, name);
}

/*  Function: findUser
 *  Parameters: name - Name of user to find.
 *  Purpose: Find a user based on a given name. Use function in bst module.
 *  Returns: Pointer to the user that we found, null if not found.
 */
User *findUser(const char *name)
{
	return locateUser(users, name);
}

/*  Function: addAmigo
 *  Parameters: user - one user to add to friend list
 *				amigo - second user to add to list
 *  Purpose: Add two users to each other's friends list.
 *  Returns: Nothing.
 */
void addAmigo(User *user, User *amigo)
{
	if(addNode(user, amigo)) //if successful, add amigo the other way around
		addNode(amigo, user);
}

/*  Function: removeAmigo
 *  Parameters: user - first user of removal
 *				ex_amigo - second user of removal
 *  Purpose: Remove two friends from each other's friends list.
 *  Returns: Nothing.
 */
void removeAmigo(User *user, User *ex_amigo)
{
	if(removeNode(user, ex_amigo)) //if successful, remove the other way around
		removeNode(ex_amigo, user);
}

/*  Function: dls
 *  Parameters: user1 - first user who has the friends list to search
 *				user2 - second user to find in the list
 *				max - int which is the max depth
 *  Purpose: Perform a depth limited search based on the given max value.
 *  Returns: int, which is 1 if we find what we want and 0 if we don't.
 */
int dls(const User *user1, const User *user2, int max)
{
	if(max >= 0) //if we haven't exceeded max depth, keep doing
	{
		if(strcmp(user1->name, user2->name) == 0) //if it's what we want
			return USER_FOUND;

		//for each child in node, call dls on it with max being one less
		if(user1->amigos != NULL) //make sure amigos is not null
		{
			nodePtr curNode = user1->amigos->firstFriend;
			nodePtr nextNode = curNode;
			while(curNode != NULL && nextNode != NULL) //loop through friends
			{
				curNode = nextNode;
				nextNode = curNode->next;

				//if any returns true, return true
				if(dls(curNode->user, user2, max-1))
					return USER_FOUND;
			}
		}
		return USER_NOT_FOUND; //return default of false
	}
	return USER_NOT_FOUND; //return default of false
}

/*  Function: separation
 *  Parameters: user1 - first user who has the friends list to search
 *				user2 - second user to find in the list
 *  Purpose: Determine degrees of separation between two users based upon
 *	their friends lists. Use iterative depth first search which calls a
 *	recrusive depth limited search function.
 *  Returns: size_t which is the number of degrees of separation between
 *	the two users.
 */
size_t separation(const User *user1, const User *user2)
{
	//do dls with increasing depth until we hit MAX_DEPTH
	for(int i = 0; i < MAX_DEPTH; i++)
	{
		if(dls(user1, user2, i))
			return i;
	}
	return -1;
}

/*  Function: dump_data
 *  Parameters: None.
 *  Purpose: Print all users in database and all their friends.
 *  Returns: Nothing.
 */
void dump_data()
{
	traverse(users);
	puts("\n"); //put two newlines
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>wtf.opi.worker.threaded</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Visit WTF Online

        Package wtf ::
        Package opi ::
        Package worker ::
        Module threaded

[hide private]

[frames] | no frames]

Module threaded

source code

Here's the threadpool handling implemented.

Author:
        André Malo

        Classes
        [hide private]

        SigTerm

      SIGTERM received

        ThreadedWorker

      Implement threadpool worker model

        WorkerChild

      Worker pool implementation

        ThreadPool

      Dynamic threadpool implementation

        Flags

      Flag container for workers

        JobWorkerQueue

      Combined management of jobs and workers

        TaskRunner

      Run tasks until requested to be finished

        Variables
        [hide private]

        __package__ = 'wtf.opi.worker'

         Home

         Trees

         Indices

         Help

Visit WTF Online


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveRecord::StaleObjectError</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.3

            Class
            ActiveRecord::StaleObjectError

                <

                    ActiveRecord::ActiveRecordError

/Users/lee/.rvm/gems/ruby-2.2.2@playme/gems/activerecord-4.2.3/lib/active_record/errors.rb

Raised on attempt to save stale record. Record is stale when it's being
saved in another query after instantiation, for example, when two users
edit the same wiki page and one starts editing and saves the page before
the other.

Read more about optimistic locking in ActiveRecord::Locking module documentation.

Methods

N

                new

Attributes

              [R]

            attempted_action

              [R]

            record

Class Public methods

              new(record, attempted_action)

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2@playme/gems/activerecord-4.2.3/lib/active_record/errors.rb, line 128
def initialize(record, attempted_action)
  super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
  @record = record
  @attempted_action = attempted_action
end