text:
$srcdir = Split-Path $myInvocation.InvocationName

# Set up environment and run a test executable or script.
. .\test_env.ps1

# The test exe is probably not in the current binary dir - it's usually
# placed in a subdirectory based on the configuration built in Visual Studio.
# So check around to see where it is - when located, set the QPID_LIB_DIR
# and PATH to look in the corresponding configuration off the src directory,
# one level up.
$prog = $args[0]
$is_script = $prog -match ".ps1$"
if (!$is_script -and !(Test-Path "$prog")) {
   . $srcdir\find_prog.ps1 $prog
   $args[0] = $prog
   $env:QPID_LIB_DIR = "..\$sub"
   $env:PATH += ";$dir\$sub;..\$sub"
}

# If qpidd.port exists and is not empty run test with QPID_PORT set.
if (Test-Path qpidd.port) {
   set-item -path env:QPID_PORT -value (get-content -path qpidd.port -totalcount 1)
}

$si = new-object System.Diagnostics.ProcessStartInfo
$si.WorkingDirectory = $pwd
$si.UseShellExecute = $false
$si.CreateNoWindow = $true
$si.RedirectStandardOutput = $true
if ($is_script) {
   $si.FileName = (get-command powershell.exe).Definition
   $si.Arguments = $args
}
else {
   $si.FileName = $args[0]
   if ($args.length -gt 1) {
      $si.Arguments = $args[1..($args.length-1)]
   }
}
$p = [System.Diagnostics.Process]::Start($si)
$line = ""
while (($line = $p.StandardOutput.ReadLine()) -ne $null) {
   $line
}
# ReadToEnd() works, but doesn't show any output until the program exits.
#$p.StandardOutput.ReadToEnd()
$p.WaitForExit()
$status = $p.ExitCode
exit $status


