text:
<?php

namespace ZendTest\Dom;

use Zend\Dom\Document;
use Zend\Dom\NodeList;
use Zend\Dom\Exception\ExceptionInterface as DOMException;

/**
 * Test class for Zend\Dom\Document.
 *
 * @group      Zend_Dom
 */
class DocumentTest extends \PHPUnit_Framework_TestCase
{
    public $html;
    public $document;

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        $this->document = new Document();
    }

    public function getHtml()
    {
        if (null === $this->html) {
            $this->html  = file_get_contents(__DIR__ . '/_files/sample.xhtml');
        }
        return $this->html;
    }

    public function loadHtml()
    {
        $this->document = new Document($this->getHtml());
    }

    public function handleError($msg, $code = 0)
    {
        $this->error = $msg;
    }

    public function testConstructorShouldNotRequireArguments()
    {
        $document = new Document();
    }

    public function testConstructorShouldAcceptDocumentString()
    {
        $html  = $this->getHtml();
        $document = new Document($html);
        $this->assertSame($html, $document->getStringDocument());
    }

    public function testDocShouldBeNullByDefault()
    {
        $this->assertNull($this->document->getStringDocument());
    }

    public function testDomDocShouldRaiseExceptionByDefault()
    {
        $this->setExpectedException('\Zend\Dom\Exception\RuntimeException', 'no document');
        $this->document->getDomDocument();
    }

    public function testDocShouldBeNullByEmptyStringConstructor()
    {
        $emptyStr = '';
        $document = new Document($emptyStr);
        $this->assertNull($this->document->getStringDocument());
    }

    public function testDocTypeShouldBeNullByDefault()
    {
        $this->assertNull($this->document->getType());
    }

    public function testDocEncodingShouldBeNullByDefault()
    {
        $this->assertNull($this->document->getEncoding());
    }

    public function testShouldAllowSettingDocument()
    {
        $this->testDocShouldBeNullByDefault();
        $this->loadHtml();
        $this->assertEquals($this->getHtml(), $this->document->getStringDocument());
    }

    public function testDocumentTypeShouldBeAutomaticallyDiscovered()
    {
        $this->loadHtml();
        $this->assertEquals(Document::DOC_XHTML, $this->document->getType());
        $this->document = new Document('<?xml version="1.0"?><root></root>');
        $this->assertEquals(Document::DOC_XML, $this->document->getType());
        $this->document = new Document('');
        $this->assertEquals(Document::DOC_HTML, $this->document->getType());
    }

    public function testQueryingWithoutRegisteringDocumentShouldThrowException()
    {
        $this->setExpectedException('\Zend\Dom\Exception\RuntimeException', 'no document');
        $result = Document\Query::execute('.foo', $this->document, Document\Query::TYPE_CSS);
    }

    public function testQueryingInvalidDocumentShouldThrowException()
    {
        set_error_handler(array($this, 'handleError'));
        $this->document = new Document('some bogus string', Document::DOC_XML);
        try {
            $result = Document\Query::execute('.foo', $this->document, Document\Query::TYPE_CSS);
            restore_error_handler();
            $this->fail('Querying invalid document should throw exception');
        } catch (DOMException $e) {
            restore_error_handler();
            $this->assertContains('Error parsing', $e->getMessage());
        }
    }

    public function testgetDomMethodShouldReturnDomDocumentWithStringDocumentInConstructor()
    {
        $html  = $this->getHtml();
        $document = new Document($html);
        $this->assertTrue($document->getDomDocument() instanceof \DOMDocument);
    }

    public function testgetDomMethodShouldReturnDomDocumentWithStringDocumentSetFromMethod()
    {
        $this->loadHtml();
        $this->assertTrue($this->document->getDomDocument() instanceof \DOMDocument);
    }

    public function testQueryShouldReturnResultObject()
    {
        $this->loadHtml();
        $result = Document\Query::execute('.foo', $this->document, Document\Query::TYPE_CSS);
        $this->assertTrue($result instanceof Document\NodeList);
    }

    public function testResultShouldIndicateNumberOfFoundNodes()
    {
        $this->loadHtml();
        $result = Document\Query::execute('.foo', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(3, count($result));
    }

    public function testResultShouldAllowIteratingOverFoundNodes()
    {
        $this->loadHtml();
        $result = Document\Query::execute('.foo', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(3, count($result));
        foreach ($result as $node) {
            $this->assertTrue($node instanceof \DOMNode, var_export($result, 1));
        }
    }

    public function testQueryShouldFindNodesWithMultipleClasses()
    {
        $this->loadHtml();
        $result = Document\Query::execute('.footerblock .last', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(1, count($result));
    }

    public function testQueryShouldFindNodesWithArbitraryAttributeSelectorsExactly()
    {
        $this->loadHtml();
        $result = Document\Query::execute('div[dojoType="FilteringSelect"]', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(1, count($result));
    }

    public function testQueryShouldFindNodesWithArbitraryAttributeSelectorsAsDiscreteWords()
    {
        $this->loadHtml();
        $result = Document\Query::execute('li[dojoType~="bar"]', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(2, count($result));
    }

    public function testQueryShouldFindNodesWithArbitraryAttributeSelectorsAndAttributeValue()
    {
        $this->loadHtml();
        $result = Document\Query::execute('li[dojoType*="bar"]', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(2, count($result));
    }

    public function testQueryXpathShouldAllowQueryingArbitraryUsingXpath()
    {
        $this->loadHtml();
        $result = Document\Query::execute('//li[contains(@dojotype, "bar")]', $this->document);
        $this->assertEquals(2, count($result));
    }

    public function testXpathPhpFunctionsShouldBeDisabledByDefault()
    {
        $this->loadHtml();
        try {
            $result = Document\Query::execute('//meta[php:functionString("strtolower", @http-equiv) = "content-type"]', $this->document);
        } catch (\Exception $e) {
            return;
        }
        $this->assertTrue(false, 'XPath PHPFunctions should be disabled by default');
    }

    public function testXpathPhpFunctionsShouldBeEnabledWithoutParameter()
    {
        $this->loadHtml();
        $this->document->registerXpathPhpFunctions();
        $result = Document\Query::execute('//meta[php:functionString("strtolower", @http-equiv) = "content-type"]', $this->document);
        $this->assertEquals(
            'content-type',
            strtolower($result->current()->getAttribute('http-equiv'))
        );
    }

    public function testXpathPhpFunctionsShouldBeNotCalledWhenSpecifiedFunction()
    {
        $this->loadHtml();
        try {
            $this->document->registerXpathPhpFunctions('stripos');
            $result = Document\Query::execute('//meta[php:functionString("strtolower", @http-equiv) = "content-type"]', $this->document);
        } catch (\Exception $e) {
            // $e->getMessage() - Not allowed to call handler 'strtolower()
            return;
        }
        $this->assertTrue(false, 'Not allowed to call handler strtolower()');
    }

    /**
     * @group ZF-9243
     */
    public function testLoadingDocumentWithErrorsShouldNotRaisePhpErrors()
    {
        $file = file_get_contents(__DIR__ . '/_files/bad-sample.html');
        $this->document = new Document($file);
        $result = Document\Query::execute('p', $this->document, Document\Query::TYPE_CSS);
        $errors = $this->document->getErrors();
        $this->assertTrue(is_array($errors));
        $this->assertTrue(0 < count($errors));
    }

    /**
     * @group ZF-9765
     */
    public function testCssSelectorShouldFindNodesWhenMatchingMultipleAttributes()
    {
        $html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <form action="#" method="get">
    <input type="hidden" name="foo" value="1" id="foo"/>
    <input type="hidden" name="bar" value="0" id="bar"/>
    <input type="hidden" name="baz" value="1" id="baz"/>
  </form>

EOF;

        $this->document = new Document($html);
        $result = Document\Query::execute('input[type="hidden"][value="1"]', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(2, count($result));
        $result = Document\Query::execute('input[value="1"][type~="hidden"]', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(2, count($result));
        $result = Document\Query::execute('input[type="hidden"][value="0"]', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(1, count($result));
    }

    /**
     * @group ZF-3938
     */
    public function testAllowsSpecifyingEncodingAtConstruction()
    {
        $doc = new Document($this->getHtml(), null, 'iso-8859-1');
        $this->assertEquals('iso-8859-1', $doc->getEncoding());
    }

    /**
     * @group ZF-3938
     */
    public function testAllowsSpecifyingEncodingWhenSettingDocument()
    {
        $this->document = new Document($this->getHtml(), null, 'iso-8859-1');
        $this->assertEquals('iso-8859-1', $this->document->getEncoding());
    }

    /**
     * @group ZF-3938
     */
    public function testAllowsSpecifyingEncodingViaSetter()
    {
        $this->document->setEncoding('iso-8859-1');
        $this->assertEquals('iso-8859-1', $this->document->getEncoding());
    }

    /**
     * @group ZF-3938
     */
    public function testSpecifyingEncodingSetsEncodingOnDomDocument()
    {
        $this->document = new Document($this->getHtml(), null, 'utf-8');
        $result = Document\Query::execute('.foo', $this->document, Document\Query::TYPE_CSS);
        $this->assertInstanceof('\\Zend\\Dom\\Document\\NodeList', $result);
        $this->assertInstanceof('\\DOMDocument', $this->document->getDomDocument());
        $this->assertEquals('utf-8', $this->document->getEncoding());
    }

    /**
     * @group ZF-11376
     */
    public function testXhtmlDocumentWithXmlDeclaration()
    {
        $xhtmlWithXmlDecl = <<<EOB
<?xml version="1.0" encoding="UTF-8" ?>

    <title />

Test paragraph.

EOB;
        $this->document = new Document($xhtmlWithXmlDecl, null, 'utf-8');
        $result = Document\Query::execute('//p', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(1, $result->count());
    }

    /**
     * @group ZF-12106
     */
    public function testXhtmlDocumentWithXmlAndDoctypeDeclaration()
    {
        $xhtmlWithXmlDecl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Virtual Library</title>

Moved to example.org.

EOB;
        $this->document = new Document($xhtmlWithXmlDecl, null, 'utf-8');
        $result = Document\Query::execute('//p', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(1, $result->count());
    }

    public function testLoadingXmlContainingDoctypeShouldFailToPreventXxeAndXeeAttacks()
    {
        $xml = <<<XML
<?xml version="1.0"?>
<!DOCTYPE results [<!ENTITY harmless "completely harmless">]>
<results>
    <result>This result is &harmless;</result>
</results>
XML;
        $this->document = new Document($xml);
        $this->setExpectedException("\Zend\Dom\Exception\RuntimeException");
        $result = Document\Query::execute('/', $this->document);
    }

    public function testOffsetExists()
    {
        $this->loadHtml();
        $result = Document\Query::execute('input', $this->document, Document\Query::TYPE_CSS);

        $this->assertEquals(3, $result->count());
        $this->assertFalse($result->offsetExists(3));
        $this->assertTrue($result->offsetExists(2));
    }

    public function testOffsetGet()
    {
        $this->loadHtml();
        $result = Document\Query::execute('input', $this->document, Document\Query::TYPE_CSS);

        $this->assertEquals(3, $result->count());
        $this->assertEquals('login', $result[2]->getAttribute('id'));
    }

    /**
     * @expectedException Zend\Dom\Exception\BadMethodCallException
     */
    public function testOffsetSet()
    {
        $this->loadHtml();
        $result = Document\Query::execute('input', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(3, $result->count());

        $result[0] = '<foobar />';
    }

    /**
     * @expectedException Zend\Dom\Exception\BadMethodCallException
     */
    public function testOffsetUnset()
    {
        $this->loadHtml();
        $result = Document\Query::execute('input', $this->document, Document\Query::TYPE_CSS);
        $this->assertEquals(3, $result->count());

        unset($result[2]);
    }
}


text:
"""Converts gcc errors in code using Google Mock to plain English."""

__author__ = 'wan@google.com (Zhanyong Wan)'

import re
import sys

_VERSION = '1.0.3'

_COMMON_GMOCK_SYMBOLS = [
    # Matchers
    '_',
    'A',
    'AddressSatisfies',
    'AllOf',
    'An',
    'AnyOf',
    'ContainerEq',
    'Contains',
    'ContainsRegex',
    'DoubleEq',
    'ElementsAre',
    'ElementsAreArray',
    'EndsWith',
    'Eq',
    'Field',
    'FloatEq',
    'Ge',
    'Gt',
    'HasSubstr',
    'IsInitializedProto',
    'Le',
    'Lt',
    'MatcherCast',
    'Matches',
    'MatchesRegex',
    'NanSensitiveDoubleEq',
    'NanSensitiveFloatEq',
    'Ne',
    'Not',
    'NotNull',
    'Pointee',
    'Property',
    'Ref',
    'ResultOf',
    'SafeMatcherCast',
    'StartsWith',
    'StrCaseEq',
    'StrCaseNe',
    'StrEq',
    'StrNe',
    'Truly',
    'TypedEq',
    'Value',

    # Actions
    'Assign',
    'ByRef',
    'DeleteArg',
    'DoAll',
    'DoDefault',
    'IgnoreResult',
    'Invoke',
    'InvokeArgument',
    'InvokeWithoutArgs',
    'Return',
    'ReturnNew',
    'ReturnNull',
    'ReturnRef',
    'SaveArg',
    'SetArgReferee',
    'SetArgumentPointee',
    'SetArrayArgument',
    'SetErrnoAndReturn',
    'Throw',
    'WithArg',
    'WithArgs',
    'WithoutArgs',

    # Cardinalities
    'AnyNumber',
    'AtLeast',
    'AtMost',
    'Between',
    'Exactly',

    # Sequences
    'InSequence',
    'Sequence',

    # Misc
    'DefaultValue',
    'Mock',
    ]

# Regex for matching source file path and line number in gcc's errors.
_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):\s+'

def _FindAllMatches(regex, s):
  """Generates all matches of regex in string s."""

  r = re.compile(regex)
  return r.finditer(s)

def _GenericDiagnoser(short_name, long_name, regex, diagnosis, msg):
  """Diagnoses the given disease by pattern matching.

  Args:
    short_name: Short name of the disease.
    long_name:  Long name of the disease.
    regex:      Regex for matching the symptoms.
    diagnosis:  Pattern for formatting the diagnosis.
    msg:        Gcc's error messages.
  Yields:
    Tuples of the form
      (short name of disease, long name of disease, diagnosis).
  """

  diagnosis = '%(file)s:%(line)s:' + diagnosis
  for m in _FindAllMatches(regex, msg):
    yield (short_name, long_name, diagnosis % m.groupdict())

def _NeedToReturnReferenceDiagnoser(msg):
  """Diagnoses the NRR disease, given the error messages by gcc."""

  regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
           + _FILE_LINE_RE + r'instantiated from here\n'
           r'.*gmock-actions\.h.*error: creating array with negative size')
  diagnosis = """
You are using an Return() action in a function that returns a reference.
Please use ReturnRef() instead."""
  return _GenericDiagnoser('NRR', 'Need to Return Reference',
                           regex, diagnosis, msg)

def _NeedToReturnSomethingDiagnoser(msg):
  """Diagnoses the NRS disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE +
           r'(instantiated from here\n.'
           r'*gmock.*actions\.h.*error: void value not ignored)'
           r'|(error: control reaches end of non-void function)')
  diagnosis = """
You are using an action that returns void, but it needs to return
*something*.  Please tell it *what* to return.  Perhaps you can use
the pattern DoAll(some_action, Return(some_value))?"""
  return _GenericDiagnoser('NRS', 'Need to Return Something',
                           regex, diagnosis, msg)

def _NeedToReturnNothingDiagnoser(msg):
  """Diagnoses the NRN disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'instantiated from here\n'
           r'.*gmock-actions\.h.*error: instantiation of '
           r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
           r'as type \'void\'')
  diagnosis = """
You are using an action that returns *something*, but it needs to return
void.  Please use a void-returning action instead.

All actions but the last in DoAll(...) must return void.  Perhaps you need
to re-arrange the order of actions in a DoAll(), if you are using one?"""
  return _GenericDiagnoser('NRN', 'Need to Return Nothing',
                           regex, diagnosis, msg)

def _IncompleteByReferenceArgumentDiagnoser(msg):
  """Diagnoses the IBRA disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'instantiated from here\n'
           r'.*gtest-printers\.h.*error: invalid application of '
           r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
  diagnosis = """
In order to mock this function, Google Mock needs to see the definition
of type "%(type)s" - declaration alone is not enough.  Either #include
the header that defines it, or change the argument to be passed
by pointer."""
  return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
                           regex, diagnosis, msg)

def _OverloadedFunctionMatcherDiagnoser(msg):
  """Diagnoses the OFM disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'error: no matching function for '
           r'call to \'Truly\(<unresolved overloaded function type>\)')
  diagnosis = """
The argument you gave to Truly() is an overloaded function.  Please tell
gcc which overloaded version you want to use.

For example, if you want to use the version whose signature is
  bool Foo(int n);
you should write
  Truly(static_cast<bool (*)(int n)>(Foo))"""
  return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
                           regex, diagnosis, msg)

def _OverloadedFunctionActionDiagnoser(msg):
  """Diagnoses the OFA disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'error: no matching function for call to \'Invoke\('
           r'<unresolved overloaded function type>')
  diagnosis = """
You are passing an overloaded function to Invoke().  Please tell gcc
which overloaded version you want to use.

For example, if you want to use the version whose signature is
  bool MyFunction(int n, double x);
you should write something like
  Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
  return _GenericDiagnoser('OFA', 'Overloaded Function Action',
                           regex, diagnosis, msg)

def _OverloadedMethodActionDiagnoser1(msg):
  """Diagnoses the OMA disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'error: '
           r'.*no matching function for call to \'Invoke\(.*, '
           r'unresolved overloaded function type>')
  diagnosis = """
The second argument you gave to Invoke() is an overloaded method.  Please
tell gcc which overloaded version you want to use.

For example, if you want to use the version whose signature is
  class Foo {
    ...
    bool Bar(int n, double x);
  };
you should write something like
  Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
  return _GenericDiagnoser('OMA', 'Overloaded Method Action',
                           regex, diagnosis, msg)

def _MockObjectPointerDiagnoser(msg):
  """Diagnoses the MOP disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'error: request for member '
           r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
           r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
  diagnosis = """
The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
not a *pointer* to it.  Please write '*(%(mock_object)s)' instead of
'%(mock_object)s' as your first argument.

For example, given the mock class:

  class %(class_name)s : public ... {
    ...
    MOCK_METHOD0(%(method)s, ...);
  };

and the following mock instance:

  %(class_name)s* mock_ptr = ...

you should use the EXPECT_CALL like this:

  EXPECT_CALL(*mock_ptr, %(method)s(...));"""
  return _GenericDiagnoser('MOP', 'Mock Object Pointer',
                           regex, diagnosis, msg)

def _OverloadedMethodActionDiagnoser2(msg):
  """Diagnoses the OMA disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'error: no matching function for '
           r'call to \'Invoke\(.+, <unresolved overloaded function type>\)')
  diagnosis = """
The second argument you gave to Invoke() is an overloaded method.  Please
tell gcc which overloaded version you want to use.

For example, if you want to use the version whose signature is
  class Foo {
    ...
    bool Bar(int n, double x);
  };
you should write something like
  Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
  return _GenericDiagnoser('OMA', 'Overloaded Method Action',
                           regex, diagnosis, msg)

def _NeedToUseSymbolDiagnoser(msg):
  """Diagnoses the NUS disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
           r'(was not declared in this scope|has not been declared)')
  diagnosis = """
'%(symbol)s' is defined by Google Mock in the testing namespace.
Did you forget to write
  using testing::%(symbol)s;
?"""
  for m in _FindAllMatches(regex, msg):
    symbol = m.groupdict()['symbol']
    if symbol in _COMMON_GMOCK_SYMBOLS:
      yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())

def _NeedToUseReturnNullDiagnoser(msg):
  """Diagnoses the NRNULL disease, given the error messages by gcc."""

  regex = ('instantiated from \'testing::internal::ReturnAction<R>'
           '::operator testing::Action<Func>\(\) const.*\n' +
           _FILE_LINE_RE + r'instantiated from here\n'
           r'.*error: no matching function for call to \'implicit_cast\('
           r'long int&\)')
  diagnosis = """
You are probably calling Return(NULL) and the compiler isn't sure how to turn
NULL into the right type. Use ReturnNull() instead.
Note: the line number may be off; please fix all instances of Return(NULL)."""
  return _GenericDiagnoser('NRNULL', 'Need to use ReturnNull',
                           regex, diagnosis, msg)

_TTB_DIAGNOSIS = """
In a mock class template, types or typedefs defined in the base class
template are *not* automatically visible.  This is how C++ works.  Before
you can use a type or typedef named %(type)s defined in base class Base<T>, you
need to make it visible.  One way to do it is:

  typedef typename Base<T>::%(type)s %(type)s;"""

def _TypeInTemplatedBaseDiagnoser1(msg):
  """Diagnoses the TTB disease, given the error messages by gcc.

  This version works when the type is used as the mock function's return
  type.
  """

  gcc_4_3_1_regex = (
      r'In member function \'int .*\n' + _FILE_LINE_RE +
      r'error: a function call cannot appear in a constant-expression')
  gcc_4_4_0_regex = (
      r'error: a function call cannot appear in a constant-expression'
      + _FILE_LINE_RE + r'error: template argument 1 is invalid\n')
  diagnosis = _TTB_DIAGNOSIS % {'type': 'Foo'}
  return (list(_GenericDiagnoser('TTB', 'Type in Template Base',
                                gcc_4_3_1_regex, diagnosis, msg)) +
          list(_GenericDiagnoser('TTB', 'Type in Template Base',
                                 gcc_4_4_0_regex, diagnosis, msg)))

def _TypeInTemplatedBaseDiagnoser2(msg):
  """Diagnoses the TTB disease, given the error messages by gcc.

  This version works when the type is used as the mock function's sole
  parameter type.
  """

  regex = (_FILE_LINE_RE +
           r'error: \'(?P<type>.+)\' was not declared in this scope\n'
           r'.*error: template argument 1 is invalid\n')
  return _GenericDiagnoser('TTB', 'Type in Template Base',
                           regex, _TTB_DIAGNOSIS, msg)

def _TypeInTemplatedBaseDiagnoser3(msg):
  """Diagnoses the TTB disease, given the error messages by gcc.

  This version works when the type is used as a parameter of a mock
  function that has multiple parameters.
  """

  regex = (r'error: expected `;\' before \'::\' token\n'
           + _FILE_LINE_RE +
           r'error: \'(?P<type>.+)\' was not declared in this scope\n'
           r'.*error: template argument 1 is invalid\n'
           r'.*error: \'.+\' was not declared in this scope')
  return _GenericDiagnoser('TTB', 'Type in Template Base',
                           regex, _TTB_DIAGNOSIS, msg)

def _WrongMockMethodMacroDiagnoser(msg):
  """Diagnoses the WMM disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE +
           r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
           r'.*\n'
           r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
  diagnosis = """
You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
  return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
                           regex, diagnosis, msg)

def _WrongParenPositionDiagnoser(msg):
  """Diagnoses the WPP disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE +
           r'error:.*testing::internal::MockSpec<.* has no member named \''
           r'(?P<method>\w+)\'')
  diagnosis = """
The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
".%(method)s".  For example, you should write:
  EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
instead of:
  EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
  return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
                           regex, diagnosis, msg)

_DIAGNOSERS = [
    _IncompleteByReferenceArgumentDiagnoser,
    _MockObjectPointerDiagnoser,
    _NeedToReturnNothingDiagnoser,
    _NeedToReturnReferenceDiagnoser,
    _NeedToReturnSomethingDiagnoser,
    _NeedToUseReturnNullDiagnoser,
    _NeedToUseSymbolDiagnoser,
    _OverloadedFunctionActionDiagnoser,
    _OverloadedFunctionMatcherDiagnoser,
    _OverloadedMethodActionDiagnoser1,
    _OverloadedMethodActionDiagnoser2,
    _TypeInTemplatedBaseDiagnoser1,
    _TypeInTemplatedBaseDiagnoser2,
    _TypeInTemplatedBaseDiagnoser3,
    _WrongMockMethodMacroDiagnoser,
    _WrongParenPositionDiagnoser,
    ]

def Diagnose(msg):
  """Generates all possible diagnoses given the gcc error message."""

  diagnoses = []
  for diagnoser in _DIAGNOSERS:
    for diag in diagnoser(msg):
      diagnosis = '[%s - %s]\n%s' % diag
      if not diagnosis in diagnoses:
        diagnoses.append(diagnosis)
  return diagnoses

def main():
  print ('Google Mock Doctor v%s - '
         'diagnoses problems in code using Google Mock.' % _VERSION)

  if sys.stdin.isatty():
    print ('Please copy and paste the compiler errors here.  Press c-D when '
           'you are done:')
  else:
    print 'Waiting for compiler errors on stdin . . .'

  msg = sys.stdin.read().strip()
  diagnoses = Diagnose(msg)
  count = len(diagnoses)
  if not count:
    print '\nGcc complained:'
    print '8<------------------------------------------------------------'
    print msg
    print '------------------------------------------------------------>8'
    print """
Uh-oh, I'm not smart enough to figure out what the problem is. :-(
However...
If you send your source code and gcc's error messages to
googlemock@googlegroups.com, you can be helped and I can get smarter --
win-win for us!"""
  else:
    print '------------------------------------------------------------'
    print 'Your code appears to have the following',
    if count > 1:
      print '%s diseases:' % (count,)
    else:
      print 'disease:'
    i = 0
    for d in diagnoses:
      i += 1
      if count > 1:
        print '\n#%s:' % (i,)
      print d
    print """
How did I do?  If you think I'm wrong or unhelpful, please send your
source code and gcc's error messages to googlemock@googlegroups.com.  Then
you can be helped and I can get smarter -- I promise I won't be upset!"""

if __name__ == '__main__':
  main()

redpajama_set_name: RedPajamaGithub


text:
package com.ibm.javametrics.web;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * Websocket Endpoint implementation for JavametricsWebSocket
 */

@ServerEndpoint(value = "/javametrics-socket", subprotocols = "/")
public class JavametricsWebSocket implements Emitter {

    private Set<Session> openSessions = new HashSet<>();

    public JavametricsWebSocket() {
        super();
    }

    @OnOpen
    public void open(Session session) {
        try {
            session.getBasicRemote().sendText(
                    "{\"topic\": \"title\", \"payload\": {\"title\":\"Application Metrics for Java\", \"docs\": \"http://github.com/RuntimeTools/javametrics\"}}");
        } catch (IOException e) {
            e.printStackTrace();
        }
        openSessions.add(session);
        DataHandler.registerEmitter(this);
    }

    @OnClose
    public void close(Session session) {
        DataHandler.deregisterEmitter(this);
        openSessions.remove(session);
    }

    @OnError
    public void onError(Throwable error) {
    }

    @OnMessage
    public void handleMessage(String message, Session session) {
    }

    /*
     * (non-Javadoc)
     *
     * @see com.ibm.javametrics.MetricsEmitter#emit(java.lang.String)
     */
    public void emit(String message) {
        openSessions.forEach((session) -> {
            try {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}


text:
Big integration test of all tools

Our new story is:
- Start from an empty ontology.
- Add a concept 'Sequence' to the ontology that maps to 'java.util.LinkedList', 'Array', etc.
- Run checker framework to propagate the corresponding annotations in the corpus.
- Add concept 'Sorted Sequence' to the ontology which is a specialization of 'Sequence' with a sortedness invariant.
- Generate a Daikon pattern from the sortedness invariant.
- Find all methods that take a Sequence and produce a Sequence and establish that invariant.
- Use program similarity to find more methods like this (because dynamic analysis will only find a few).
- Order the resulting set by 'quality'.
- Pick the best implementation and add it back to the ontology as a cliche for sorting.

How to run:

    ./fetch_dependencies.sh

This downloads all the jars, compiles stuff, etc. Only needs to be run once.

    python backend.py

Compiles the corpus projects, generates tests and dtrace files, computes dot files, runs petablox.

    python frontend.py

or

    python frontend.py Sort04 Sort15

runs the main loop over the corpus, or the subset of corpus programs specified in the args.

Results of all tools running can be found on Travis:
[![Click here to see the Results of the experiments on TravisCI](https://travis-ci.org/aas-integration/integration-test.svg?branch=master)](https://travis-ci.org/aas-integration/integration-test)

# Obtaining LogicBlox

LogicBlox is released every month. It is available for download at
https://download.logicblox.com . To obtain a username and password for
this website, please fill out the form at
http://www.logicblox.com/learn/academic-license-request-form/ and
indicate that you are a MUSE team member.

LogicBlox offers Linux 64-bit as well as OSX distributions. If you
problems installing LogicBlox, please contact
muse-users@logicblox.com. You might want to be signed up for this
group as well!

Documentation is available at
https://developer.logicblox.com/documentation/ . Depending on what you
are most interested in, you want to check the reference manual or the
admin manual.

Just email martin.bravenboer@logicblox.com if you have any further
questions.


text:
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl" href="XSLT/Maps.xslt" ?>

<!--Ordered by Year ((1st)first year ascending, (2nd)final year ascending), then Alphabetic ((3rd)first name ascending)-->
<locations>
	<fromLocations>
		<state name="">
			<city name="">
				<instance name="" text="" />
			</city>
		</state>
		<state name="CA">
			<city name="American Canyon">
				<instance name="Dore Deffebaugh" text="2008-2009" />
			</city>
			<city name="Glendale">
				<instance name="Tomoyuki Matsushima" text="2004-2007" />
			</city>
			<city name="Inglewood">
				<instance name="DeAndre McCall" text="2005-2007" />
			</city>
			<city name="Moraga">
				<instance name="Michael Harlow" text="2005-2008" />
			</city>
			<city name="San Marino">
				<instance name="Noah Mathis" text="2013" />
			</city>
		</state>
		<state name="AZ">
			<city name="Scottsdale">
				<instance name="Victoria Langford" text="2004-2007" />
			</city>
		</state>
		<state name="TX">
			<city name="El Paso">
				<instance name="David Aguilar" text="2005-2008" />
			</city>
		</state>
		<state name="NE">
			<city name="Papillion">
				<instance name="Sam Plumb" text="2013" />
			</city>
		</state>
		<state name="WI">
			<city name="Madison">
				<instance name="Alexander Gebhart" text="2003-2005" />
			</city>
			<city name="Menasha">
				<instance name="Brian Timm" text="2004-2006" />
			</city>
			<city name="Tomah">
				<instance name="Jeffrey Arthur" text="2009" />
			</city>
		</state>
		<state name="IL">
			<city name="Glen Ellyn">
				<instance name="Karl Weintraub" text="2002-2005" />
			</city>
			<city name="Highland Park">
				<instance name="Jeffrey Atkins" text="2008-2011" />
			</city>
			<city name="Northbrook">
				<instance name="Stephen Uy" text="2010-2012" />
			</city>
		</state>
		<state name="MI">
			<city name="Adrian">
				<instance name="Kellen Marceau" text="2009-2013" />
			</city>
			<city name="Allen Park">
				<instance name="John DeBono" text="2013" />
			</city>
			<city name="Ann Arbor">
				<instance name="Brett Beel" text="2003-2005" />
				<instance name="Paul Winterhalter" text="2003-2005" />
				<instance name="Lewis Ezekiel" text="2004-2007" />
				<instance name="Abby Johnson" text="2006-2009" />
				<instance name="Kelsy Wilson" text="2006-2009" />
				<instance name="Jonathan Bower" text="2010-2013" />
				<instance name="Bill Grant" text="2011" />
				<instance name="Chris Haddlesey" text="2011" />
				<instance name="Patrick Wan" text="2012" />
				<instance name="Nicholas Terrell" text="2012-2013" />
			</city>
			<city name="Bad Axe">
				<instance name="Erin Mooney" text="2004" />
			</city>
			<city name="Battle Creek">
				<instance name="Matt Busch" text="2010" />
				<instance name="Santos Campos" text="2012-2013" />
			</city>
			<city name="Belleville">
				<instance name="Matthew Rodriguez" text="2004-2007" />
			</city>
			<city name="Berkley">
				<instance name="Mark Rulkowski" text="2008-2011" />
			</city>
			<city name="Birmingham">
				<instance name="Catherine Castellana" text="2005-2008" />
			</city>
			<city name="Blissfield">
				<instance name="Brian Cremean" text="2004-2006" />
			</city>
			<city name="Boyne City">
				<instance name="Kevin Wroblewski" text="2012" />
			</city>
			<city name="Brooklyn">
				<instance name="Ryan McKown" text="2006-2010" />
			</city>
			<city name="Canton"><!-- Canton is marked as Canton Township on the map -->
				<instance name="Paul Sutherland" text="2005-2007" />
			</city>
			<city name="Carson City">
				<instance name="Logan McClintic" text="2012-2013" />
			</city>
			<city name="Cass City">
				<instance name="Timothy Khoury" text="2002-2005" />
			</city>
			<city name="Clinton Township">
				<instance name="Jake Gondek" text="2012-2013" />
				<instance name="Brett Zablocki" text="2013" />
			</city>
			<city name="Commerce Township">
				<instance name="Brian Daniels" text="2011-2013" />
				<instance name="Ryan O'Keefe" text="2013" />
			</city>
			<city name="Davison">
				<instance name="Tyler Kane" text="2012-2013" />
			</city>
			<city name="Detroit">
				<instance name="Sierra Cain" text="2007-2010" />
			</city>
			<city name="DeWitt">
				<instance name="Zachary Ruch" text="2010-2013" />
			</city>
			<city name="Dexter">
				<instance name="Daniel Roberts" text="2004-2007" />
				<instance name="Sam Laidlaw" text="2010-2013" />
			</city>
			<city name="Durand">
				<instance name="Samuel Cain" text="2013" />
			</city>
			<city name="East Grand Rapids">
				<instance name="Greg King" text="1999-2000" />
			</city>
			<city name="East Lansing">
				<instance name="Andrew Wood" text="2011-2013" />
			</city>
			<city name="Escanaba">
				<instance name="Shane Myrik" text="2010-2013" />
			</city>
			<city name="Farmington Hills">
				<instance name="Michael Carlson" text="2008-2011" />
				<instance name="Kyle McDevitt" text="2008-2011" />
				<instance name="Andrew Schumacher" text="2009-2013" />
				<instance name="Neil Banchero-Smith" text="2011-2013" />
				<instance name="Peter Romero" text="2013" />
				<instance name="Timothy Schumacher" text="2013" />
			</city>
			<city name="Ferndale">
				<instance name="Peter Ceglarek" text="2010-2011" />
			</city>
			<city name="Franklin">
				<instance name="Adam Fisher" text="2010-2013" />
			</city>
			<city name="Galesburg">
				<instance name="Anthony Fici" text="2013" />
			</city>
			<city name="Grandville">
				<instance name="Eric Burkman" text="2004-2006" />
			</city>
			<city name="Grand Rapids">
				<instance name="Jen Cisler" text="2004-2007" />
				<instance name="Andrew Monks" text="2006" />
				<instance name="Whitaker Martin" text="2006-2009" />
			</city>
			<city name="Grayling">
				<instance name="Christopher Wells" text="2008-2011" />
			</city>
			<city name="Grosse Pointe Woods">
				<instance name="Christopher Jenkins" text="2011-2013" />
			</city>
			<city name="Harrison Twp.">
				<instance name="Mitch Bradley" text="2004-2007" />
			</city>
			<city name="Haslett">
				<instance name="Jacob Zimmerman" text="2013" />
			</city>
			<city name="Hastings">
				<instance name="Matthew Hoffman" text="2005-2007" />
				<instance name="Jason Bies" text="2007-2010" />
			</city>
			<city name="Holland">
				<instance name="Marco Krcatovich" text="2000-2004" />
				<instance name="Natalie Setterberg" text="2012-2013" />
			</city>
			<city name="Holt">
				<instance name="Brian Rudd" text="2003-2006" />
			</city>
			<city name="Howard City">
				<instance name="Allen Fisher" text="2004-2007" />
			</city>
			<city name="Hudson">
				<instance name="Eric Heininger" text="2003-2005" />
			</city>
			<city name="Hudsonville">
				<instance name="Pete Dahl" text="2012-2013" />
			</city>
			<city name="Huntington Woods">
				<instance name="Andrew Lapin" text="2007-2009" />
			</city>
			<city name="Jackson">
				<instance name="Desmond Davis" text="2008" />
				<instance name="Anthony Sexton" text="2012-2013" />
			</city>
			<city name="Jerome">
				<instance name="Kaili McKnight" text="2007-2010" />
			</city>
			<city name="Lake Orion">
				<instance name="Michael Roberts" text="2012-2013" />
			</city>
			<city name="Livonia">
				<instance name="Jon Tap" text="2006-2008" />
			</city>
			<city name="Manistee">
				<instance name="Laura Lindgren" text="2009-2012" />
			</city>
			<city name="Marshall">
				<instance name="Devin Hurst" text="2003-2006" />
			</city>
			<city name="Marysville">
				<instance name="Breanna Duso" text="2010-2013" />
			</city>
			<city name="Mason">
				<instance name="Alexandra Genia" text="2008-2011" />
			</city>
			<city name="Midland">
				<instance name="Andrew Mitchell" text="2008-2011" />
				<instance name="Molly Drlik" text="2010-2013" />
			</city>
			<city name="Muskegon">
				<instance name="Sean Collins" text="2005" />
			</city>
			<city name="New Boston">
				<instance name="Greg Baker" text="2005-2008" />
				<instance name="Antoinette Ruffolo" text="2007" />
			</city>
			<city name="New Buffalo">
				<instance name="Natalie Blackwood" text="2011-2013" />
			</city>
			<city name="Northville">
				<instance name="Caitlin Northcutt" text="2008-2011" />
				<instance name="Ryuta Oshikiri" text="2008-2011" />
				<instance name="Jeffrey Okala" text="2011-2012" />
				<instance name="Yutaka Oshikiri" text="2011-2013" />
			</city>
			<city name="Novi">
				<instance name="Jeffrey Gdowski" text="2001-2005" />
				<instance name="Andrew Laskowski" text="2003-2006" />
				<instance name="Chris Rodgers" text="2004-2008" />
				<instance name="Jake Hoernschemeyer" text="2006-2009" />
				<instance name="T.J. Wolfgram" text="2008, 2010" />
			</city>
			<city name="Onsted">
				<instance name="Duane Breijak" text="2003-2007" />
			</city>
			<city name="Owosso">
				<instance name="Allison George" text="2013" />
			</city>
			<city name="Parma">
				<instance name="Timothy Collins" text="2005-2007" />
			</city>
			<city name="Pewamo">
				<instance name="Joseph Stoddard" text="2010-2012" />
			</city>
			<city name="Plymouth">
				<instance name="Marten Hawkins" text="2009-2011" />
				<instance name="Nick Battishill" text="2011-2013" />
			</city>
			<city name="Portage">
				<instance name="Jeremy Bronson" text="2002-2005" />
				<instance name="Nathan Werme" text="2009-2012" />
			</city>
			<city name="Rapid River">
				<instance name="Nathan Bennett" text="2005-2008" />
			</city>
			<city name="Redford">
				<instance name="K. Scott Tripp" text="2007-2009" />
			</city>
			<city name="Rochester Hills">
				<instance name="Brian Green" text="2003-2006" />
				<instance name="Nick Gasperoni" text="2004-2007" />
				<instance name="Jeffrey Zebrowski" text="2005-2008" />
				<instance name="Michaella DeRubeis" text="2013" />
			</city>
			<city name="Saline">
				<instance name="Annaka Voss" text="2005-2006" />
				<instance name="Grace Wolfe" text="2010-2013" />
				<instance name="Ian Wolfe" text="2013" />
			</city>
			<city name="Southgate">
				<instance name="Marie Gentile" text="2013" />
			</city>
			<city name="South Haven">
				<instance name="Shawna Mulvihill" text="2013" />
			</city>
			<city name="South Lyon">
				<instance name="Eric Heininger" text="2003-2005" />
				<instance name="Aaron Schoeff" text="2004-2007" />
			</city>
			<city name="St. Ignace">
				<instance name="Sarah Springsteen" text="2001-2003, 2005" />
			</city>
			<city name="Sterling Heights">
				<instance name="John Zalewski" text="2003-2006" />
			</city>
			<city name="Stevensville">
				<instance name="Amy Rydleski" text="2005-2008" />
			</city>
			<city name="Taylor">
				<instance name="Ikenna Anyanetu" text="2007-2009" />
				<instance name="Adam Winnie" text="2010-2012" />
				<instance name="Nathan Steeby" text="2012" />
			</city>
			<city name="Traverse City">
				<instance name="Jesse Belanger" text="2008-2010" />
				<instance name="Trent Hibbard" text="2010-2013" />
			</city>
			<city name="Temperance">
				<instance name="Michael Bacon" text="2010-2013" />
				<instance name="Elizabeth Smith" text="2011-2013" />
			</city>
			<city name="Trenton">
				<instance name="John Eagal" text="2003-2006" />
			</city>
			<city name="Troy">
				<instance name="Michael Carroll" text="2002-2005" />
				<instance name="Jonathan Beaumont" text="2009-2012" />
				<instance name="Stanley Smith" text="2012-2013" />
			</city>
			<city name="Vicksburg">
				<instance name="Melissa Beams" text="2004-2007" />
				<instance name="Christian Hatfield" text="2006-2009" />
			</city>
			<city name="Walker">
				<instance name="Bill Melville" text="2005-2008" />
			</city>
			<city name="Warren">
				<instance name="Matthew Vujovich" text="2007-2010" />
				<instance name="Alexander Birch" text="2011-2013" />
				<instance name="Ellyse Vogel" text="2012-2013" />
			</city>
			<city name="Watervliet">
				<instance name="Taylor Gast" text="2006-2009" />
			</city>
			<city name="Wayne">
				<instance name="Solomon Shurge" text="2009-2013" />
			</city>
			<city name="West Bloomfield">
				<instance name="Mark Coldren" text="2010-2011" />
			</city>
			<city name="White Cloud">
				<instance name="Keith Trice" text="2003-2005" />
			</city>
			<city name="Williamsburg">
				<instance name="Ryan Parlin" text="2010-2012" />
			</city>
			<city name="Williamston">
				<instance name="Annalisa Grunwald" text="2004-2005" />
			</city>
			<city name="Zeeland">
				<instance name="Kyle Lutz" text="2009-2010" />
			</city>
		</state>
		<state name="IN">
			<city name="Lebanon">
				<instance name="Zachary Wall" text="2013" />
			</city>
		</state>
		<state name="AL">
			<city name="Madison">
				<instance name="Michael Spratley" text="2003-2005" />
			</city>
		</state>
		<state name="OH">
			<city name="Columbus">
				<instance name="Becky Shapiro" text="2004-2007" />
			</city>
			<city name="Dublin">
				<instance name="Bryan DeGrendel" text="2005-2008" />
			</city>
			<city name="Wilmington">
				<instance name="Joseph Lohrum" text="2002-2006" />
			</city>
			<city name="Wooster">
				<instance name="Jack Hall" text="2006-2007" />
			</city>
		</state>
		<state name="GA">
			<city name="Atlanta">
				<instance name="Trevor Dworetz" text="2011-2013" />
			</city>
		</state>
		<state name="FL">
			<city name="Winter Garden">
				<instance name="Clay Mikush" text="2012-2013" />
			</city>
		</state>
		<state name="VA">
			<city name="Newport News">
				<instance name="Chris Butler" text="2003-2006" />
			</city>
		</state>
		<state name="DE">
			<city name="Newark">
				<instance name="Peter Chi" text="2000-2002" />
			</city>
		</state>
		<state name="PA">
			<city name="Malvern">
				<instance name="Brian Herrick" text="2006-2009" />
			</city>
		</state>
		<state name="NJ">
			<city name="Basking Ridge">
				<instance name="Katelyn Stover" text="2011-2013" />
			</city>
			<city name="Medford">
				<instance name="Eric Pesch" text="2009-2012" />
			</city>
			<city name="Pennington">
				<instance name="Darren Gross" text="2010-2013" />
			</city>
			<city name="Westfield">
				<instance name="Alex Ying" text="2013" />
			</city>
		</state>
		<state name="NY">
			<city name="Brewster">
				<instance name="Richie Grasso" text="2008" />
			</city>
			<city name="Highland">
				<instance name="Jason Krystek" text="2009-2011" />
			</city>
			<city name="Williamsville">
				<instance name="Max Lustig" text="2010-2013" />
			</city>
		</state>
		<state name="CT">
			<city name="Gales Ferry">
				<instance name="Ian Baker" text="2011-2013" />
			</city>
		</state>
	</fromLocations>
	<homeLocations>
		<state name="WA">
			<city name="Seattle">
				<instance name="Brian Timm" text="2004-2006" />
				<instance name="Jen Cisler" text="2004-2007" />
			</city>
		</state>
		<state name="CA">
			<city name="Hermosa Beach">
				<instance name="John Zalewski" text="2003-2006" />
			</city>
			<city name="San Francisco">
				<instance name="Ryuta Oshikiri" text="2008-2011" />
			</city>
			<city name="San Luis Obispo">
				<instance name="Peter Chi" text="2000-2002" />
			</city>
		</state>
		<state name="TX">
			<city name="Austin">
				<instance name="Ian Kahn" text="2000-2003" />
			</city>
			<city name="Dallas">
				<instance name="Amy Rydleski" text="2005-2008" />
			</city>
		</state>
		<state name="MN">
			<city name="St. Paul">
				<instance name="Michael Harlow" text="2005-2008" />
			</city>
		</state>
		<state name="MS">
			<city name="Starkville">
				<instance name="Jason Bies" text="2007-2010" />
			</city>
		</state>
		<state name="IL">
			<city name="Chicago">
				<instance name="Eric Heininger" text="2003-2005" />
			</city>
		</state>
		<state name="MI">
			<city name="Ann Arbor">
				<instance name="Nathan Werme" text="2009-2012" />
			</city>
			<city name="Grand Rapids">
				<instance name="Greg King" text="1999-2000" />
			</city>
		</state>
		<state name="MD">
			<city name="Nottingham">
				<instance name="Erin Mooney" text="2004" />
			</city>
		</state>
		<state name="CT">
			<city name="New Haven">
				<instance name="Eric Heininger" text="2003-2005" />
				<instance name="Brian Green" text="2003-2006" />
			</city>
		</state>
		<state name="Spain">
			<city name="Lugo">
				<instance name="Bill Melville" text="2005-2008" />
			</city>
		</state>
		<state name="France">
			<city name="Paris">
				<instance name="Kelsy Wilson" text="2006-2009" />
			</city>
		</state>
		<state name="Germany">
			<city name="Meitingen">
				<instance name="Ryan McKown" text="2006-2010" />
			</city>
		</state>
	</homeLocations>
	<bowlTripLocations>
	</bowlTripLocations>
	<boneTripLocations>
	</boneTripLocations>
</locations>


text:
using MatterHackers.Agg.UI;
using MatterHackers.RayTracer;
using MatterHackers.VectorMath;
using System;

namespace MatterHackers.MeshVisualizer
{
	public class MouseEvent3DArgs : EventArgs
	{
		public IntersectInfo info;
		public MouseEventArgs MouseEvent2D;
		private Ray mouseRay;

		public Ray MouseRay { get { return mouseRay; } }

		public MouseEvent3DArgs(MouseEventArgs mouseEvent2D, Ray mouseRay, IntersectInfo info)
		{
			this.info = info;
			this.MouseEvent2D = mouseEvent2D;
			this.mouseRay = mouseRay;
		}
	}
}


text:
package androidx.slice.compat;

import static androidx.core.content.PermissionChecker.PERMISSION_DENIED;
import static androidx.core.content.PermissionChecker.PERMISSION_GRANTED;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;

import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Process;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import androidx.test.filters.SdkSuppress;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

@RunWith(AndroidJUnit4.class)
@LargeTest
@SdkSuppress(minSdkVersion = 19)
public class CompatPermissionManagerTest {

    private final Context mContext = ApplicationProvider.getApplicationContext();

    @FlakyTest
    @Test
    public void testAutoGrant() {
        final Uri uri = new Uri.Builder()
                .scheme(ContentResolver.SCHEME_CONTENT)
                .authority("my.authority")
                .path("my_path")
                .build();
        final String testPermission = "android.permission.SOME_PERMISSION";

        final int grantedPid = Process.myPid();
        final int grantedUid = Process.myUid();

        final int nonGrantedPid = grantedPid + 1;
        final int nonGrantedUid = grantedUid + 1;

        Context permContext = new ContextWrapper(mContext) {
            @Override
            public int checkPermission(String permission, int pid, int uid) {
                if (testPermission.equals(permission)) {
                    if (grantedUid == uid) {
                        return PackageManager.PERMISSION_GRANTED;
                    } else if (nonGrantedUid == uid) {
                        return PackageManager.PERMISSION_DENIED;
                    }
                }
                return super.checkPermission(permission, pid, uid);
            }

            @Override
            public PackageManager getPackageManager() {
                final PackageManager realPm = super.getPackageManager();
                PackageManager pm = mock(PackageManager.class, withSettings()
                        .defaultAnswer(new Answer() {
                            @Override
                            public Object answer(InvocationOnMock invocation) throws Throwable {
                                return invocation.getMethod().invoke(realPm,
                                        invocation.getArguments());
                            }
                        }));
                when(pm.getPackagesForUid(grantedUid)).thenReturn(new String[] { "grant_pkg"});
                when(pm.getPackagesForUid(nonGrantedUid)).thenReturn(new String[] { "other_pkg"});
                return pm;
            }
        };
        CompatPermissionManager manager = spy(new CompatPermissionManager(permContext, "nothing", 0,
                new String[] {testPermission}));

        assertEquals(PERMISSION_DENIED, manager.checkSlicePermission(uri,
                nonGrantedPid, nonGrantedUid));

        assertEquals(PERMISSION_GRANTED, manager.checkSlicePermission(uri, grantedPid, grantedUid));
        verify(manager).grantSlicePermission(eq(uri), eq("grant_pkg"));

    }

}


text:
id: 5900f3df1000cf542c50fef1
challengeType: 5
title: 'Problem 115: Counting block combinations II'
forumTopicId: 301741
localeTitle: 'Задача 115: Комбинации счетных блоков II'
---

## Description

ПРИМЕЧАНИЕ. Это более сложная версия задачи 114. Строка, измеряющая n единиц длины, имеет красные блоки с минимальной длиной м единиц, размещенных на ней, так что любые два красных блока (которые допускаются к разным длинам) разделяются по крайней мере, одним черным квадратом. Пусть функция заполнения, F (m, n), представляет количество способов заполнения строки. Например, F (3, 29) = 673135 и F (3, 30) = 1089155. То есть, при m = 3 можно видеть, что n = 30 является наименьшим значением, для которого функция заполнения один миллион. Точно так же при m = 10 можно проверить, что F (10, 56) = 880711 и F (10, 57) = 1148904, поэтому n = 57 является наименьшим значением, для которого функция заполнения один миллион. При m = 50 найдите наименьшее значение n, для которого функция заполнения заполнения сначала превышает один миллион.

## Instructions

## Tests

```yml
tests:
  - text: <code>euler115()</code> should return 168.
    testString: assert.strictEqual(euler115(), 168);

```

## Challenge Seed

```js
function euler115() {
  // Good luck!
  return true;
}

euler115();

```

## Solution

```js
// solution required
```


text:
package com.xwray.groupie.example.databinding;

import android.content.Intent;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.xwray.groupie.ExpandableGroup;
import com.xwray.groupie.Group;
import com.xwray.groupie.GroupieAdapter;
import com.xwray.groupie.GroupieViewHolder;
import com.xwray.groupie.Item;
import com.xwray.groupie.OnItemClickListener;
import com.xwray.groupie.OnItemLongClickListener;
import com.xwray.groupie.Section;
import com.xwray.groupie.TouchCallback;
import com.xwray.groupie.example.core.InfiniteScrollListener;
import com.xwray.groupie.example.core.Prefs;
import com.xwray.groupie.example.core.SettingsActivity;
import com.xwray.groupie.example.core.decoration.CarouselItemDecoration;
import com.xwray.groupie.example.core.decoration.DebugItemDecoration;
import com.xwray.groupie.example.core.decoration.SwipeTouchCallback;
import com.xwray.groupie.example.databinding.databinding.ActivityMainBinding;
import com.xwray.groupie.example.databinding.item.CardItem;
import com.xwray.groupie.example.databinding.item.CarouselCardItem;
import com.xwray.groupie.example.databinding.item.ColumnItem;
import com.xwray.groupie.example.databinding.item.DraggableItem;
import com.xwray.groupie.example.databinding.item.FullBleedCardItem;
import com.xwray.groupie.example.databinding.item.HeaderItem;
import com.xwray.groupie.example.databinding.item.HeartCardItem;
import com.xwray.groupie.example.databinding.item.SmallCardItem;
import com.xwray.groupie.example.databinding.item.SwipeToDeleteItem;
import com.xwray.groupie.example.databinding.item.UpdatableItem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static final String INSET_TYPE_KEY = "inset_type";
    public static final String FULL_BLEED = "full_bleed";
    public static final String INSET = "inset";

    private ActivityMainBinding binding;
    private GroupieAdapter groupAdapter;
    private GridLayoutManager layoutManager;
    private Prefs prefs;

    private int gray;
    private int betweenPadding;
    private int[] rainbow200;
    private int[] rainbow500;

    private Section infiniteLoadingSection;
    private Section swipeSection;
    private Section dragSection;

    // Normally there's no need to hold onto a reference to this list, but for demonstration
    // purposes, we'll shuffle this list and post an update periodically
    private ArrayList<UpdatableItem> updatableItems;

    // Hold a reference to the updating group, so we can, well, update it
    private Section updatingGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        prefs = Prefs.get(this);

        gray = ContextCompat.getColor(this, R.color.background);
        betweenPadding = getResources().getDimensionPixelSize(R.dimen.padding_small);
        rainbow200 = getResources().getIntArray(R.array.rainbow_200);
        rainbow500 = getResources().getIntArray(R.array.rainbow_500);

        groupAdapter = new GroupieAdapter();
        groupAdapter.setOnItemClickListener(onItemClickListener);
        groupAdapter.setOnItemLongClickListener(onItemLongClickListener);
        groupAdapter.setSpanCount(12);
        populateAdapter();
        layoutManager = new GridLayoutManager(this, groupAdapter.getSpanCount());
        layoutManager.setSpanSizeLookup(groupAdapter.getSpanSizeLookup());

        final RecyclerView recyclerView = binding.recyclerView;
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HeaderItemDecoration(gray, betweenPadding));
        recyclerView.addItemDecoration(new InsetItemDecoration(gray, betweenPadding));
        recyclerView.addItemDecoration(new DebugItemDecoration(this));
        recyclerView.setAdapter(groupAdapter);
        recyclerView.addOnScrollListener(new InfiniteScrollListener(layoutManager) {
            @Override public void onLoadMore(int currentPage) {
                for (int i = 0; i < 5; i++) {
                    infiniteLoadingSection.add(new CardItem());
                }
            }
        });

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(touchCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            }
        });

        prefs.registerListener(onSharedPrefChangeListener);
    }

    private void populateAdapter() {

        // Full bleed item
        Section fullBleedItemSection = new Section(new HeaderItem(R.string.full_bleed_item));
        fullBleedItemSection.add(new FullBleedCardItem());
        groupAdapter.add(fullBleedItemSection);

        // Update in place group
        Section updatingSection = new Section();
        View.OnClickListener onShuffleClicked = new View.OnClickListener() {
            @Override public void onClick(View view) {
                List<UpdatableItem> shuffled = new ArrayList<>(updatableItems);
                Collections.shuffle(shuffled);
                updatingGroup.update(shuffled);

                // You can also do this by forcing a change with payload
                binding.recyclerView.post(new Runnable() {
                    @Override public void run() {
                        binding.recyclerView.invalidateItemDecorations();
                    }
                });
            }
        };
        HeaderItem updatingHeader = new HeaderItem(
                R.string.updating_group,
                R.string.updating_group_subtitle,
                R.drawable.shuffle,
                onShuffleClicked);
        updatingSection.setHeader(updatingHeader);
        updatingGroup = new Section();
        updatableItems = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            updatableItems.add(new UpdatableItem(i));
        }
        updatingGroup.update(updatableItems);
        updatingSection.add(updatingGroup);
        groupAdapter.add(updatingSection);

        // Expandable group
        ExpandableHeaderItem expandableHeaderItem = new ExpandableHeaderItem(R.string.expanding_group, R.string.expanding_group_subtitle);
        ExpandableGroup expandableGroup = new ExpandableGroup(expandableHeaderItem);
        for (int i = 0; i < 2; i++) {
            expandableGroup.add(new CardItem());
        }
        groupAdapter.add(expandableGroup);

        // Columns
        Section columnSection = new Section(new HeaderItem(R.string.vertical_columns));
        ColumnGroup columnGroup = makeColumnGroup();
        columnSection.add(columnGroup);
        groupAdapter.add(columnSection);

        // Group showing even spacing with multiple columns
        Section multipleColumnsSection = new Section(new HeaderItem(R.string.multiple_columns));
        for (int i = 0; i < 12; i++) {
            multipleColumnsSection.add(new SmallCardItem());
        }
        groupAdapter.add(multipleColumnsSection);

        // Swipe to delete (with add button in header)
        swipeSection = new Section(new HeaderItem(R.string.swipe_to_delete));
        for (int i = 0; i < 3; i++) {
            swipeSection.add(new SwipeToDeleteItem(rainbow200[6]));
        }
        groupAdapter.add(swipeSection);

        dragSection = new Section(new HeaderItem(R.string.drag_to_reorder));
        dragSection.clear();
        for (int i = 0; i < 5; i++) {
            dragSection.add(new DraggableItem(rainbow500[i]));
        }
        groupAdapter.add(dragSection);

        // Horizontal carousel
        Section carouselSection = new Section(new HeaderItem(R.string.carousel, R.string.carousel_subtitle));
        carouselSection.setHideWhenEmpty(true);
        Group carousel = makeCarouselGroup();
        carouselSection.add(carousel);
        groupAdapter.add(carouselSection);

        // Update with payload
        Section updateWithPayloadSection = new Section(new HeaderItem(R.string.update_with_payload, R.string.update_with_payload_subtitle));
        for (int i = 0; i < rainbow500.length; i++) {
            updateWithPayloadSection.add(new HeartCardItem(i, onFavoriteListener));

        }
        groupAdapter.add(updateWithPayloadSection);

        // Infinite loading section
        infiniteLoadingSection = new Section(new HeaderItem(R.string.infinite_loading));
        groupAdapter.add(infiniteLoadingSection);
    }

    private ColumnGroup makeColumnGroup() {
        List<ColumnItem> columnItems = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            // First five items are red -- they'll end up in a vertical column
            columnItems.add(new ColumnItem(i));
        }
        for (int i = 6; i <= 10; i++) {
            // Next five items are pink
            columnItems.add(new ColumnItem(i));
        }
        return new ColumnGroup(columnItems);
    }

    private Group makeCarouselGroup() {
        CarouselItemDecoration carouselDecoration = new CarouselItemDecoration(gray, betweenPadding);
        GroupieAdapter carouselAdapter = new GroupieAdapter();
        for (int i = 0; i < 10; i++) {
            carouselAdapter.add(new CarouselCardItem(rainbow200[i]));
        }
        return new CarouselGroup(carouselDecoration, carouselAdapter);
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(Item item, View view) {
            if (item instanceof CardItem) {
                CardItem cardItem = (CardItem) item;
                if (!TextUtils.isEmpty(cardItem.getText())) {
                    Toast.makeText(MainActivity.this, cardItem.getText(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    private OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(Item item, View view) {
            if (item instanceof CardItem) {
                CardItem cardItem = (CardItem) item;
                if (!TextUtils.isEmpty(cardItem.getText())) {
                    Toast.makeText(MainActivity.this, "Long clicked: " + cardItem.getText(), Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return false;
        }
    };

    @Override protected void onDestroy() {
        prefs.unregisterListener(onSharedPrefChangeListener);
        super.onDestroy();
    }

    private TouchCallback touchCallback = new SwipeTouchCallback() {
        @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            Item item = groupAdapter.getItem(viewHolder.getBindingAdapterPosition());
            Item targetItem = groupAdapter.getItem(target.getBindingAdapterPosition());

            List<Group> dragItems = dragSection.getGroups();
            int targetIndex = dragItems.indexOf(targetItem);
            dragItems.remove(item);

            // if item gets moved out of the boundary
            if (targetIndex == -1) {
                if (target.getBindingAdapterPosition() < viewHolder.getBindingAdapterPosition()) {
                    targetIndex = 0;
                } else {
                    targetIndex = dragItems.size() - 1;
                }
            }

            dragItems.add(targetIndex, item);
            dragSection.update(dragItems);
            return true;
        }

        @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            Item item = groupAdapter.getItem(viewHolder.getBindingAdapterPosition());
            // Change notification to the adapter happens automatically when the section is
            // changed.
            swipeSection.remove(item);
        }
    };

    private SharedPreferences.OnSharedPreferenceChangeListener onSharedPrefChangeListener =
            new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
                    // This is pretty evil, try not to do this
                    groupAdapter.notifyDataSetChanged();
                }
            };

    private Handler handler = new Handler();
    private HeartCardItem.OnFavoriteListener onFavoriteListener = new HeartCardItem.OnFavoriteListener() {
        @Override
        public void onFavorite(final HeartCardItem item, final boolean favorite) {
            // Pretend to make a network request
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Network request was successful!
                    item.setFavorite(favorite);
                    item.notifyChanged(HeartCardItem.FAVORITE);
                }
            }, 1000);
        }
    };

}


text:
HMIWorker is a standalone singleton which processes HMI actions. If you want to
have a customized HMI instead the one integrated with Apollo Dreamview, just
develope a frontend and send operations to the backend which delegates to
HMIWorker.

## HMI Config

See modules/dreamview/proto/hmi_config.proto. It defines all supported modes,
modules, hardware and tools.

## HMI Worker

According to the HMIConfig, HMI Worker could trigger actions like:
- Change mode, map, vehicle and driving mode.
- Register event handler for changing mode, map and vehicle.
- Start, stop or execute other registered commands for modules.
- Execute registered tools.
- Submit DriveEvent which will be recorded as a ROS message.
- Get current HMIConfig and HMIStatus, which could be used for UI update.

## Vehicle Manager

VehicleManager is the one to actually config everything when changing vehicles.
The major thing is to copy all vehicle-wised parameter files to right place. The
source and destination mappings are defined by
modules/dreamview/conf/vehicle_data.pb.txt.


text:
package com.jivesoftware.os.amzabot.deployable.endpoint;

import com.jivesoftware.os.amzabot.deployable.AmzaBotService;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import io.swagger.annotations.Api;
import java.util.Map.Entry;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Api(value = "Amza Bot")
@Singleton
@Path("/api/amzabot/v1")
public class AmzaBotEndpoints {

    private static final MetricLogger LOG = MetricLoggerFactory.getLogger();

    private final AmzaBotService service;

    public AmzaBotEndpoints(@Context AmzaBotService service) {
        this.service = service;
    }

    @POST
    @Path("/keys/{name}")
    public Response set(@PathParam("name") String key, String value) {
        try {
            service.set(key, value);
            return Response.accepted().build();
        } catch (Exception e) {
            LOG.error("Failed to handle set name:{} {}", new Object[] { key, value }, e);
            return Response.serverError().build();
        }
    }

    @POST
    @Path("/keys")
    public Response set(Set<Entry<String, String>> entries) {
        try {
            service.multiSet(entries);
            return Response.accepted().build();
        } catch (Exception e) {
            LOG.error("Failed to handle set batch: {}", new Object[] { entries }, e);
            return Response.serverError().build();
        }
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/keys/{name}")
    public Response get(@PathParam("name") String key) {
        try {
            String value = service.get(key);
            if (value == null) {
                return Response.noContent().build();
            }

            return Response.ok(value).build();
        } catch (Exception e) {
            LOG.error("Failed to handle get name:{}", new Object[] { key }, e);
            return Response.serverError().build();
        }
    }

    @DELETE
    @Path("/keys/{name}")
    public Response delete(@PathParam("name") String key) {
        try {
            String value = service.delete(key);
            if (value == null) {
                return Response.noContent().build();
            }

            return Response.accepted().build();
        } catch (Exception e) {
            LOG.error("Failed to handle delete name:{}", new Object[] { key }, e);
            return Response.serverError().build();
        }
    }

}


text:
define(function (require) {

  'use strict';

  /**
   * Module dependencies
   */

  var defineComponent = require('flight/lib/component');
  var templates = require('templates');
  var _ = require('underscore');

  /**
   * Module exports
   */

  return defineComponent(tweetItems);

  /**
   * Module function
   */

  function tweetItems() {
    this.defaultAttrs({
      tag: null
    });

    var MAX_TWEETS = 30;

    this.render = function () {
      this.$node.html(templates.tweetItems());
      this.node.querySelector('template').model = { tweets: this.tweets };
      Platform.performMicrotaskCheckpoint();
    };

    this.onStreamData = function (results) {
      _.each(results, function (tweet) {
        this.tweets.unshift(tweet);
      }.bind(this));
      // Setting the maximum after everything has been added.
      this.tweets.splice(MAX_TWEETS);

      Platform.performMicrotaskCheckpoint();
    };

    this.after('initialize', function () {
      this.tweets = [];

      this.render();
      this.on(document, 'dataSearchStreamReceived', function (ev, data) {
        if (data.tag === this.attr.tag) {
          this.onStreamData(data.results);
        }
      });
    });
  }

});


text:
package org.lable.rfc3881.auditlogger.adapter.sl4fj;

import org.junit.Test;
import org.lable.codesystem.codereference.CodeReference;
import org.lable.rfc3881.auditlogger.api.*;
import org.lable.rfc3881.auditlogger.definition.rfc3881.*;
import org.slf4j.Logger;
import org.slf4j.MarkerFactory;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;

import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class SLF4JAdapterTest {
    @Test
    public void recordTest() throws NoSuchFieldException, IllegalAccessException, IOException {
        AuditLogAdapter auditLogAdapter = new SLF4JAdapter();
        Logger mockLogger = setMockLogger((SLF4JAdapter) auditLogAdapter);

        LogEntry logEntry = new LogEntry(
                new Event(new CodeReference("events", "logon", "log-on"), EventAction.EXECUTE, EventOutcome.SUCCESS),
                new Principal("bob", (String) null, "Bob Jones", new CodeReference("roles", "user", "authenticated user")),
                null,
                null,
                NetworkAccessPoint.byIPAddress("127.0.0.1"),
                Collections.singletonList(
                        new AuditSource("servercluster1", "tomcat1", AuditSourceType.WEB_SERVER_PROCESS)),
                Collections.singletonList(
                        new ParticipantObject("bob",
                                ParticipantObjectType.PERSON,
                                ParticipantObjectIDType.USER_IDENTIFIER,
                                ParticipantObjectTypeRole.USER,
                                DataLifeCycle.ACCESS_OR_USE,
                                new CodeReference("sensitivity", "TOPSECRET", "Quite secret"),
                                "Bob Jones",
                                "TEST",
                                new ParticipantObject.Detail(
                                        new CodeReference("detail", "DT1", "Detail 1"),
                                        "Detail"
                                ))
                ),
                new CodeReference("version", "1", "1")
        );

        auditLogAdapter.record(logEntry);

        verify(mockLogger).info(eq(MarkerFactory.getMarker("AUDIT")), anyString());
    }

    // Set up a mock logger in the 'final' logger field.
    private Logger setMockLogger(SLF4JAdapter slf4JAdapter) throws NoSuchFieldException, IllegalAccessException {
        Logger mockLogger = mock(Logger.class);
        Field field = slf4JAdapter.getClass().getDeclaredField("logger");
        field.setAccessible(true);
        // Remove final modifier from field.
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        field.set(slf4JAdapter, mockLogger);
        return mockLogger;
    }
}


text:
<?php

namespace Cubiche\Core\Metadata\Tests\Fixtures;

use Cubiche\Core\Collections\ArrayCollection\ArraySet;
use Cubiche\Core\Collections\ArrayCollection\ArraySetInterface;
use Cubiche\Core\Metadata\ClassMetadata;
use Cubiche\Core\Metadata\PropertyMetadata;
use Cubiche\Core\Metadata\Tests\Fixtures\Annotations as Cubiche;
use Cubiche\Domain\Model\Entity;
use Cubiche\Domain\System\Integer;
use Cubiche\Domain\System\StringLiteral;
use Cubiche\Domain\Web\EmailAddress;

/**
 * User Class.
 *
 * @author Ivannis Suárez Jerez <ivannis.suarez@gmail.com>
 * @Cubiche\AggregateRoot
 */
class User extends Entity
{
    /**
     * @var IdInterface
     * @Cubiche\Id
     */
    protected $id;

    /**
     * @var StringLiteral
     * @Cubiche\Field(type="StringLiteral", name="fullName")
     */
    protected $name;

    /**
     * @var StringLiteral
     * @Cubiche\Field(type="StringLiteral")
     */
    protected $username;

    /**
     * @var int
     * @Cubiche\Field(type="Integer")
     */
    protected $age;

    /**
     * @var EmailAddress
     * @Cubiche\Field(type="EmailAddress", name="email_address")
     */
    protected $email;

    /**
     * @var ArraySetInterface
     * @Cubiche\Field(type="ArraySet", of="Cubiche\Core\Metadata\Tests\Fixtures\Address")
     */
    protected $addresses;

    /**
     * @var ArraySetInterface
     * @Cubiche\Field(type="ArraySet", of="Cubiche\Core\Metadata\Tests\Fixtures\User")
     */
    protected $friends;

    /**
     * @param UserId $id
     * @param string $name
     * @param string $username
     * @param int    $age
     * @param string $email
     */
    public function __construct(UserId $id, $name, $username, $age, $email)
    {
        parent::__construct($id);

        $this->name = StringLiteral::fromNative($name);
        $this->username = StringLiteral::fromNative($username);
        $this->age = Integer::fromNative($age);
        $this->email = EmailAddress::fromNative($email);
        $this->addresses = new ArraySet();
        $this->friends = new ArraySet();
    }

    /**
     * @return StringLiteral
     */
    public function name()
    {
        return $this->name;
    }

    /**
     * @return StringLiteral
     */
    public function username()
    {
        return $this->username;
    }

    /**
     * @return int
     */
    public function age()
    {
        return $this->age;
    }

    /**
     * @return EmailAddress
     */
    public function email()
    {
        return $this->email;
    }

    /**
     * @return ArraySetInterface
     */
    public function addresses()
    {
        return $this->addresses;
    }

    /**
     * @param Address $address
     */
    public function addAddress(Address $address)
    {
        return $this->addresses->add($address);
    }

    /**
     * @return ArraySetInterface
     */
    public function friends()
    {
        return $this->friends;
    }

    /**
     * @param User $friend
     */
    public function addFriend(User $friend)
    {
        return $this->friends->add($friend);
    }

    /**
     * @param ClassMetadata $classMetadata
     */
    public static function loadMetadata(ClassMetadata $classMetadata)
    {
        // id
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'id'
        );

        $propertyMetadata->addMetadata('identifier', true);
        $propertyMetadata->addMetadata('name', '_id');
        $classMetadata->addPropertyMetadata($propertyMetadata);

        // name
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'name'
        );

        $propertyMetadata->addMetadata('identifier', false);
        $propertyMetadata->addMetadata('name', 'fullName');
        $propertyMetadata->addMetadata('type', 'StringLiteral');
        $classMetadata->addPropertyMetadata($propertyMetadata);

        // username
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'username'
        );

        $propertyMetadata->addMetadata('identifier', false);
        $propertyMetadata->addMetadata('type', 'StringLiteral');
        $classMetadata->addPropertyMetadata($propertyMetadata);

        // age
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'age'
        );

        $propertyMetadata->addMetadata('identifier', false);
        $propertyMetadata->addMetadata('type', 'Integer');
        $classMetadata->addPropertyMetadata($propertyMetadata);

        // email
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'email'
        );

        $propertyMetadata->addMetadata('identifier', false);
        $propertyMetadata->addMetadata('type', 'EmailAddress');
        $classMetadata->addPropertyMetadata($propertyMetadata);

        // addresses
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'addresses'
        );

        $propertyMetadata->addMetadata('identifier', false);
        $propertyMetadata->addMetadata('type', 'ArraySet');
        $propertyMetadata->addMetadata('of', 'Cubiche\Core\Metadata\Tests\Fixtures\Address');

        $classMetadata->addPropertyMetadata($propertyMetadata);

        // friends
        $propertyMetadata = new PropertyMetadata(
            $classMetadata->className(),
            'friends'
        );

        $propertyMetadata->addMetadata('identifier', false);
        $propertyMetadata->addMetadata('type', 'ArraySet');
        $propertyMetadata->addMetadata('of', 'Cubiche\Core\Metadata\Tests\Fixtures\User');

        $classMetadata->addPropertyMetadata($propertyMetadata);
    }
}


text:
DELETE addons_categories FROM addons_categories
    INNER JOIN categories
    ON addons_categories.category_id=categories.id
    WHERE categories.application_id NOT IN (1, 61);
DELETE FROM categories WHERE application_id NOT IN (1, 61);


text:
'use strict';

const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');

const ruleName = 'no-empty-source';

const messages = ruleMessages(ruleName, {
	rejected: 'Unexpected empty source',
});

function rule(actual, options, context) {
	return (root, result) => {
		const validOptions = validateOptions(result, ruleName, { actual });

		if (!validOptions) {
			return;
		}

		const rootString = context.fix ? root.toString() : root.source.input.css;

		if (rootString.trim()) {
			return;
		}

		report({
			message: messages.rejected,
			node: root,
			result,
			ruleName,
		});
	};
}

rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;


text:
package com.creativewidgetworks.goldparser.engine.enums;

/**
 * ParseResult
 *
 * Dependencies: None
 *
 * @author Devin Cook (http://www.DevinCook.com/GOLDParser)
 * @author Ralph Iden (http://www.creativewidgetworks.com), port to Java
 * @version 5.0.0
 */
public enum ParseResult {
    UNDEFINED         (-1),
    ACCEPT            (1),
    SHIFT             (2),
    REDUCE_NORMAL     (3),
    REDUCE_ELIMINATED (4),  // Trim
    SYNTAX_ERROR      (5),
    INTERNAL_ERROR    (6);