text:
namespace Common.Lab
{
    public class Bird : Animal
    {
        const string ColorDefault = "Blanc";
        public string Color { get; internal set; }
        public Bird(int weight, string color = ColorDefault)
            : base(weight)
        {
            this.Color = color;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
id: version-1.13.0-producing
title: Producing Messages
original_id: producing
---

To publish messages to Kafka you have to create a producer. Simply call the `producer` function of the client to create it:

```javascript
const producer = kafka.producer()
```

## Options

| option                 | description                                                                                | default              |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| createPartitioner      | Take a look at [Custom Partitioner](#custom-partitioner) for more information                                                                                | `null`               |
| retry                  | Take a look at [Producer Retry](#retry) for more information                                                                                | `null`               |
| metadataMaxAge         | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions | `300000` - 5 minutes |
| allowAutoTopicCreation | Allow topic creation when querying metadata for non-existent topics                                                                                | `true`               |
| transactionTimeout | The maximum amount of time in ms that the transaction coordinator will wait for a transaction status update from the producer before proactively aborting the ongoing transaction. If this value is larger than the `transaction.max.timeout.ms` setting in the __broker__, the request will fail with a `InvalidTransactionTimeout` error | `60000`                            |
| idempotent         | _Experimental._ If enabled producer will ensure each message is written exactly once. Acks _must_ be set to -1 ("all"). Retries will default to MAX_SAFE_INTEGER.                                                                                | `false`                            |
| maxInFlightRequests | Max number of requests that may be in progress at any time. If falsey then no limit.                                    | `null` _(no limit)_ |
The method `send` is used to publish messages to the Kafka cluster.

```javascript
const producer = kafka.producer()

await producer.connect()
await producer.send({
    topic: 'topic-name',
    messages: [
        { key: 'key1', value: 'hello world' },
        { key: 'key2', value: 'hey hey!' }
    ],
})
```

Example with a defined partition:

```javascript
const producer = kafka.producer()

await producer.connect()
await producer.send({
    topic: 'topic-name',
    messages: [
        { key: 'key1', value: 'hello world', partition: 0 },
        { key: 'key2', value: 'hey hey!', partition: 1 }
    ],
})
```

The method `send` has the following signature:

```javascript
await producer.send({
    topic: <String>,
    messages: <Message[]>,
    acks: <Number>,
    timeout: <Number>,
    compression: <CompressionTypes>,
})
```

| property           | description                                                                                | default                            |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- |
| topic              | topic name                                                                                | `null`                             |
| messages           | An array of objects with "key" (optional), "value" (required), "partition" (optional), "timestamp" (optional), "headers" (optional), example:
 `[{ key: 'my-key', value: 'my-value'}]`                                                                                | `null`                             |
| acks               | Control the number of required acks.
 __-1__ = all replicas must acknowledge _(default)_
 __0__ = no acknowledgments
 __1__ = only waits for the leader to acknowledge                                                                                | `-1` all replicas must acknowledge |
| timeout            | The time to await a response in ms                                                                                | `30000`                            |
| compression        | Compression codec                                                                                | `CompressionTypes.None`            |

By default, the producer is configured to distribute the messages with the following logic:

- If a partition is specified in the message, use it
- If no partition is specified but a key is present choose a partition based on a hash (murmur2) of the key
- If no partition or key is present choose a partition in a round-robin fashion

## Message Headers

Kafka v0.11 introduces record headers, which allows your messages to carry extra metadata. To send headers with your message, include the key `headers` with the values. Example:

```javascript
await producer.send({
    topic: 'topic-name',
    messages: [{
        key: 'key1',
        value: 'hello world',
        headers: {
            'correlation-id': '2bfb68bb-893a-423b-a7fa-7b568cad5b67',
            'system-id': 'my-system'
        }
    }]
})
```

## Producing to multiple topics

To produce to multiple topics at the same time, use `sendBatch`. This can be useful, for example, when migrating between two topics.

```javascript
const topicMessages = [
  {
    topic: 'topic-a',
    messages: [{ key: 'key', value: 'hello topic-a' }],
  },
  {
    topic: 'topic-b',
    messages: [{ key: 'key', value: 'hello topic-b' }],
  },
  {
    topic: 'topic-c',
    messages: [
      {
        key: 'key',
        value: 'hello topic-c',
        headers: {
          'correlation-id': '2bfb68bb-893a-423b-a7fa-7b568cad5b67',
        },
      }
    ],
  }
]
await producer.sendBatch({ topicMessages })
```

`sendBatch` has the same signature as `send`, except `topic` and `messages` are replaced with `topicMessages`:

```javascript
await producer.sendBatch({
    topicMessages: <TopicMessages[]>,
    acks: <Number>,
    timeout: <Number>,
    compression: <CompressionTypes>,
})
```

| property      | description                                                                                |
| ------------- | ---------------------------------------------------------------------------------------------------------- |
| topicMessages | An array of objects with `topic` and `messages`.
`messages` is an array of the same type as for `send`. |

##  Custom partitioner

It's possible to assign a custom partitioner to the producer. A partitioner is a function which returns another function responsible for the partition selection, something like this:

```javascript
const MyPartitioner = () => {
    return ({ topic, partitionMetadata, message }) => {
        // select a partition based on some logic
        // return the partition number
        return 0
    }
}
```

`partitionMetadata` is an array of partitions with the following structure:

`{ partitionId: <NodeId>, leader: <NodeId> }`

Example:

```javascript
[
    { partitionId: 1, leader: 1 },
    { partitionId: 2, leader: 2 },
    { partitionId: 0, leader: 0 }
]
```

To use your custom partitioner, use the option `createPartitioner` when creating the producer.

```javascript
kafka.producer({ createPartitioner: MyPartitioner })
```

### Default Partitioners

KafkaJS ships with 2 partitioners: `DefaultPartitioner` and `JavaCompatiblePartitioner`.

The `JavaCompatiblePartitioner` should be compatible with the default partitioner that ships with the Java Kafka client. This can be important to meet the [co-partitioning requirement](https://docs.confluent.io/current/ksql/docs/developer-guide/partition-data.html#co-partitioning-requirements) when joining multiple topics.

Use the `JavaCompatiblePartitioner` by importing it and providing it to the Producer constructor:

```javascript
const { Partitioners } = require('kafkajs')
kafka.producer({ createPartitioner: Partitioners.JavaCompatiblePartitioner })
```

##  Retry

The option `retry` can be used to customize the configuration for the producer.

Take a look at [Retry](Configuration.md#retry) for more information.

##  Compression

Since KafkaJS aims to have as small footprint and as few dependencies as possible, only the GZIP codec is part of the core functionality. Providing plugins supporting other codecs might be considered in the future.

###  GZIP

```javascript
const { CompressionTypes } = require('kafkajs')

async () => {
  await producer.send({
    topic: 'topic-name',
    compression: CompressionTypes.GZIP,
    messages: [
        { key: 'key1', value: 'hello world' },
        { key: 'key2', value: 'hey hey!' }
    ],
  })
}
```

The consumers know how to decompress GZIP, so no further work is necessary.

###  Snappy

Snappy support is provided by the package `kafkajs-snappy`

```sh
npm install kafkajs-snappy
# yarn add kafkajs-snappy
```

```javascript
const {  CompressionTypes, CompressionCodecs } = require('kafkajs')
const SnappyCodec = require('kafkajs-snappy')

CompressionCodecs[CompressionTypes.Snappy] = SnappyCodec
```

Take a look at the official [readme](https://github.com/tulios/kafkajs-snappy) for more information

###  LZ4

LZ4 support is provided by the package `kafkajs-lz4`

```sh
npm install kafkajs-lz4
# yarn add kafkajs-lz4
```

```javascript
const { CompressionTypes, CompressionCodecs } = require('kafkajs')
const LZ4 = require('kafkajs-lz4')

CompressionCodecs[CompressionTypes.LZ4] = new LZ4().codec
```

The package also accepts options to granularly control LZ4 compression & decompression. Take a look at the official [readme](https://github.com/indix/kafkajs-lz4) for more information.

###  Other

Any other codec than GZIP can be easily implemented using existing libraries.

A codec is an object with two `async` functions: `compress` and `decompress`. Import the libraries and define the codec object:

```javascript
const MyCustomSnappyCodec = {
    async compress(encoder) {
        return someCompressFunction(encoder.buffer)
    },

    async decompress(buffer) {
        return someDecompressFunction(buffer)
    }
}
```

Now that we have the codec object, we can add it to the implementation:

```javascript
const { CompressionTypes, CompressionCodecs } = require('kafkajs')
CompressionCodecs[CompressionTypes.Snappy] = MyCustomSnappyCodec
```

The new codec can now be used with the `send` method, example:

```javascript
await producer.send({
    topic: 'topic-name',
    compression: CompressionTypes.Snappy,
    messages: [
        { key: 'key1', value: 'hello world' },
        { key: 'key2', value: 'hey hey!' }
    ],
})
```


text:
describe('Handlers:', function () {
    var AuthService, $httpBackend;

    beforeEach(module('angular-spa-auth'));
    beforeEach(inject(function(_AuthService_, _$httpBackend_){
        AuthService = _AuthService_;
        $httpBackend = _$httpBackend_;

        //setup
        AuthService.config.verbose = true;
        AuthService.config.endpoints.isAuthenticated = ENDPOINTS.IS_AUTHENTICATED_SUCCESS;
        AuthService.config.endpoints.login = ENDPOINTS.LOGIN_SUCCESS;

        //setup backend
        $httpBackend.whenGET(ENDPOINTS.IS_AUTHENTICATED_SUCCESS).respond(200, false);
        $httpBackend.whenPOST(ENDPOINTS.LOGIN_SUCCESS).respond(500);
    }));

    describe('error():', function () {

        it('Call default handler using .login() method', function () {
            //given:
            spy();

            //when: call login method
            AuthService.login();
            $httpBackend.flush();

            //then:
            checkIfCalled(1, false);
        });

        it('Call custom handler using .run() method', function () {
            //given: set error handler
            var testValue = false;
            setupAndSpy(function (err) {
                testValue = err;
            });
            // -> calls .run method which uses error handler inside
            $httpBackend.flush();

            //then:
            checkIfCalled(1, false);
            expect(testValue).toEqual(false);
        });

        it('Call custom handler using .login() method', function () {
            //given: set custom error handler
            var errorResponse = false;
            setupAndSpy(function (err) {
                errorResponse = err;
            });
            // -> calls .run method which uses error handler inside
            $httpBackend.flush();

            //then:
            expect(AuthService.config.handlers.error.calls.count()).toEqual(1);

            //when: call login method
            AuthService.login();
            $httpBackend.flush();

            //then:
            checkIfCalled(2);
            expect(errorResponse.status).toEqual(500);
        });

        function setupAndSpy(logoutHandler) {
            AuthService.run({
                handlers: {
                    error: logoutHandler
                }
            });

            spy();
        }

        function spy() {
            spyOn(AuthService.config.handlers, 'error').and.callThrough();
        }

        function checkIfCalled(count, data) {
            if(data) {
                expect(AuthService.config.handlers.error).toHaveBeenCalledWith(data);
            } else {
                expect(AuthService.config.handlers.error).toHaveBeenCalled();
            }
            expect(AuthService.config.handlers.error.calls.count()).toEqual(count);
        }

    });
});


text:
#ifndef CHISQL_H_
#define CHISQL_H_

#include <stdint.h>
#include "create.h"
#include "insert.h"
#include "sra.h"
#include "delete.h"

#define SQL_NOTVALID (-1)
#define SQL_NULL (0)
#define SQL_INTEGER_1BYTE (1)
#define SQL_INTEGER_2BYTE (2)
#define SQL_INTEGER_4BYTE (4)
#define SQL_TEXT (13)

#define STMT_CREATE (0)
#define STMT_SELECT (1)
#define STMT_INSERT (2)
#define STMT_DELETE (3)

typedef struct chisql_statement
{
    bool explain;
    char *text;
    uint8_t type;
    union {
        Create_t *create;
        SRA_t    *select;
        Insert_t *insert;
        Delete_t *delete;
    } stmt;
} chisql_statement_t;

int chisql_parser(const char *sql, chisql_statement_t **stmt);
int chisql_stmt_print(chisql_statement_t *stmt);

#endif /* SQL_TYPES_H_ */


text:
sap.ui.define(["sap/ui/integration/Designtime"
], function (Designtime) {
	"use strict";
	return function () {
		return new Designtime({
			"form": {
				"items": {
					"group": {
						"label": "Group1",
						"type": "group",
						"hint": "Please refer to the documentation lets see how this will behave if the text is wrapping to the next line and has two links. good?"
					},
					"stringParameter": {
						"manifestpath": "/temp/configuration/parameters/stringParameter/value",
						"type": "string",
						"label": "StaticLabel",
						"hint": "Please refer to the documentation lets see how this will behave if the text is wrapping to the next line and has two links. good?"
					}
				}
			}
		});
	};
});


text:
<?php

namespace Ivory\Tests\HttpAdapter\Event\Subscriber;

use Ivory\HttpAdapter\Event\Events;
use Ivory\HttpAdapter\Event\Subscriber\LoggerSubscriber;
use Ivory\HttpAdapter\Event\Timer\TimerInterface;
use Ivory\HttpAdapter\Message\InternalRequestInterface;

/**
 * Logger subscriber test.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class LoggerSubscriberTest extends AbstractSubscriberTest
{
    /** @var \Ivory\HttpAdapter\Event\Subscriber\LoggerSubscriber */
    private $loggerSubscriber;

    /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $logger;

    /** @var \Ivory\HttpAdapter\Event\Formatter\FormatterInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $formatter;

    /** @var \Ivory\HttpAdapter\Event\Timer\TimerInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $timer;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->loggerSubscriber = new LoggerSubscriber(
            $this->logger = $this->createLoggerMock(),
            $this->formatter = $this->createFormatterMock(),
            $this->timer = $this->createTimerMock()
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        unset($this->timer);
        unset($this->formatter);
        unset($this->logger);
        unset($this->loggerSubscriber);
    }

    public function testDefaultState()
    {
        $this->loggerSubscriber = new LoggerSubscriber($this->logger);

        $this->assertInstanceOf(
            'Ivory\HttpAdapter\Event\Subscriber\AbstractFormatterSubscriber',
            $this->loggerSubscriber
        );

        $this->assertSame($this->logger, $this->loggerSubscriber->getLogger());

        $this->assertInstanceOf(
            'Ivory\HttpAdapter\Event\Formatter\Formatter',
            $this->loggerSubscriber->getFormatter()
        );

        $this->assertInstanceOf('Ivory\HttpAdapter\Event\Timer\Timer', $this->loggerSubscriber->getTimer());
    }

    public function testInitialState()
    {
        $this->assertSame($this->logger, $this->loggerSubscriber->getLogger());
        $this->assertSame($this->formatter, $this->loggerSubscriber->getFormatter());
        $this->assertSame($this->timer, $this->loggerSubscriber->getTimer());
    }

    public function testSubscribedEvents()
    {
        $events = LoggerSubscriber::getSubscribedEvents();

        $this->assertArrayHasKey(Events::REQUEST_CREATED, $events);
        $this->assertSame(array('onRequestCreated', 100), $events[Events::REQUEST_CREATED]);

        $this->assertArrayHasKey(Events::REQUEST_SENT, $events);
        $this->assertSame(array('onRequestSent', 100), $events[Events::REQUEST_SENT]);

        $this->assertArrayHasKey(Events::REQUEST_ERRORED, $events);
        $this->assertSame(array('onRequestErrored', 100), $events[Events::REQUEST_ERRORED]);

        $this->assertArrayHasKey(Events::MULTI_REQUEST_CREATED, $events);
        $this->assertSame(array('onMultiRequestCreated', 100), $events[Events::MULTI_REQUEST_CREATED]);

        $this->assertArrayHasKey(Events::MULTI_REQUEST_SENT, $events);
        $this->assertSame(array('onMultiRequestSent', 100), $events[Events::MULTI_REQUEST_SENT]);

        $this->assertArrayHasKey(Events::MULTI_REQUEST_ERRORED, $events);
        $this->assertSame(array('onMultiResponseErrored', 100), $events[Events::MULTI_REQUEST_ERRORED]);
    }

    public function testRequestSentEvent()
    {
        $this->timer
            ->expects($this->once())
            ->method('start')
            ->with($this->identicalTo($request = $this->createRequestMock()))
            ->will($this->returnValue($startedRequest = $this->createRequestMock()));

        $this->timer
            ->expects($this->once())
            ->method('stop')
            ->with($this->identicalTo($startedRequest))
            ->will($this->returnValue($stoppedRequest = $this->createRequestMock()));

        $this->formatter
            ->expects($this->once())
            ->method('formatRequest')
            ->with($this->identicalTo($stoppedRequest))
            ->will($this->returnValue($formattedRequest = 'request'));

        $this->formatter
            ->expects($this->once())
            ->method('formatResponse')
            ->with($this->identicalTo($response = $this->createResponseMock()))
            ->will($this->returnValue($formattedResponse = 'response'));

        $this->logger
            ->expects($this->once())
            ->method('debug')
            ->with(
                $this->matchesRegularExpression('/^Send "GET http:\/\/egeloen\.fr" in [0-9]+\.[0-9]{2} ms\.$/'),
                $this->identicalTo(array(
                    'adapter'  => 'http_adapter',
                    'request'  => $formattedRequest,
                    'response' => $formattedResponse,
                ))
            );

        $this->loggerSubscriber->onRequestCreated($requestCreatedEvent = $this->createRequestCreatedEvent(null, $request));
        $this->loggerSubscriber->onRequestSent($requestSentEvent = $this->createRequestSentEvent(null, $startedRequest, $response));

        $this->assertSame($startedRequest, $requestCreatedEvent->getRequest());
        $this->assertSame($stoppedRequest, $requestSentEvent->getRequest());
    }

    public function testRequestErroredEvent()
    {
        $this->timer
            ->expects($this->once())
            ->method('start')
            ->with($this->identicalTo($request = $this->createRequestMock()))
            ->will($this->returnValue($startedRequest = $this->createRequestMock()));

        $this->timer
            ->expects($this->once())
            ->method('stop')
            ->with($this->identicalTo($startedRequest))
            ->will($this->returnValue($stoppedRequest = $this->createRequestMock()));

        $this->formatter
            ->expects($this->once())
            ->method('formatRequest')
            ->with($this->identicalTo($stoppedRequest))
            ->will($this->returnValue($formattedRequest = 'request'));

        $this->formatter
            ->expects($this->once())
            ->method('formatResponse')
            ->with($this->identicalTo($response = $this->createResponseMock()))
            ->will($this->returnValue($formattedResponse = 'response'));

        $this->formatter
            ->expects($this->once())
            ->method('formatException')
            ->with($this->identicalTo($exception = $this->createExceptionMock($startedRequest, $response)))
            ->will($this->returnValue($formattedException = 'exception'));

        $exception
            ->expects($this->once())
            ->method('setRequest')
            ->with($this->identicalTo($stoppedRequest));

        $this->logger
            ->expects($this->once())
            ->method('error')
            ->with(
                $this->identicalTo('Unable to send "GET http://egeloen.fr".'),
                $this->identicalTo(array(
                    'adapter'   => 'http_adapter',
                    'exception' => $formattedException,
                    'request'   => $formattedRequest,
                    'response'  => $formattedResponse,
                ))
            );

        $this->loggerSubscriber->onRequestCreated($event = $this->createRequestCreatedEvent(null, $request));
        $this->loggerSubscriber->onRequestErrored($this->createRequestErroredEvent(null, $exception));

        $this->assertSame($startedRequest, $event->getRequest());
    }

    public function testMultiRequestSentEvent()
    {
        $requests = array($request1 = $this->createRequestMock(), $request2 = $this->createRequestMock());

        $this->timer
            ->expects($this->exactly(count($requests)))
            ->method('start')
            ->will($this->returnValueMap(array(
                array($request1, $startedRequest1 = $this->createRequestMock()),
                array($request2, $startedRequest2 = $this->createRequestMock()),
            )));

        $responses = array(
            $response1 = $this->createResponseMock($startedRequest1),
            $response2 = $this->createResponseMock($startedRequest2),
        );

        $this->timer
            ->expects($this->exactly(count($responses)))
            ->method('stop')
            ->will($this->returnValueMap(array(
                array($startedRequest1, $stoppedRequest1 = $this->createRequestMock()),
                array($startedRequest2, $stoppedRequest2 = $this->createRequestMock()),
            )));

        $this->formatter
            ->expects($this->exactly(count($responses)))
            ->method('formatRequest')
            ->will($this->returnValueMap(array(
                array($stoppedRequest1, $formattedRequest1 = 'request1'),
                array($stoppedRequest2, $formattedRequest2 = 'request2'),
            )));

        $this->formatter
            ->expects($this->exactly(count($responses)))
            ->method('formatResponse')
            ->will($this->returnValueMap(array(
                array($response1, $formattedResponse1 = 'response1'),
                array($response2, $formattedResponse2 = 'response2'),
            )));

        $this->logger
            ->expects($this->exactly(count($responses)))
            ->method('debug')
            ->withConsecutive(
                array(
                    $this->matchesRegularExpression('/^Send "GET http:\/\/egeloen\.fr" in [0-9]+\.[0-9]{2} ms\.$/'),
                    array(
                        'adapter'  => 'http_adapter',
                        'request'  => $formattedRequest1,
                        'response' => $formattedResponse1,
                    ),
                ),
                array(
                    $this->matchesRegularExpression('/^Send "GET http:\/\/egeloen\.fr" in [0-9]+\.[0-9]{2} ms\.$/'),
                    array(
                        'adapter'  => 'http_adapter',
                        'request'  => $formattedRequest2,
                        'response' => $formattedResponse2,
                    ),
                )
            );

        $response1
            ->expects($this->once())
            ->method('withParameter')
            ->with($this->identicalTo('request'), $this->identicalTo($stoppedRequest1))
            ->will($this->returnValue($stoppedResponse1 = $this->createResponseMock($stoppedRequest1)));

        $response2
            ->expects($this->once())
            ->method('withParameter')
            ->with($this->identicalTo('request'), $this->identicalTo($stoppedRequest2))
            ->will($this->returnValue($stoppedResponse2 = $this->createResponseMock($stoppedRequest2)));

        $this->loggerSubscriber->onMultiRequestCreated($requestCreatedEvent = $this->createMultiRequestCreatedEvent(null, $requests));
        $this->loggerSubscriber->onMultiRequestSent($requestSentEvent = $this->createMultiRequestSentEvent(null, $responses));

        $this->assertSame(array($startedRequest1, $startedRequest2), $requestCreatedEvent->getRequests());
        $this->assertSame(array($stoppedResponse1, $stoppedResponse2), $requestSentEvent->getResponses());
    }

    public function testMultiRequestErroredEvent()
    {
        $requests = array(
            $request1 = $this->createRequestMock(),
            $request2 = $this->createRequestMock(),
        );

        $this->timer
            ->expects($this->exactly(count($requests)))
            ->method('start')
            ->will($this->returnValueMap(array(
                array($request1, $startedRequest1 = $this->createRequestMock()),
                array($request2, $startedRequest2 = $this->createRequestMock()),
            )));

        $exceptions = array(
            $exception1 = $this->createExceptionMock(
                $startedRequest1,
                $response1 = $this->createResponseMock($request1)
            ),
            $exception2 = $this->createExceptionMock(
                $startedRequest2,
                $response2 = $this->createResponseMock($request2)
            ),
        );

        $this->timer
            ->expects($this->exactly(count($exceptions)))
            ->method('stop')
            ->will($this->returnValueMap(array(
                array($startedRequest1, $stoppedRequest1 = $this->createRequestMock()),
                array($startedRequest2, $stoppedRequest2 = $this->createRequestMock()),
            )));

        $this->formatter
            ->expects($this->exactly(count($exceptions)))
            ->method('formatRequest')
            ->will($this->returnValueMap(array(
                array($stoppedRequest1, $formattedRequest1 = 'request1'),
                array($stoppedRequest2, $formattedRequest2 = 'request2'),
            )));

        $this->formatter
            ->expects($this->exactly(count($exceptions)))
            ->method('formatResponse')
            ->will($this->returnValueMap(array(
                array($response1, $formattedResponse1 = 'response1'),
                array($response2, $formattedResponse2 = 'response2'),
            )));

        $this->formatter
            ->expects($this->exactly(count($exceptions)))
            ->method('formatException')
            ->will($this->returnValueMap(array(
                array($exception1, $formattedException1 = 'exception1'),
                array($exception2, $formattedException2 = 'exception1'),
            )));

        $this->logger
            ->expects($this->exactly(count($exceptions)))
            ->method('error')
            ->withConsecutive(
                array(
                    $this->identicalTo('Unable to send "GET http://egeloen.fr".'),
                    $this->identicalTo(array(
                        'adapter'   => 'http_adapter',
                        'exception' => $formattedException1,
                        'request'   => $formattedRequest1,
                        'response'  => $formattedResponse1,
                    )),
                ),
                array(
                    $this->identicalTo('Unable to send "GET http://egeloen.fr".'),
                    $this->identicalTo(array(
                        'adapter'   => 'http_adapter',
                        'exception' => $formattedException2,
                        'request'   => $formattedRequest2,
                        'response'  => $formattedResponse2,
                    )),
                )
            );

        $exception1
            ->expects($this->once())
            ->method('setRequest')
            ->with($this->identicalTo($stoppedRequest1));

        $exception2
            ->expects($this->once())
            ->method('setRequest')
            ->with($this->identicalTo($stoppedRequest2));

        $this->loggerSubscriber->onMultiRequestCreated($event = $this->createMultiRequestCreatedEvent(null, $requests));
        $this->loggerSubscriber->onMultiResponseErrored($this->createMultiRequestErroredEvent(null, $exceptions));

        $this->assertSame(array($startedRequest1, $startedRequest2), $event->getRequests());
    }

    /**
     * {@inheritdoc}
     */
    protected function createRequestMock()
    {
        $request = parent::createRequestMock();

        $request
            ->expects($this->any())
            ->method('getUri')
            ->will($this->returnValue('http://egeloen.fr'));

        $request
            ->expects($this->any())
            ->method('getMethod')
            ->will($this->returnValue('GET'));

        $request
            ->expects($this->any())
            ->method('getParameter')
            ->with($this->identicalTo(TimerInterface::TIME))
            ->will($this->returnValue(123));

        return $request;
    }

    /**
     * {@inheritdoc}
     */
    protected function createResponseMock(InternalRequestInterface $internalRequest = null)
    {
        $response = parent::createResponseMock();
        $response
            ->expects($this->any())
            ->method('getParameter')
            ->with($this->identicalTo('request'))
            ->will($this->returnValue($internalRequest));

        return $response;
    }

    /**
     * Creates a logger mock.
     *
     * @return \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject The logger mock.
     */
    private function createLoggerMock()
    {
        return $this->getMock('Psr\Log\LoggerInterface');
    }

    /**
     * Creates a formatter mock.
     *
     * @return \Ivory\HttpAdapter\Event\Formatter\FormatterInterface|\PHPUnit_Framework_MockObject_MockObject The formatter mock.
     */
    private function createFormatterMock()
    {
        return $this->getMock('Ivory\HttpAdapter\Event\Formatter\FormatterInterface');
    }

    /**
     * Creates a timer mock.
     *
     * @return \Ivory\HttpAdapter\Event\Timer\TimerInterface|\PHPUnit_Framework_MockObject_MockObject The timer mock.
     */
    private function createTimerMock()
    {
        return $this->getMock('Ivory\HttpAdapter\Event\Timer\TimerInterface');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using OKHOSTING.UI.Controls;

namespace OKHOSTING.UI.Console.Controls
{
    public class MenuItem : Terminal.Gui.MenuBarItem, IMenuItem
    {
        public MenuItem()
        {
            Children = new List<IMenuItem>();
        }

        public MenuItem(string text) : this()
        {
            Text = text;
        }

        public MenuItem(string text, EventHandler onClick) : this(text)
        {

        }

        public string Text
        {
            get
            {
                return base.Title.ToString();
            }
            set
            {
                base.Title = value;
            }
        }
        public object Tag
        {
            get;
            set;
        }

        public new ICollection<IMenuItem> Children
        {
            get;
            protected set;
        }

        public event EventHandler Click;

        public override string ToString()
        {
            return Text ?? base.ToString();
        }
    }
}


text:
package quickfix.field;
import quickfix.IntField;

public class ContAmtType extends IntField
{
  static final long serialVersionUID = 20050617;

  public static final int FIELD = 519;
  public static final int COMMISSION_AMOUNT = 1;
  public static final int COMMISSION_PERCENT = 2;
  public static final int INITIAL_CHARGE_AMOUNT = 3;
  public static final int INITIAL_CHARGE_PERCENT = 4;
  public static final int DISCOUNT_AMOUNT = 5;
  public static final int DISCOUNT_PERCENT = 6;
  public static final int DILUTION_LEVY_AMOUNT = 7;
  public static final int DILUTION_LEVY_PERCENT = 8;
  public static final int EXIT_CHARGE_AMOUNT = 9;
  public static final int EXIT_CHARGE_PERCENT = 10;
  public static final int FUND_BASED_RENEWAL_COMMISSION_PERCENT = 11;
  public static final int PROJECTED_FUND_VALUE = 12;
  public static final int FUND_BASED_RENEWAL_COMMISSION_AMOUNT = 13;
  public static final int FUND_BASED_RENEWAL_COMMISSION_AMOUNT2 = 14;
  public static final int NET_SETTLEMENT_AMOUNT = 15;

  public ContAmtType()
  {
    super(519);
  }

  public ContAmtType(int data)
  {
     super(519, data);
  }

}


text:
        {{ label || 'Nome impresso no cartão' }}

    <input
        class="aph form__control text-uppercase"
        type="text"
        name="name"
        id="{{ id || 'cc_name' }}"
        data-ng-model="card.name"
        data-ng-change="card.name = (card.name | uppercase)"
        data-creditcard-holder-validator
        data-prevent-paste
        required
    />

        {{ errorMessage || 'Preencha conforme impresso no cartão' }}


text:
using LinqToDB.Mapping;
using System;

#pragma warning disable 1573, 1591
#nullable enable

namespace Cli.Default.SqlServerNorthwind
{
	[Table("Invoices", IsView = true)]
	public class Invoice
	{
		[Column("ShipName"                         )] public string?   ShipName       { get; set; } // nvarchar(40)
		[Column("ShipAddress"                      )] public string?   ShipAddress    { get; set; } // nvarchar(60)
		[Column("ShipCity"                         )] public string?   ShipCity       { get; set; } // nvarchar(15)
		[Column("ShipRegion"                       )] public string?   ShipRegion     { get; set; } // nvarchar(15)
		[Column("ShipPostalCode"                   )] public string?   ShipPostalCode { get; set; } // nvarchar(10)
		[Column("ShipCountry"                      )] public string?   ShipCountry    { get; set; } // nvarchar(15)
		[Column("CustomerID"                       )] public string?   CustomerId     { get; set; } // nchar(5)
		[Column("CustomerName"  , CanBeNull = false)] public string    CustomerName   { get; set; } = null!; // nvarchar(40)
		[Column("Address"                          )] public string?   Address        { get; set; } // nvarchar(60)
		[Column("City"                             )] public string?   City           { get; set; } // nvarchar(15)
		[Column("Region"                           )] public string?   Region         { get; set; } // nvarchar(15)
		[Column("PostalCode"                       )] public string?   PostalCode     { get; set; } // nvarchar(10)
		[Column("Country"                          )] public string?   Country        { get; set; } // nvarchar(15)
		[Column("Salesperson"   , CanBeNull = false)] public string    Salesperson    { get; set; } = null!; // nvarchar(31)
		[Column("OrderID"                          )] public int       OrderId        { get; set; } // int
		[Column("OrderDate"                        )] public DateTime? OrderDate      { get; set; } // datetime
		[Column("RequiredDate"                     )] public DateTime? RequiredDate   { get; set; } // datetime
		[Column("ShippedDate"                      )] public DateTime? ShippedDate    { get; set; } // datetime
		[Column("ShipperName"   , CanBeNull = false)] public string    ShipperName    { get; set; } = null!; // nvarchar(40)
		[Column("ProductID"                        )] public int       ProductId      { get; set; } // int
		[Column("ProductName"   , CanBeNull = false)] public string    ProductName    { get; set; } = null!; // nvarchar(40)
		[Column("UnitPrice"                        )] public decimal   UnitPrice      { get; set; } // money
		[Column("Quantity"                         )] public short     Quantity       { get; set; } // smallint
		[Column("Discount"                         )] public float     Discount       { get; set; } // real
		[Column("ExtendedPrice"                    )] public decimal?  ExtendedPrice  { get; set; } // money
		[Column("Freight"                          )] public decimal?  Freight        { get; set; } // money
	}
}


text:
var winHome;

exports.createApplicationWindow = function(){
	var win = Titanium.UI.createWindow({
		title:'YBOB Boozerlyzer',
		backgroundImage:'/images/smallcornercup.png',
		modal:true
	});
	win.orientationModes =  [Titanium.UI.LANDSCAPE_LEFT, Titanium.UI.LANDSCAPE_RIGHT];

	Ti.API.debug('gameMemory 1');
	var scoresDialog = require('/ui/scoresDialog');
	scoresDialog.setParent(win);
	var dbGameScores = require('/db/gameScores');
	//include the menu choices
	// var menu = menus;
	var menu = require('/ui/menu');
	//need to give it specific help for this screen
	var memoryGameHelp = "Press the buttons to advance the images. If two IMAGES are the same press the lower LEFT button. If the LOCATION is the same press the lower RIGHT button. Otherwise press either NO MATCH button. Points are awarded for speed & coordination.";
	menu.setHelpMessage(memoryGameHelp);
	win.activity.onCreateOptionsMenu = function(event){
		menu.createMenus(event);
	};

	//overload the open function to display help dialog
	win.addEventListener('open', function(){
		var initialHelp = require('/ui/initialHelpDialog');
		initialHelp.showNotice('memoryGame',memoryGameHelp);
	});

	var stimulus, grid;
	var labelScore, score, labelBonus, bonus, countLabel,nBackLabel,missCountLabel, labelGameMessage;
	var currentObj = 0, points = 0, coordbonus = 0, speedbonus = 0,  inhibitbonus = 0;
	var startTime = 0, stepStartTime = 0, count = 0, missCount = 0, falseAlarmCount = 0;
	var count_GO, miss_GO, count_NOGO, miss_NOGO;
	var speed_GO, speed_NOGO, coord_GO, coord_NOGO, inhibit;
	var gameStarted = false, gameAllowRestart = true, clicked = false,dialogOpen  = false;
	var iconSize = 90;
	var imgtop = [2,2,2,96,96,96,190,190,190];
	var imgleft = [2,96,190,2,96,190,2,96,190];
	var leftButton = 5, rightButton= 376;
	var topButton = 30, bottomButton = 150;

	var fruitprefix = '/images/fruit/';
	var fruits = ['apple.png','banana.png','cherry.png','grapefruit.png','kiwi.png','lemon.png','lime.png','strawberry.png','watermelon.png','starfruit.png'];

	//	track what object is shown and its location for each step
	var stepImage = [],stepLocation = [];
	var nBack = 1;

	// funtion to handle the button presses
	var whatClicked = function (e) {
		if (clicked ){
			//don't do anything
			return;
		}
		clicked = true;
		//var cen = e.source.center;
		for (item in e.source){
			Ti.API.debug('e.' + item + ' ' + e.source[''+item]);

		}

		var cen = {x:0,y:0};
		cen.x = e.source.left + 0.5 * e.source.width;
		cen.y = e.source.top + 0.5 * e.source.height;
		var idx = parseInt(e.source.idx, 10);
		var globalCoords = {x:0,y:0};

		Ti.API.debug("whatClicked x,y " + e.x + ", " + e.y  );
		Ti.API.debug('source cen' + JSON.stringify(cen));
		Ti.API.debug('Button clicked idx:' + idx);
		Ti.API.debug('stepLocation   :' + stepLocation[count]);
		Ti.API.debug('stepLocation -n:' + stepLocation[count-nBack]);
		Ti.API.debug('stepImage   :' + stepImage[count]);
		Ti.API.debug('stepImage -n:' + stepImage[count-nBack]);
		if(count < nBack){
			//nothing to do
		}else if (idx === -1){
			//work out correct location of the click globally
			globalCoords.x = e.x + leftButton;
			globalCoords.y = e.y + bottomButton;

			//clicked left button, cheick if image matches N back item
			//clicked teh right button see if location matches nBack location.
			if (stepImage[count] === stepImage[count - nBack]){
				Ti.API.debug('image match');
				//CORRECT!
				points += 10;
				speedbonus += calcSpeedBonus(stepStartTime, new Date().getTime());
				coordbonus += calcCoordinationBonus("GO",cen,globalCoords);
			}else{
				//WRONG!
				inhibitbonus -= 5;
				missCount++;
			}
		}else if (idx === 1){
			globalCoords.x = e.x + rightButton;
			globalCoords.y = e.y + bottomButton;
			//clicked teh right button see if location matches nBack location.
			if (stepLocation[count] === stepLocation[count - nBack]){
				Ti.API.debug('location match');
				//CORRECT!
				points += 10;
				speedbonus += calcSpeedBonus(stepStartTime, new Date().getTime());
				coordbonus += calcCoordinationBonus("GO",cen,globalCoords);
			}else{
				//WRONG!
				inhibitbonus -= 5;
				missCount++;
			}
		}else if (idx === -10 || idx === 10){
			if (stepLocation[count] === stepLocation[count - nBack]
			|| stepImage[count] === stepImage[count - nBack] ){
				//player missed this one.
				//too bad
				missCount++;
			}else{
				globalCoords.x = e.x + (idx=== -10 ? leftButton: rightButton);
				globalCoords.y = e.y + topButton;

				Ti.API.debug('no match');
				speedbonus += calcSpeedBonus(stepStartTime, new Date().getTime());
				coordbonus += calcCoordinationBonus("NOGO",cen,globalCoords);
				points += 2;
			}
		}
		gameStep();
	};

	function updateScore(){
		Ti.API.debug('updateScore :' + points + 'pts');
		score.text = '' + Math.round(points);
		countLabel.text = '' + Math.round(count);
		missCountLabel.text = (missCount === 0 ? '' : missCount + " missed");
		//round the bonus points
		bonus.text = Math.round(speedbonus) + ' speed\t' + Math.round(coordbonus) + ' coord\t' + Math.round(inhibitbonus) + ' oops';
	}

	// new game function
	function newGame(){
		//ultimately this should log stuff
		//at moment it doesn't do much

		//reset counters & other variables
		currentObj = 0;
		points = 0;
		coordbonus = 0;
		speedbonus = 0;
		inhibitbonus = 0;
		count = 0;
		missCount = 0;
		falseAlarmCount = 0;

		gameStarted = true;
		gameAllowRestart = false;
		startTime = new Date().getTime();
		labelGameMessage.visible = false;

		gameStep();
	}
	Ti.API.debug('gameMemory 2');

	/**
	 * The main game loop all the clever stuff happens in here
	 */
	function gameStep(){
		count++;
	 	Ti.API.debug('Game Step ' + count);
	 	clicked = false;
		if (missCount > 4){
			gameOver();
			return;
		}
		updateScore();

		stepStartTime = new Date().getTime();

		//get next item
		currentImg = Math.floor(9*Math.random());
		currentLoc = Math.floor(9*Math.random());
		//keep track of what has been shown.
		stepImage[count] = currentImg;
		stepLocation[count] = currentLoc;

		//show new item
		stimulus.visible = false;
		stimulus.image = fruitprefix + fruits[currentImg];
		stimulus.top = imgtop[currentLoc];
		stimulus.left = imgleft[currentLoc];
		stimulus.visible = true;

	}
	function gameOver(){
		//GAME OVER!
		stimulus.visible = false;
		// labelGameMessage.visible = true;
		// labelGameMessage.text = 'Final Score: ' + Math.floor(points+inhibitbonus+coordbonus+speedbonus) + '\nGame Over';
		count = 0;
		missCount = 0;
		gameStarted = false;
		gameEndSaveScores();
		dialogOpen = true;
		scoresDialog.setParent(win);
		scoresDialog.setScores( 'Memory Game',
								Math.floor(points+inhibitbonus+coordbonus+speedbonus),
								speedbonus,
								coordbonus,
								inhibitbonus,
								5,
								"",
								'/icons/Memory.png' );
		scoresDialog.open();
		Ti.API.debug('memory game over end');
	}
	scoresDialog.addEventListener('close', function(e){
		setTimeout(function(){
			dialogOpen = false;
			labelGameMessage.visible = true;
			labelGameMessage.text = 'Tap to start game';
			gameStarted = false;
			gameAllowRestart = true;
		}, 1000);
	});

	Ti.API.debug('gameMemory 3');

	function calcSpeedBonus(stepStart,clickTime){
		//TODO - the reaction time bonus
		//Ti.API.debug('calcSpeedBonus - stepStart' + stepStart);
		//Ti.API.debug('calcSpeedBonus - clickTime' + clickTime);
		var timediff = 10 - (clickTime -stepStart) /100;
		Ti.API.debug('calcSpeedBonus - timediff' + timediff);
		return Math.max(0, timediff);
	}

	function calcCoordinationBonus(trialType, centObj,centTouch){
		// a simple linear bonus of between 0 & 10 points for being
		// between 50 and 0 units from the object center
		var distx = centObj.x - centTouch.x;
		var disty = centObj.y - centTouch.y;
		var dist = Math.sqrt(distx*distx + disty*disty);
		Ti.API.debug('calcCoordinationBonus - dist' + dist);
		var bonusdist = Math.min(dist,50);
		return 10*(50-bonusdist)/250;
		if(trialType === "GO"){
			speed_GO += timediff;
		}else{
			speed_NOGO += timediff;
		}
	}
	function clear(o){
		var t  = o.text;
		setTimeout(function()
		{
			if (o.text == t)
			{
				o.text = "";
			}
		},2000);
	}

	function setUpOnce(){
		Ti.API.debug('win_gameMemory - setup once');
		var leftNOButton = Ti.UI.createButton({
			title:'No match',
			width:'100',
			height:'100',
			top:topButton,
			left:leftButton,
			backgroundColor:'#888',
			borderWidth:3,
			borderRadius:4,
			idx:-10
		});
		leftNOButton.addEventListener('click',function(events)
		{
			whatClicked(events);
		});
		win.add(leftNOButton);
		Ti.API.debug('win_gameMemory - setup once 2');

		var leftYESButton = Ti.UI.createButton({
			title:'Shape matched item 1 step before',
			width:'100',
			height:'100',
			top:bottomButton,
			left:leftButton,
			backgroundColor:'#888',
			borderWidth:3,
			borderRadius:4,
			idx:-1
		});
		leftYESButton.addEventListener('click',function(events)
		{
			whatClicked(events);
		});
		win.add(leftYESButton);

		var rightNOButton = Ti.UI.createButton({
			title:'No match',
			width:'100',
			height:'100',
			top:topButton,
			left:rightButton,
			backgroundColor:'#888',
			borderWidth:3,
			borderRadius:4,
			idx:10
		});
		rightNOButton.addEventListener('click',function(events)
		{
			whatClicked(events);
		});
		win.add(rightNOButton);

		var rightYESButton = Ti.UI.createButton({
			title:'Location matched item 1 step before',
			width:'100',
			height:'100',
			top:bottomButton,
			left:rightButton,
			backgroundColor:'#888',
			borderWidth:3,
			borderRadius:4,
			idx:1
		});
		rightYESButton.addEventListener('click',function(events)
		{
			whatClicked(events);
		});
		win.add(rightYESButton);

		Ti.API.debug('win_gameMemory - setup once 3');
		grid = Ti.UI.createView({
			//TODO
			//The grid image is commented out because of a bug in SDK 1.7.2
			//check back periodically to see if the bug has been fixed.
			// http://developer.appcelerator.com/question/40711/unable-to-load-bitmap-not-enough-memory-bitmap-size-exceeds-vm-budget#81151
			//backgroundImage:'/images/grid3x3.png',
			height:282,
			width:282,
			top:20,
			left:100
		});
		Ti.API.debug('win_gameMemory - setup once 4');
//		grid.visible = false;
		Ti.API.debug('win_gameMemory - setup once 5');
		win.add(grid);
		Ti.API.debug('win_gameMemory - setup once 6');
		stimulus = Ti.UI.createImageView({
				width:iconSize,height:iconSize,
				top:imgtop[0],
				left:imgleft[0],
				image:fruitprefix + fruits[0]
			});
		stimulus.visible = false;
		grid.add(stimulus);

		//
		//	The labels for the scores.
		//
		labelScore = Ti.UI.createLabel({
			color:'white',
			font:{fontSize:14,fontFamily:'Helvetica Neue'},
			top:2,
			left:2,
			textAlign:'left',
			text:'Score:',
			height:'auto',
			width:40
		});

		score = Ti.UI.createLabel({
			color:'green',
			font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			top:2,
			left:40,
			textAlign:'right',
			text:'      0',
			height:'auto',
			width:80
		});
		labelBonus = Ti.UI.createLabel({
			color:'white',
			font:{fontSize:12,fontFamily:'Helvetica Neue'},
			top:2,
			left:140,
			textAlign:'left',
			text:'Bonus',
			height:'auto',
			width:46
		});
		bonus = Ti.UI.createLabel({
			color:'red',
			font:{fontSize:12,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			top:2,
			left:190,
			textAlign:'right',
			text:'  0 speed,   0 coord,   0 oops',
			height:'auto',
			width:'auto'
		});

		//label for how many steps back we are currently counting
		countLabel = Ti.UI.createLabel({
			color:'black',
			font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			bottom:2,
			right:70,
			textAlign:'right',
			text:'0',
			width:100
		});

		//label for how many steps back we are currently counting
		nBackLabel = Ti.UI.createLabel({
			color:'blue',
			font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			bottom:2,
			right:2,
			textAlign:'right',
			text:'1 Back',
			width:100
		});

		//label for how many location or shape misses we have
		missCountLabel = Ti.UI.createLabel({
			color:'blue',
			font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			top:2,
			right:2,
			textAlign:'right',
			text:'0 Missed',
			width:100
		});

		// label across centre of screen for pause, start etc
		labelGameMessage = Ti.UI.createLabel({
			color:'purple',
			font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			textAlign:'center',
			text:'Tap to start'
		});
		win.add(labelScore);
		win.add(score);
		win.add(labelBonus);
		win.add(bonus);
		win.add(countLabel);
		win.add(nBackLabel);
		win.add(missCountLabel);
		win.add(labelGameMessage);

		Ti.API.debug('win_gameMemory - setup done');
	}

	Ti.API.debug('gameMemory 4');

	win.addEventListener('click',function(ev)
	{
		if (!gameStarted && gameAllowRestart && !dialogOpen){
		 	Ti.API.debug('Game Start');
			newGame();
		}
	});

	setUpOnce();
	Ti.API.debug('gameMemory 5');

	function gameEndSaveScores(){
		var now = parseInt((new Date()).getTime()/1000, 10);

		var gameSaveData = [{Game: 'DualNBack',
							GameVersion:2,
							PlayStart: startTime/1000 ,
							PlayEnd: now,
							TotalScore:points,
							GameSteps:count,
							Speed_GO:speedbonus,
							Speed_NOGO:0,
							Coord_GO:coordbonus,
							Coord_NOGO:0,
							Level:nBack,
							Inhibition:inhibitbonus,
							Feedback:count + ' steps',
							Choices:'',
							SessionID:Titanium.App.Properties.getInt('SessionID'),
							UserID:Titanium.App.Properties.getInt('UserID'),
							LabPoints:5 //,
						}];
		dbGameScores.SaveResult(gameSaveData);
	}

	//KLUDGE
	//to make parent window focus event fire when you press back button
	labelScore.focus();

	//
	// Cleanup and return home
	win.addEventListener('android:back', function(e) {
		if (!winHome) {
			var winmain = require('/win/win_main');
				winHome = winmain.createApplicationWindow();
		}
		win.close();
		winHome.open();
		winHome.refresh();
	});

	return win;
};


text:
package nl.armatiek.xmlindex.saxon.functions.xmlindex;
/*
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.BooleanValue;
import net.sf.saxon.value.SequenceType;
import nl.armatiek.xmlindex.conf.Definitions;

/**
 *
 * @author Maarten Kroon
 */
public class LocalVariableReferencer extends ExtensionFunctionDefinition {

  public static final StructuredQName qName =
      new StructuredQName("", Definitions.NAMESPACE_EXT_FUNCTIONS, "local-variable-referencer");

  @Override
  public StructuredQName getFunctionQName() {
    return qName;
  }

  @Override
  public int getMinimumNumberOfArguments() {
    return 1;
  }

  @Override
  public int getMaximumNumberOfArguments() {
    return 20;
  }

  @Override
  public SequenceType[] getArgumentTypes() {
    return new SequenceType[] {
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE,
        SequenceType.ANY_SEQUENCE
    };
  }

  @Override
  public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
    return SequenceType.SINGLE_BOOLEAN;
  }

  @Override
  public XMLIndexExtensionFunctionCall makeCallExpression() {
    return new LocalVariableReferencerCall();
  }

  @Override
  public boolean hasSideEffects() {
    return true;
  }

  public static class LocalVariableReferencerCall extends XMLIndexExtensionFunctionCall {

    @Override
    public BooleanValue call(XPathContext context, Sequence[] arguments) throws XPathException {
      return BooleanValue.TRUE;
    }
  }

}


text:
package org.jetbrains.plugins.scala
package util.macroDebug

import java.awt.BorderLayout

import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem._
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.{PsiDocumentManager, PsiFile}
import com.intellij.ui.JBSplitter
import org.jetbrains.plugins.scala.actions.ScalaActionUtil
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.worksheet.actions.{CleanWorksheetAction, TopComponentAction}
import org.jetbrains.plugins.scala.worksheet.runconfiguration.WorksheetCache

/**
 * @author Ksenia.Sautina
 * @author Dmitry Naydanov
 * @since 11/12/12
 */
class CleanMacrosheetAction() extends AnAction with TopComponentAction {

  def actionPerformed(e: AnActionEvent) {
    val editor: Editor = FileEditorManager.getInstance(e.getProject).getSelectedTextEditor
    val file: VirtualFile = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext)

    if (editor == null || file == null) return

    val psiFile: PsiFile = PsiDocumentManager.getInstance(e.getProject).getPsiFile(editor.getDocument)
    val viewer =  WorksheetCache.getInstance(e.getProject).getViewer(editor)

    if (psiFile == null || viewer == null) return

    val splitPane = viewer.getComponent.getParent.asInstanceOf[JBSplitter]
    val parent = splitPane.getParent
    if (parent == null) return

    invokeLater {
      inWriteAction {
        CleanWorksheetAction.resetScrollModel(viewer)

        CleanWorksheetAction.cleanWorksheet(psiFile.getNode, editor, viewer, e.getProject)

        parent.remove(splitPane)
        parent.add(editor.getComponent, BorderLayout.CENTER)
        editor.getSettings.setFoldingOutlineShown(true)
        ScalaMacroDebuggingUtil.macrosToExpand.clear()
      }
    }
  }

  override def update(e: AnActionEvent) {
    ScalaActionUtil.enableAndShowIfInScalaFile(e)
  }

  override def actionIcon = AllIcons.Actions.GC

  override def bundleKey = "worksheet.clear.button"
}


text:
package org.snf4j.core.codec.zip;

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

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class GzipEncoderTest extends EncoderTest {

	@Test
	public void testDeflateBound() throws Exception {
		TestGzipEncoder gzip = new TestGzipEncoder();

		assertEquals(ZlibEncoderTest.expectedBound(1)+8, gzip.deflateBound(1));
		assertEquals(ZlibEncoderTest.expectedBound(1000)+8, gzip.deflateBound(1000));
	}

	void assertEncode(String expected, int expectedCount, boolean decoderFinished) throws Exception {
		List<ByteBuffer> o = new ArrayList<ByteBuffer>();
		GzipDecoder d = new GzipDecoder();

		assertEquals(expectedCount, out.size());
		for (ByteBuffer bb: out) {
			byte[] b = new byte[bb.remaining()];
			ByteBuffer dup = bb.duplicate();

			dup.get(b);
			d.decode(null, b, o);
		}
		assertEquals(decoderFinished, d.isFinished());

		StringBuilder sb = new StringBuilder();
		for (ByteBuffer bb: o) {
			byte[] b = new byte[bb.remaining()];
			bb.get(b);
			sb.append(new String(b));
		}
		assertEquals(expected, sb.toString());
	}

	@Test
	public void testEncode() throws Exception {
		GzipEncoder e = new GzipEncoder();
		e.finish();
		e.encode(null, "abcd".getBytes(), out);
		assertEncode("abcd", 2, true);
		assertTrue(e.isFinished());
		out.clear();

		e = new GzipEncoder(9);
		e.encode(null, "1234567890".getBytes(), out);
		assertEncode("1234567890", 1, false);
		assertFalse(e.isFinished());
		e.encode(null, "XX".getBytes(), out);
		assertEncode("1234567890XX", 2, false);
		assertFalse(e.isFinished());
		e.finish();
		assertFalse(e.isFinished());
		e.encode(null, "YY".getBytes(), out);
		assertEncode("1234567890XXYY", 4, true);
		assertTrue(e.isFinished());
		out.clear();

	}

	static class TestGzipEncoder extends GzipEncoder {

		int boundOut;

		@Override
		public int deflateBound(int len) {
			boundOut = super.deflateBound(len);
			return boundOut;
		}
	}
}