    private final int enumCode;

    ParseResult(int code) {
        this.enumCode = code;
    }

    public int getCode() {
        return enumCode;
    }

    public static ParseResult getParseResult(int code) {
        for (int i = 0; i < values().length; i++) {
            if (values()[i].enumCode == code) {
                return values()[i];
            }
        }
        return UNDEFINED;
    }
}


text:
FinnishYnabConverter
==========================

Converts csv transaction files to YNAB 4 compatible format. Most Finnish banks have ability to export your transactions to csv format from their web application.

* Verified to work with following bank formats
  * OP csv format
  * Handelsbanken csv format

Target framework: .NET Core 2.2

Building
==========================

```
git clone git@github.com:jkauppinen/FinnishYnabConverter.git
cd FinnishYnabConverter
dotnet build FinnishYnabConverter.sln
```

Creating executable on linux

```
dotnet publish -c Release -r ubuntu.16.04-x64
```
Using
==========================

To view available commands

```
FinnishYnabConverter --help
```


text:
using Newtonsoft.Json.Linq;
using ProtoBuf;
using Replicate;
using Replicate.MetaData;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace Spectrum.Framework.Network.Surrogates
{
    public class Primitive
    {
        public object Object;
        public Primitive() { }
        public Primitive(object obj)
        {
            if (obj is Enum)
                obj = (int)obj;
            Object = obj;
        }
    }
    [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
    [ReplicateType]
    public class PrimitiveSurrogate
    {
        public TypeId type;
        public byte[] buffer;

        private object Object
        {
            get
            {
                if (type.Id.IsEmpty) return null;
                MemoryStream stream = new MemoryStream(buffer);
                Type objType = TypeHelper.Model.GetType(type);
                if (objType == typeof(JToken))
                    return (JToken)(JSONSurrogate)Serializer.NonGeneric.Deserialize(typeof(JSONSurrogate), stream);
                return Serialization.BinarySerializer.Deserialize(objType, stream);
            }
        }
        public static implicit operator PrimitiveSurrogate(Primitive obj)
        {
            if (obj == null) return null;
            if (obj.Object != null)
            {
                TypeId type = TypeHelper.Model.GetId(obj.Object.GetType());
                MemoryStream buffer = new MemoryStream();
                Serialize(buffer, obj.Object);
                return new PrimitiveSurrogate() { type = type, buffer = buffer.ToArray() };
            }
            return new PrimitiveSurrogate();
        }
        public static implicit operator Primitive(PrimitiveSurrogate obj)
        {
            if (obj == null) return null;
            return new Primitive(obj.Object);
        }
        public static MemoryStream Serialize(MemoryStream stream, object obj)
        {
            if (obj is JToken)
                obj = (JSONSurrogate)(JToken)obj;
            Serialization.BinarySerializer.Serialize(obj.GetType(), obj, stream);
            return stream;
        }
    }
}


text:
"""Tests for cement.core.config."""

import os
from cement.core import exc, config, backend
from cement.utils import test

CONFIG = """
[my_section]
my_param = my_value
"""

class BogusConfigHandler(config.CementConfigHandler):

    class Meta:
        label = 'bogus'

class ConfigTestCase(test.CementCoreTestCase):

    @test.raises(exc.InterfaceError)
    def test_invalid_config_handler(self):
            self.app.handler.register(BogusConfigHandler)

    @test.raises(NotImplementedError)
    def test_parse_file_not_implemented(self):
        c = config.CementConfigHandler()
        c._setup(self.app)
        c._parse_file(self.tmp_file)

    def test_has_key(self):
        self.app.setup()
        self.ok(self.app.config.has_section(self.app._meta.config_section))

    def test_config_override(self):
        defaults = dict()
        defaults['test'] = dict()
        defaults['test']['debug'] = False
        defaults['test']['foo'] = 'bar'

        # first test that it doesn't override the config with the default
        # setting of arguments_override_config=False
        self.app = self.make_app(
            config_defaults=defaults,
            argv=['--foo=not_bar'],
            arguments_override_config=False
        )
        self.app.setup()
        self.app.args.add_argument('--foo', action='store')
        self.app.run()
        self.eq(self.app.config.get('test', 'foo'), 'bar')

        # then make sure that it does
        self.app = self.make_app(
            config_defaults=defaults,
            argv=['--foo=not_bar'],
            arguments_override_config=True,
            meta_override=['foo'],
        )
        self.app.setup()
        self.app.args.add_argument('--foo', action='store')
        self.app.run()
        self.eq(self.app.config.get('test', 'foo'), 'not_bar')

        # one last test just for code coverage
        self.app = self.make_app(
            config_defaults=defaults,
            argv=['--debug'],
            arguments_override_config=True
        )
        self.app.setup()
        self.app.args.add_argument('--foo', action='store')
        self.app.run()
        self.eq(self.app.config.get('test', 'foo'), 'bar')

    def test_parse_file_bad_path(self):
        self.app._meta.config_files = ['./some_bogus_path']
        self.app.setup()

    def test_parse_file(self):
        f = open(self.tmp_file, 'w+')
        f.write(CONFIG)
        f.close()
        self.app._meta.config_files = [self.tmp_file]
        self.app.setup()
        self.eq(self.app.config.get('my_section', 'my_param'), 'my_value')


text:
<?php
/**
 * This file has been @generated by a phing task by {@link GeneratePhonePrefixData}.
 * See [README.md](README.md#generating-data) for more information.
 *
 * Pull requests changing data in these files will not be accepted. See the
 * [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
 * metadata changes.
 *
 * Do not modify this file directly!
 */

return array (
  38260 => 'm:tel',
  38263 => 'Telenor',
  38266 => 'Telekom',
  38267 => 'Telekom',
  38268 => 'm:tel',
  38269 => 'Telenor',
);


text:
package org.jhaws.common.web.wicket.bootbox;

import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;

// submit
// form.add(new ConfirmationSubmitLink("submit", Model.of("confirmationmessage")).addConfirmation());
// werkt in forms en geneste forms
// werkt op "a href", "input type=submit", "button"
@SuppressWarnings("serial")
public class ConfirmationSubmitLink extends SubmitLink {
    private BootBoxHelper builder = new BootBoxHelper();

    public ConfirmationSubmitLink(String id, Form<?> form) {
        super(id, form);
        builder.setCancelButton(new ResourceModel("confirmation.box.cancel.button.label", (IModel<String>) null));
    }

    public ConfirmationSubmitLink(String id, IModel<?> model, Form<?> form) {
        super(id, model, form);
        builder.setCancelButton(new ResourceModel("confirmation.box.cancel.button.label", (IModel<String>) null));
    }

    public ConfirmationSubmitLink(String id, IModel<?> model) {
        super(id, model);
        builder.setCancelButton(new ResourceModel("confirmation.box.cancel.button.label", (IModel<String>) null));
    }

    public ConfirmationSubmitLink(String id) {
        super(id);
        builder.setCancelButton(new ResourceModel("confirmation.box.cancel.button.label", (IModel<String>) null));
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        // WICKET 6/7
        // BootboxJavascriptEventConfirmation handler = new
        // BootboxJavascriptEventConfirmation();
        // handler.setMessage(builder.getMessage());
        // handler.setTitle(builder.getTitle());
        // handler.setOkButton(builder.getOkButton());
        // handler.setOkButtonIcon(builder.getOkButtonIcon());
        // handler.setCancelButton(builder.getCancelButton());
        // handler.setCancelButtonIcon(builder.getCancelButtonIcon());
        // add(handler);
    }

    @Override
    protected CharSequence getTriggerJavaScript() {
        CharSequence triggerJavaScript = super.getTriggerJavaScript();
        // WICKET 9
        if (triggerJavaScript != null) {
            triggerJavaScript = "event.preventDefault();bootbox.confirm(" + builder.getScript().replace(BootBoxHelper.QFUNC, "function(result){console.log(result);if(result){" + triggerJavaScript + "}}") + ");";
        }
        return triggerJavaScript;
    }

    @Override
    public void renderHead(IHeaderResponse response) {
        super.renderHead(response);
        response.render(JavaScriptHeaderItem.forReference(BootBox.JS));
        response.render(JavaScriptHeaderItem.forReference(BootBox.JS_LOCALE));
    }

    public IModel<String> getOkButton() {
        return this.builder.getOkButton();
    }

    public ConfirmationSubmitLink setOkButton(IModel<String> okButton) {
        this.builder.setOkButton(okButton);
        return this;
    }

    public IModel<String> getCancelButton() {
        return this.builder.getCancelButton();
    }

    public ConfirmationSubmitLink setCancelButton(IModel<String> cancelButton) {
        this.builder.setCancelButton(cancelButton);
        return this;
    }

    public IModel<String> getOkButtonIcon() {
        return this.builder.getOkButtonIcon();
    }

    public ConfirmationSubmitLink setOkButtonIcon(IModel<String> okButtonIcon) {
        this.builder.setOkButtonIcon(okButtonIcon);
        return this;
    }

    public IModel<String> getCancelButtonIcon() {
        return this.builder.getCancelButtonIcon();
    }

    public ConfirmationSubmitLink setCancelButtonIcon(IModel<String> cancelButtonIcon) {
        this.builder.setCancelButtonIcon(cancelButtonIcon);
        return this;
    }

    public IModel<String> getTitle() {
        return this.builder.getTitle();
    }

    public ConfirmationSubmitLink setTitle(IModel<String> title) {
        this.builder.setTitle(title);
        return this;
    }

    public IModel<String> getMessage() {
        return this.builder.getMessage();
    }

    public ConfirmationSubmitLink setMessage(IModel<String> message) {
        this.builder.setMessage(message);
        return this;
    }
}


text:
<?php
new yii\web\Application(require(dirname(__DIR__) . '/config/acceptance.php'));


text:
#pragma once

#include "../interactionbase_api.h"

namespace Visualization {
	class Item;
}

namespace Interaction {

class INTERACTIONBASE_API AutoCompleteEntry
{
	public:
		typedef std::function<void (AutoCompleteEntry* entry)> ExecuteFunction;

		AutoCompleteEntry(const QString& text = QString(), const QString& description = QString());
		AutoCompleteEntry(const QString& text, const QString& description,
				Visualization::Item* visualization, ExecuteFunction execFunction = nullptr);
		AutoCompleteEntry(const QString& text, const QString& description,
				QSharedPointer<Visualization::Item> visualization,	ExecuteFunction execFunction = nullptr);
		virtual ~AutoCompleteEntry();

		virtual void execute();

		const QString& text();
		const QString& description();
		QSharedPointer<Visualization::Item> visualization();

		void setText(const QString& suggestion);
		void setDescription(const QString& description);
		void setVisualization(QSharedPointer<Visualization::Item> item);
		void setVisualization(Visualization::Item* item);
		void setExecutionFunction(ExecuteFunction execFunction);

	private:
		QString text_;
		QString description_;
		QSharedPointer<Visualization::Item> vis_;
		ExecuteFunction execFunction_;

};

inline const QString& AutoCompleteEntry::text() { return text_; }
inline const QString& AutoCompleteEntry::description() { return description_; }
inline QSharedPointer<Visualization::Item> AutoCompleteEntry::visualization() { return vis_; }
inline void AutoCompleteEntry::setText(const QString& text) { text_ = text; }
inline void AutoCompleteEntry::setDescription(const QString& description) { description_ = description; }

} /* namespace Interaction */


text:
		<title>Post Example</title>

		<form method="post" action="http://event.ris.dev.muze.nl:7001/post">
			id      <input name="id">

			password<input name="password">

			message <textarea name="message" ></textarea>

			<input type="submit">
		</form>