text:
/// <reference path="../../src/Kiwi.ts" />

/**
* This script is a demonstration of how you can apply transforms to a group and how it affects the gameobjects inside of it.
**/

class GroupMovement extends Kiwi.State {

    constructor() {
        super('GroupMovement');
    }

    preload() {
        this.game.stage.resize(800, 250);
        this.addSpriteSheet('snake', 'assets/spritesheets/snake.png', 150, 117);
    }

    snakes: Kiwi.Group;
    numSnakes: number = 50;         //number of snakes to spawn
    direction: string = 'right';    //the direction the group is facing

    create() {

        //to see information about animations look at the animation component section
        this.textures.snake.sequences.push(new Kiwi.Animations.Sequence('slither', [1, 2, 3, 4, 5, 6], 0.1, true));

        //create a new group and add it to the stage
        this.snakes = new Kiwi.Group(this);
        this.addChild(this.snakes);

        /**
        * Create some new snakes and add them all to the snakes group.
        **/
        for (var i = 0; i < this.numSnakes; i++) {

            var s = new Kiwi.GameObjects.Sprite(this, this.textures.snake, Math.random() * this.game.stage.width, Math.random() * this.game.stage.height - 117 );
            this.snakes.addChild(s);
            s.animation.play('slither');

        }

    }

    update() {
        super.update();

        /**
        * Move the entire group in the 'right' or 'left' direction.
        **/
        if (this.direction == 'right') {

            this.snakes.scaleX = 1;
            this.snakes.x += 3;

            if (this.snakes.x > this.game.stage.width) {
                this.direction = 'left';
                this.snakes.x *= 2;
            }

        } else {

            this.snakes.scaleX = -1;
            this.snakes.x -= 3;

            if (this.snakes.x < -150) {
                this.direction = 'right';
                this.snakes.x -= this.game.stage.width;
            }

        }
    }

}

//Create's a new Kiwi.Game.
/*
* Param One - DOMID - String - ID of a DOMElement that the game will reside in.
* Param Two - GameName - String - Name that the game will be given.
* Param Three - State - Object - The state that is to be loaded by default.
* Param Four - Options - Object - Optional options that the game will use whilst playing. Currently this is used to to choose the renderer/debugmode/device to target
*/
if (typeof gameOptions == "undefined") var gameOptions  = {};

var game = new Kiwi.Game('game', 'KiwiExample', GroupMovement, gameOptions );

redpajama_set_name: RedPajamaGithub


text: export PATH=$HOME/Code/nancy/bin:$PATH


text:
[![NPM Version](http://img.shields.io/npm/v/touchy.svg?style=flat)](https://npmjs.org/package/touchy)

# touchy

Yet another `tap`, `tap:hold` and `swipe` events enabler. Based on
[xtap-event](https://github.com/royriojas/xtap-event)/[tap.js](https://github.com/alexgibson/tap.js/)

TODO: Add unit tests

## installation

```bash
npm i --save touchy
```

## usage

```javascript
// usually this is enough to generate the events
// this can be done in a module that can be required
// at the beginning of your app to generate the events
var touchy = require('touchy');
touchy.enableOn(document);
```

## Events

This library will generate the following events:

- `tap`
- `tap:hold`
- `swipe`
- `swipe:up`
- `swipe:down`
- `swipe:left`
- `swipe:right`

### tap

The `tap` event is generated when:

- a `touchstart`/`mousedown` event is followed by a `touchend`/`mouseup`
- the `end target` is the same as the `start target`
- the user hasn't move the finger between the starting event and the end
  event for more than `options.minTapDisplacementTolerance` (default: 10px)
- the time between `touchstart`/`mousedown` and `touchend`/`mouseup` is
  less than `opts.tapHoldMinThreshold` (default: 500ms)

**Example**

```javascript
// usually this is enough to generate the events
var touchy = require('touchy');
touchy.enableOn(document);

var ele = document.querySelector('#selector');
ele.on('tap', function (e) {
  console.log('tap!');
});
```

### tap:hold

The `tap:hold` event is generated when:

- a `touchstart`/`mousedown` event is followed by a `touchend`/`mouseup`
- the `end target` is the same as the `start target`
- the user hasn't move the finger between the starting event and the end
  event for more than `options.minTapDisplacementTolerance` (default: 10px)
- the user has not released the finger for more than `opts.tapHoldMinThreshold` (default: 500ms)

**Example**

```javascript
// usually this is enough to generate the events
var touchy = require('touchy');
touchy.enableOn(document);

var ele = document.querySelector('#selector');
ele.on('tap:hold', function (e) {
  console.log('tap:hold!');
});
```

### swipe, swipe:left, swipe:right, swipe:up and swipe:down

The `swipe` event is generated when

- a `touchstart`/`mousedown` event is followed by `touchmove`/`mousemove` and then by a `touchend`/`mouseup`
- the user has moved the finger between the starting event and the end
  event for more than `options.minTapDisplacementTolerance` (default: 10px)
- a `tap:hold` event has not being generated

**Example**

```javascript
// usually this is enough to generate the events
var touchy = require('touchy');
touchy.enableOn(document);

var ele = document.querySelector('#selector');
ele.on('swipe', function (e) {
  console.log('swipe', e.detail.direction); // direction: down, up, left, right
});
```

Custom events are also generated with the direction of the swipe: `swipe:left`, `swipe:right`, `swipe:up` and `swipe:down`

```javascript
// usually this is enough to generate the events
var touchy = require('touchy');
touchy.enableOn(document);

var ele = document.querySelector('#selector');
ele.on('swipe:left', function (e) {
  console.log('swipe:left');
});
```


text:
package io.opencensus.exporter.trace.ocagent;

import com.google.common.annotations.VisibleForTesting;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import io.opencensus.proto.agent.common.v1.Node;
import io.opencensus.proto.agent.trace.v1.CurrentLibraryConfig;
import io.opencensus.proto.agent.trace.v1.TraceServiceGrpc.TraceServiceStub;
import io.opencensus.proto.agent.trace.v1.UpdatedLibraryConfig;
import io.opencensus.trace.config.TraceConfig;
import io.opencensus.trace.config.TraceParams;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;

/** Handler of config service RPC. */
@ThreadSafe
final class OcAgentTraceServiceConfigRpcHandler {

  private static final Logger logger =
      Logger.getLogger(OcAgentTraceServiceConfigRpcHandler.class.getName());

  // A reference to the currentConfigObserver returned from stub.
  @GuardedBy("this")
  @Nullable
  private StreamObserver<CurrentLibraryConfig> currentConfigObserver;

  // The RPC status when this stream finishes/disconnects. Null if the stream is still connected.
  @GuardedBy("this")
  @Nullable
  private Status terminateStatus;

  private final TraceConfig traceConfig; // Inject a mock TraceConfig in unit tests.

  private OcAgentTraceServiceConfigRpcHandler(TraceConfig traceConfig) {
    this.traceConfig = traceConfig;
  }

  private synchronized void setCurrentConfigObserver(
      StreamObserver<CurrentLibraryConfig> currentConfigObserver) {
    this.currentConfigObserver = currentConfigObserver;
  }

  // Creates an OcAgentTraceServiceConfigRpcHandler. Tries to initiate the config stream with the
  // given TraceServiceStub.
  static OcAgentTraceServiceConfigRpcHandler create(
      TraceServiceStub stub, TraceConfig traceConfig) {
    OcAgentTraceServiceConfigRpcHandler configRpcHandler =
        new OcAgentTraceServiceConfigRpcHandler(traceConfig);
    UpdatedLibraryConfigObserver updatedLibraryConfigObserver =
        new UpdatedLibraryConfigObserver(traceConfig, configRpcHandler);
    try {
      StreamObserver<CurrentLibraryConfig> currentConfigObserver =
          stub.config(updatedLibraryConfigObserver);
      configRpcHandler.setCurrentConfigObserver(currentConfigObserver);
    } catch (StatusRuntimeException e) {
      configRpcHandler.onComplete(e);
    }
    return configRpcHandler;
  }

  // Sends the initial config message with Node to Agent.
  // Once the initial config message is sent, the current thread will be blocked watching for
  // subsequent updated library configs, unless the stream is interrupted.
  synchronized void sendInitialMessage(Node node) {
    io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto =
        TraceProtoUtils.getCurrentTraceConfig(traceConfig);
    // First config must have Node set.
    CurrentLibraryConfig firstConfig =
        CurrentLibraryConfig.newBuilder().setNode(node).setConfig(currentTraceConfigProto).build();
    sendCurrentConfig(firstConfig);
  }

  // Follow up after applying the updated library config.
  private synchronized void sendCurrentConfig() {
    // Bouncing back CurrentLibraryConfig to Agent.
    io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto =
        TraceProtoUtils.getCurrentTraceConfig(traceConfig);
    CurrentLibraryConfig currentLibraryConfig =
        CurrentLibraryConfig.newBuilder().setConfig(currentTraceConfigProto).build();
    sendCurrentConfig(currentLibraryConfig);
  }

  // Sends current config to Agent if the stream is still connected, otherwise do nothing.
  private synchronized void sendCurrentConfig(CurrentLibraryConfig currentLibraryConfig) {
    if (isCompleted() || currentConfigObserver == null) {
      return;
    }
    try {
      currentConfigObserver.onNext(currentLibraryConfig);
    } catch (Exception e) { // Catch client side exceptions.
      onComplete(e);
    }
  }

  // Marks this config stream as completed with an optional error.
  // Once onComplete is called, this OcAgentTraceServiceConfigRpcHandler instance can be discarded
  // and GC'ed in the worker thread.
  synchronized void onComplete(@javax.annotation.Nullable Throwable error) {
    if (isCompleted()) {
      return;
    }
    currentConfigObserver = null;
    // TODO(songya): add Runnable
    Status status;
    if (error == null) {
      status = Status.OK;
    } else if (error instanceof StatusRuntimeException) {
      status = ((StatusRuntimeException) error).getStatus();
    } else {
      status = Status.UNKNOWN;
    }
    terminateStatus = status;
  }

  synchronized boolean isCompleted() {
    return terminateStatus != null;
  }

  @VisibleForTesting
  @Nullable
  synchronized Status getTerminateStatus() {
    return terminateStatus;
  }

  @VisibleForTesting
  static class UpdatedLibraryConfigObserver implements StreamObserver<UpdatedLibraryConfig> {

    private final TraceConfig traceConfig;
    private final OcAgentTraceServiceConfigRpcHandler configRpcHandler;

    @VisibleForTesting
    UpdatedLibraryConfigObserver(
        TraceConfig traceConfig, OcAgentTraceServiceConfigRpcHandler configRpcHandler) {
      this.traceConfig = traceConfig;
      this.configRpcHandler = configRpcHandler;
    }

    @Override
    public void onNext(UpdatedLibraryConfig value) {
      // First, apply the incoming updated config.
      TraceParams updatedTraceParams = TraceProtoUtils.getUpdatedTraceParams(value, traceConfig);
      traceConfig.updateActiveTraceParams(updatedTraceParams);

      // Then echo back current config.
      configRpcHandler.sendCurrentConfig();
    }

    @Override
    public void onError(Throwable t) {
      logger.log(Level.WARNING, "Config stream is disconnected.", t);
      configRpcHandler.onComplete(t);
    }

    @Override
    public void onCompleted() {
      configRpcHandler.onComplete(null);
    }
  }
}


text:
struct HLandscapeSplineProxy : public HHitProxy
{
	DECLARE_HIT_PROXY( LANDSCAPE_API );

	HLandscapeSplineProxy(EHitProxyPriority InPriority = HPP_Wireframe) :
		HHitProxy(InPriority)
	{
	}
	virtual EMouseCursor::Type GetMouseCursor() override
	{
		return EMouseCursor::Crosshairs;
	}
};

struct HLandscapeSplineProxy_Segment : public HLandscapeSplineProxy
{
	DECLARE_HIT_PROXY( LANDSCAPE_API );

	class ULandscapeSplineSegment* SplineSegment;

	HLandscapeSplineProxy_Segment(class ULandscapeSplineSegment* InSplineSegment) :
		HLandscapeSplineProxy(),
		SplineSegment(InSplineSegment)
	{
	}
	virtual void AddReferencedObjects( FReferenceCollector& Collector ) override
	{
		Collector.AddReferencedObject( SplineSegment );
	}
};

struct HLandscapeSplineProxy_ControlPoint : public HLandscapeSplineProxy
{
	DECLARE_HIT_PROXY( LANDSCAPE_API );

	class ULandscapeSplineControlPoint* ControlPoint;

	HLandscapeSplineProxy_ControlPoint(class ULandscapeSplineControlPoint* InControlPoint) :
		HLandscapeSplineProxy(HPP_Foreground),
		ControlPoint(InControlPoint)
	{
	}
	virtual void AddReferencedObjects( FReferenceCollector& Collector ) override
	{
		Collector.AddReferencedObject( ControlPoint );
	}
};

struct HLandscapeSplineProxy_Tangent : public HLandscapeSplineProxy
{
	DECLARE_HIT_PROXY( LANDSCAPE_API );

	ULandscapeSplineSegment* SplineSegment;
	uint32 End:1;

	HLandscapeSplineProxy_Tangent(class ULandscapeSplineSegment* InSplineSegment, bool InEnd) :
		HLandscapeSplineProxy(HPP_UI),
		SplineSegment(InSplineSegment),
		End(InEnd)
	{
	}
	LANDSCAPE_API virtual void Serialize(FArchive& Ar);

	virtual EMouseCursor::Type GetMouseCursor() override
	{
		return EMouseCursor::CardinalCross;
	}
};


text:
<?php

namespace Phorms;

interface Element {

  /***
   * Returns an array of variables extracted from the provided $post
   **/
  function data($post);

  /***
   * Returns an array of errors for the provided data
   **/
  function check($data);

  /***
   * Saves an array of errors for the provided data
   **/
  function errors($errors);

  /***
   * Returns an array of element names
   **/
  function names();

  /***
   * Returns a element given its name
   **/
  function getElement($name);

  /***
   * Searches element by a given selector
   **/
  function queryElements($selector);

  /***
   * Removes a element given its name
   **/
  function removeElement($name);

  /***
   * Replaces one element with another
   **/
  function replaceElement($element, $with);
}


text:
bandit
======
[![Build Status](https://travis-ci.org/joakimkarlsson/bandit.svg)](https://travis-ci.org/joakimkarlsson/bandit)

Human friendly unit testing for C++11

Bandit is a framework for C++11 that wants to make working with unit tests a pleasant
experience.

For more information, go to [the bandit website](http://banditcpp.org).

Bandit is released under the [MIT license](LICENSE.md)

#An example

This is a complete test application written in bandit:

```cpp
#include <bandit/bandit.h>
using namespace bandit;

// Tell bandit there are tests here.
go_bandit([](){

    // We're describing how a fuzzbox works.
    describe("fuzzbox:", [](){
      guitar_ptr guitar;
      fuzzbox_ptr fuzzbox;

      // Make sure each test has a fresh setup with
      // a guitar with a fuzzbox connected to it.
      before_each([&](){
        guitar = guitar_ptr(new struct guitar());
        fuzzbox = fuzzbox_ptr(new struct fuzzbox());
        guitar->add_effect(*fuzzbox);
      });

      it("starts in clean mode", [&](){
        AssertThat(guitar->sound(), Equals(sounds::clean));
      });

      // Describe what happens when we turn on the fuzzbox.
      describe("in distorted mode", [&](){

        // Turn on the fuzzbox.
        before_each([&](){
          fuzzbox->flip();
        });

        it("sounds distorted", [&](){
          AssertThat(guitar->sound(), Equals(sounds::distorted));
        });
      });
    });

});

int main(int argc, char* argv[])
{
  // Run the tests.
  return bandit::run(argc, argv);
}
```


text:
import creditcards from 'creditcards';

/**
 * Omit null or empty string properties of object
 * @param {Object} object
 * @returns {Object}
 */
const omitNullString = obj => {
    const refObj = obj;

    $.each(refObj, (key, value) => {
        if (value === null || value === '') {
            delete refObj[key];
        }
    });

    return refObj;
};

/**
 * Get credit card type from credit card number
 * @param {string} value
 */
export const creditCardType = value => creditcards.card.type(creditcards.card.parse(value), true);

/**
 * Wrapper for ajax request to store a new instrument in bigpay
 * @param {object} Representing the data needed for the header
 * @param {object} Representing the data needed for the body
 * @param {function} done Function to execute on a successful response
 * @param {function} fail Function to execute on a unsuccessful response
 */
export const storeInstrument = ({
    // Hostname, Ids & Token
    paymentsUrl,
    shopperId,
    storeHash,
    vaultToken,
}, {
    /* eslint-disable */
    // Provider Name
    provider_id,

    // Instrument Details
    credit_card_number,
    expiration,
    name_on_card,
    cvv,
    default_instrument,

    // Billing Address
    address1,
    address2,
    city,
    postal_code,
    state_or_province_code,
    country_code,
    company,
    first_name,
    last_name,
    email,
    phone,
    /* eslint-enable */
}, done, fail) => {
    const expiry = expiration.split('/');

    $.ajax({
        url: `${paymentsUrl}/stores/${storeHash}/customers/${shopperId}/stored_instruments`,
        dataType: 'json',
        method: 'POST',
        cache: false,
        headers: {
            Authorization: vaultToken,
            Accept: 'application/vnd.bc.v1+json',
            'Content-Type': 'application/vnd.bc.v1+json',
        },
        data: JSON.stringify({
            instrument: {
                type: 'card',
                cardholder_name: name_on_card,
                number: creditcards.card.parse(credit_card_number),
                expiry_month: creditcards.expiration.month.parse(expiry[0]),
                expiry_year: creditcards.expiration.year.parse(expiry[1], true),
                verification_value: cvv,
            },
            billing_address: omitNullString({
                address1,
                address2,
                city,
                postal_code,
                state_or_province_code,
                country_code,
                company,
                first_name,
                last_name,
                email,
                phone,
            }),
            provider_id,
            default_instrument,
        }),
    })
        .done(done)
        .fail(fail);
};

export const Formatters = {
    /**
     * Sets up a format for credit card number
     * @param field
     */
    setCreditCardNumberFormat: field => {
        if (field) {
            $(field).on('keyup', ({ target }) => {
                const refTarget = target;
                refTarget.value = creditcards.card.format(creditcards.card.parse(target.value));
            });
        }
    },

    /**
     * Sets up a format for expiration date
     * @param field
     */
    setExpirationFormat: field => {
        if (field) {
            $(field).on('keyup', ({ target, which }) => {
                const refTarget = target;
                if (which === 8 && /.*(\/)$/.test(target.value)) {
                    refTarget.value = target.value.slice(0, -1);
                } else if (target.value.length > 4) {
                    refTarget.value = target.value.slice(0, 5);
                } else if (which !== 8) {
                    refTarget.value = target.value
                        .replace(/^([1-9]\/|[2-9])$/g, '0$1/')
                        .replace(/^(0[1-9]|1[0-2])$/g, '$1/')
                        .replace(/^([0-1])([3-9])$/g, '0$1/$2')
                        .replace(/^(0[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2')
                        .replace(/^([0]+)\/|[0]+$/g, '0')
                        .replace(/[^\d\/]|^[\/]*$/g, '')
                        .replace(/\/\//g, '/');
                }
            });
        }
    },
};

export const Validators = {
    /**
     * Sets up a validation for credit card number
     * @param validator
     * @param field
     * @param errorMessage
     */
    setCreditCardNumberValidation: (validator, field, errorMessage) => {
        if (field) {
            validator.add({
                selector: field,
                validate: (cb, val) => {
                    const result = val.length && creditcards.card.isValid(creditcards.card.parse(val));

                    cb(result);
                },
                errorMessage,
            });
        }
    },

    /**
     * Sets up a validation for expiration date
     * @param validator
     * @param field
     * @param errorMessage
     */
    setExpirationValidation: (validator, field, errorMessage) => {
        if (field) {
            validator.add({
                selector: field,
                validate: (cb, val) => {
                    const expiry = val.split('/');
                    let result = val.length && /^(0[1-9]|1[0-2])\/([0-9]{2})$/.test(val);
                    result = result && !creditcards.expiration.isPast(creditcards.expiration.month.parse(expiry[0]), creditcards.expiration.year.parse(expiry[1], true));

                    cb(result);
                },
                errorMessage,
            });
        }
    },

    /**
     * Sets up a validation for name on card
     * @param validator
     * @param field
     * @param errorMessage
     */
    setNameOnCardValidation: (validator, field, errorMessage) => {
        if (field) {
            validator.add({
                selector: field,
                validate: (cb, val) => {
                    const result = !!val.length;

                    cb(result);
                },
                errorMessage,
            });
        }
    },

    /**
     * Sets up a validation for cvv
     * @param validator
     * @param field
     * @param errorMessage
     * @param {any} cardType The credit card number type
     */
    setCvvValidation: (validator, field, errorMessage, cardType) => {
        if (field) {
            validator.add({
                selector: field,
                validate: (cb, val) => {
                    const type = typeof cardType === 'function' ? cardType() : cardType;
                    const result = val.length && creditcards.cvc.isValid(val, type);

                    cb(result);
                },
                errorMessage,
            });
        }
    },
};


text:
using namespace BloombergLP;

//=============================================================================
//                             TEST PLAN
//-----------------------------------------------------------------------------
// 'bsls::Util' is a utility class, where each function will be tested in a
// separate test case.  Any significant test machinery will be tested before
// any function whose test case relies upon it.
//
// Further, there are a number of behaviors that explicitly should not compile
// by accident that we will provide tests for.  These tests should fail to
// compile if the appropriate macro is defined.  Each such test will use a
// unique macro for its feature test, and provide a commented-out definition of
// that macro immediately above the test, to easily enable compiling that test
// while in development.  Below is the list of all macros that control the
// availability of these tests:
//  #define BSLS_UTIL_COMPILE_FAIL_FORWARD_RVALUE_AS_LVALUE
//-----------------------------------------------------------------------------
// [2] TYPE *bsls::Util::addressOf(TYPE&);
// [3] BSLS_UTIL_ADDRESSOF macro
// [4] TYPE&& forward(typename Util_RemoveReference<TYPE>::type& t);
//-----------------------------------------------------------------------------
// [5] USAGE EXAMPLE
//
// Test apparatus
// [1]  CvQualification cvqOfPtr(T *p);
// [1]  EvilType *EvilType::operator&();
// [1]  EvilType *EvilType::realAddress();

//-----------------------------------------------------------------------------

// ============================================================================
//                      STANDARD BDE ASSERT TEST MACROS
// ----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.

namespace {

int testStatus = 0;

void aSsErT(bool b, const char *s, int i)
{
    if (b) {
        printf("Error " __FILE__ "(%d): %s    (failed)\n", i, s);
        if (testStatus >= 0 && testStatus <= 100) ++testStatus;
    }
}

}  // close unnamed namespace

// ============================================================================
//                      STANDARD BDE TEST DRIVER MACROS
// ----------------------------------------------------------------------------

#define ASSERT       BSLS_BSLTESTUTIL_ASSERT
#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define ASSERTV      BSLS_BSLTESTUTIL_ASSERTV

#define Q   BSLS_BSLTESTUTIL_Q   // Quote identifier literally.
#define P   BSLS_BSLTESTUTIL_P   // Print identifier and value.
#define P_  BSLS_BSLTESTUTIL_P_  // P(X) without '\n'.
#define T_  BSLS_BSLTESTUTIL_T_  // Print a tab (w/o newline).
#define L_  BSLS_BSLTESTUTIL_L_  // current Line number

//=============================================================================
//                              USAGE EXAMPLE
//-----------------------------------------------------------------------------
///Usage
///-----
// This section illustrates intended usage of this component.
//
///Example 1: Obtain the address of a 'class' that defines 'operator&'.
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// There are times, especially within low-level library functions, where it is
// necessary to obtain the address of an object even if that object's class
// overloads 'operator&' to return something other than the object's address.
//
// First, we create a special reference-like type that can refer to a single
// bit within a byte (inline implementations are provided in class scope for
// ease of exposition):
//..
    class BitReference {

        // DATA
        char *d_byte_p;
        int   d_bitpos;

      public:
        // CREATORS
        BitReference(char *byteptr = 0, int bitpos = 0)             // IMPLICIT
        : d_byte_p(byteptr)
        , d_bitpos(bitpos)
        {
        }

        // ACCESSORS
        operator bool() const { return (*d_byte_p >> d_bitpos) & 1; }

        int bitpos() const { return d_bitpos; }
        char *byteptr() const { return d_byte_p; }
    };
//..
// Then, we create a pointer-like type that can point to a single bit:
//..
    class BitPointer {

        // DATA
        char *d_byte_p;
        int   d_bitpos;

      public:
        // CREATORS
        BitPointer(char *byteptr = 0, int bitpos = 0)               // IMPLICIT
        : d_byte_p(byteptr)
        , d_bitpos(bitpos)
        {
        }

        // ACCESSORS
        BitReference operator*() const
        {
            return BitReference(d_byte_p, d_bitpos);
        }

        // etc.
    };
//..
// Next, we overload 'operator&' for 'BitReference' to return a 'BitPointer'
// instead of a raw pointer, completing the setup:
//..
    inline BitPointer operator&(const BitReference& ref)
    {
        return BitPointer(ref.byteptr(), ref.bitpos());
    }
//..

//=============================================================================
//                  GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------

struct EvilType {
    // This 'struct' supplies an overload for the unary 'operator&' in order to
    // test the correct behavior of the 'bsls::Util::addressOf' function.  Each
    // 'EvilType' object will reports its address as that returned by the
    // 'bogusPtr' method, which points to some statically allocated memory
    // outside the object itself.  The true address of such an object can be
    // discovered by calling the 'realAddress' method.

    // DATA
    int        d_dummy; // Some data to avoid empty-class optimizations
    static int d_bogus; // statically allocated object representing bad address

  public:
    // CLASS METHODS
    static EvilType *bogusPtr() {
        // Return the address of some valid memory that is not within the
        // footprint of any 'EvilType' object.
        return reinterpret_cast<EvilType*>(&d_bogus);
    }

    // CREATORS
    explicit EvilType(int val = 0) : d_dummy(val) { }
        // Create a 'EvilType' object.

    // ACCESSORS
    EvilType                *operator&()                { return bogusPtr(); }
    EvilType const          *operator&() const          { return bogusPtr(); }
    EvilType volatile       *operator&() volatile       { return bogusPtr(); }
    EvilType const volatile *operator&() const volatile { return bogusPtr(); }
        // Overload operator& to return something other than the address of
        // this object.

    EvilType                *realAddress()                { return this; }
    EvilType const          *realAddress() const          { return this; }
    EvilType volatile       *realAddress() volatile       { return this; }
    EvilType const volatile *realAddress() const volatile { return this; }
        // Return the actual address of this object.
};

int EvilType::d_bogus = 0;

template <class TYPE1, class TYPE2>
struct TestAreSame {
    static bool test() {
        return false;
    }
};

template <class TYPE>
struct TestAreSame<TYPE, TYPE> {
    static bool test() {
        return true;
    }
};

//=============================================================================
//                  GLOBAL HELPER FUNCTIONS FOR TESTING
//-----------------------------------------------------------------------------

enum CvQualification {
    CVQ_UNQUALIFIED,
    CVQ_CONST,
    CVQ_VOLATILE,
    CVQ_CONST_VOLATILE
};

template <class TYPE>
inline
CvQualification cvqOfPtr(TYPE *) { return CVQ_UNQUALIFIED; }

template <class TYPE>
inline
CvQualification cvqOfPtr(const TYPE *) { return CVQ_CONST; }

template <class TYPE>
inline
CvQualification cvqOfPtr(volatile TYPE *) { return CVQ_VOLATILE; }

template <class TYPE>
inline
CvQualification cvqOfPtr(const volatile TYPE *) { return CVQ_CONST_VOLATILE; }

namespace TestFuncs
{
void a() {}
int b(double&) { return 0; }
double *c(const int &, volatile double) { return 0; }
}  // close namespace TestFuncs

//=============================================================================
//                              MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int             test = argc > 1 ? atoi(argv[1]) : 0;
    bool         verbose = argc > 2;
    bool     veryVerbose = argc > 3;
    bool veryVeryVerbose = argc > 4;

    (void) veryVeryVerbose;

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.
      case 5: {
        // --------------------------------------------------------------------
        // USAGE EXAMPLE
        //
        // Concerns:
        //: 1 The usage example provided in the component header file compiles,
        //:   links, and runs as shown.
        //
        // Plan:
        //: 1 Incorporate usage example from header into test driver, remove
        //:   leading comment characters, and replace 'assert' with 'ASSERT'.
        //:   (C-1)
        //
        // Testing:
        //   USAGE EXAMPLE
        // --------------------------------------------------------------------

        if (verbose) printf("\nUSAGE EXAMPLE"
                            "\n=============\n");

// Then, we note that there are times when it might be desirable to get the
// true address of a 'BitReference'.  Since the above overload prevents the
// obvious syntax from working, we use 'bsls::Util::addressOf' to accomplish
// this task.
//
// Next, we create a 'BitReference' object:
//..
    char c[4];
    BitReference br(c, 3);
//..
// Now, we invoke 'bsls::Util::addressOf' to obtain and save the address of
// 'br':
//..
    BitReference *p = bsls::Util::addressOf(br);  // OK
    // BitReference *p = &br;                     // Won't compile
//..
// Notice that the commented line illustrates canonical use of 'operator&' that
// would not compile in this example.
//
// Finally, we verify that address obtained is the correct one, running some
// sanity checks:
//..
    ASSERT(0 != p);
    ASSERT(c == p->byteptr());
    ASSERT(3 == p->bitpos());
//..
      } break;
      case 4: {
        // --------------------------------------------------------------------
        // TESTING 'forward'
        //
        // Concerns:
        //: 1 Calling 'bsls::Util::forward' with an lvalue will return an
        //:   lvalue reference to that object.
        //:
        //: 2 Calling 'bsls::Util::forward' with an rvalue will return an
        //:   rvalue reference to that object.
        //:
        //: 3 'bsls::Util::forward' preserves cv-qualifiers of the forwarded
        //:   type.
        //:
        //: 4 The 'bsls::Util::forward' methods are 'noexcept'.
        //:
        //: 5 The 'bsls::Util::forward' methods are 'constexpr'.
        //:
        //: 6 It is a compile time error to pass an rvalue to be forwarded as
        //:   an lvalue.
        //
        // Plan:
        //: 1 Call 'forward<int&>' with a non-cv-qualified lvalue and assign
        //:   the result to an 'int&'.  Verify that the addresses of the lvalue
        //:   argument and the return value match.  Repeat with cv-qualified
        //:   lvalues. (C1, C3)
        //:
        //: 2 Call 'forward<int>' with a non-cv-qualified rvalue and assign
        //:   the result to an 'int&&'.  Verify that the addresses of the
        //:   rvalue argument and the return value match.  Repeat with
        //:   cv-qualified rvalues. (C2, C3)
        //:
        //: 3 Call 'forward<int>' with a non-cv-qualified prvalue and assign
        //:   the result to an 'int&&'.  Verify that the values of the prvalue
        //:   argument and the return value match.  Repeat with cv-qualified
        //:   prvalues. (C2, C3)
        //:
        //: 4 Try forwarding a prvalue as an lvalue ('forward<int&>(42)') and
        //:   check that it does not compile.  Notice that this is a manual
        //:   test that need to be enabled by defining the
        //:   'BSLS_UTIL_COMPILE_FAIL_FORWARD_RVALUE_AS_LVALUE' macro. (C6)
        //:
        //: 5 If the compiler supports 'noexcept' use the 'noexcept' operator
        //:   to test that both overloads of 'forward' are 'noexcept'.
        //:
        //: 6 If the compiler supports 'constexpr' use 'constexpr' input to
        //:   'forward' and assign the return value to a 'constexpr' variable.
        //:   The code will not compile if 'forward' is not declared
        //:   'constexpr'.  Notice that rvalues cannot be 'constexpr' so we do
        //:   not test for them.
        //
        // Testing:
        //   TYPE&& forward(typename Util_RemoveReference<TYPE>::type& t);
        // --------------------------------------------------------------------

#ifndef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES
        if (verbose) printf("\nSKIPPED TESTING 'forward'"
                            "\n=========================\n");
#else
        if (verbose) printf("\nTESTING 'forward'"
                            "\n=================\n");

        // Non-cv-qualified

        int lvalue = 42;
        int& lvalueResult = bsls::Util::forward<int&>(lvalue);
        ASSERTV(&lvalue, &lvalueResult, &lvalue == &lvalueResult);
        ASSERT((TestAreSame<int&,
                        decltype(bsls::Util::forward<int&>(lvalue))>::test()));

        int&& rvalue = 42;
        int&& rvalueResult = bsls::Util::forward<int>(rvalue);
        ASSERTV(&rvalue, &rvalueResult, &rvalue == &rvalueResult);
        ASSERT((TestAreSame<int&&,
                         decltype(bsls::Util::forward<int>(rvalue))>::test()));

        // 'const' values

        const int clvalue = 42;
        const int& clvalueResult = bsls::Util::forward<const int&>(clvalue);
        ASSERTV(&clvalue, &clvalueResult, &clvalue == &clvalueResult);
        ASSERT((TestAreSame<const int&,
                 decltype(bsls::Util::forward<const int&>(clvalue))>::test()));

        const int&& crvalue = 42;
        const int&& crvalueResult = bsls::Util::forward<const int>(crvalue);
        ASSERTV(&crvalue, &crvalueResult, &crvalue == &crvalueResult);
        ASSERT((TestAreSame<const int&&,
                  decltype(bsls::Util::forward<const int>(crvalue))>::test()));

        // 'volatile' values

        volatile int vlvalue = 42;
        volatile int& vlvalueResult =
                                   bsls::Util::forward<volatile int&>(vlvalue);
        ASSERTV(&vlvalue, &vlvalueResult, &vlvalue == &vlvalueResult);
        ASSERT((TestAreSame<volatile int&,
              decltype(bsls::Util::forward<volatile int&>(vlvalue))>::test()));

        volatile int&& vrvalue = 42;
        volatile int&& vrvalueResult =
                                    bsls::Util::forward<volatile int>(vrvalue);
        ASSERTV(&vrvalue, &vrvalueResult, &vrvalue == &vrvalueResult);
        ASSERT((TestAreSame<volatile int&&,
               decltype(bsls::Util::forward<volatile int>(vrvalue))>::test()));

        // 'const' 'volatile' values

        typedef const volatile int cvint;

        cvint cvlvalue = 42;
        cvint& cvlvalueResult = bsls::Util::forward<cvint&>(cvlvalue);
        ASSERTV(&cvlvalue, &cvlvalueResult, &cvlvalue == &cvlvalueResult);
        ASSERT((TestAreSame<cvint&,
                    decltype(bsls::Util::forward<cvint&>(cvlvalue))>::test()));

        cvint&& cvrvalue = 42;
        cvint&& cvrvalueResult = bsls::Util::forward<cvint>(cvrvalue);
        ASSERTV(&cvrvalue, &cvrvalueResult, &cvrvalue == &cvrvalueResult);
        ASSERT((TestAreSame<cvint&&,
                     decltype(bsls::Util::forward<cvint>(cvrvalue))>::test()));

# ifdef BSLS_UTIL_COMPILE_FAIL_FORWARD_RVALUE_AS_LVALUE
        bsls::Util::forward<int&>(42);                             // Concern 6
# endif

# ifdef BSLS_COMPILERFEATURES_SUPPORT_NOEXCEPT
        ASSERT(noexcept(bsls::Util::forward<int&>(lvalue)));       // Concern 4
        ASSERT(noexcept(bsls::Util::forward<int>(rvalue)));
# endif

# ifdef BSLS_COMPILERFEATURES_SUPPORT_CONSTEXPR
        static constexpr int ce1 = 42;                             // Concern 5
        constexpr const int& ce1Result = bsls::Util::forward<const int&>(ce1);
        (void) ce1Result;
# endif

#endif
      } break;
      case 3: {
        // --------------------------------------------------------------------
        // TESTING MACRO BSLS_UTIL_ADDRESSOF
        //
        // Concerns:
        //: 1 The macro applies 'bsls::Util::addressOf' on Windows and
        //:   'operator&' on every other platform.
        //
        // Plan:
        //: 1 Create an object of type 'EvilType' (see GLOBAL
        //:   TYPEDEFS/CONSTANTS FOR TESTING AND VARIABLES) with an overloaded
        //:   'operator&' and verify that 'bsls::Util::addressOf' invokes
        //:   'operator&' on UNIX, and that on Windows it returns the address
        //:    of the created object instead. (C-1)
        //
        // Testing:
        //   BSLS_UTIL_ADDRESSOF macro
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING MACRO BSLS_UTIL_ADDRESSOF"
                            "\n=================================\n");

        EvilType mX; const EvilType& X = mX;

#ifndef BDE_USE_ADDRESSOF
        if (verbose)
            printf("\nTest that 'bsls::Util::addressOf' returns 'bogusPtr'\n");
        ASSERT(X.bogusPtr() == BSLS_UTIL_ADDRESSOF(X));
#else
        if (verbose)
             printf("\nTest that 'bsls::Util::addressOf' returns '&X'\n");
        ASSERT(X.realAddress() == BSLS_UTIL_ADDRESSOF(X));
#endif

      } break;
      case 2: {
        // --------------------------------------------------------------------
        // TESTING 'addressOf'
        //
        // Concerns:
        //: 1 Calling 'bsls::Util::addressOf' on an object will return the
        //:   address of the object whether or not the object's class has an
        //:   overloaded 'operator&'.
        //:
        //: 2 The returned pointer has the same cv-qualification as the
        //:   argument.
        //:
        //: 3 The result of calling addressof on a reference has the same
        //:   effect as on an (lvalue) object.
        //
        // Plan:
        //: 1 Create a number of objects of types 'int' and 'EvilType', where
        //:   'EvilType' has an overloaded 'operator&'.  Test that the pointer
        //:   returned from calling 'addressOf' on each object points to that
        //:   object.  (In the case of 'EvilType', the 'realAddress' method
        //:   returns the true address of the object. (C-1, 3)
        //:
        //: 2 Using objects and references with all four different
        //:   cv-qualifications, verify that the pointer returned by
        //:   'addressOf' has the correct qualification (using the 'cvqOfPtr'
        //:   function). (C-2)
        //
        // Testing:
        //   TYPE *bsls::Util::addressOf(TYPE&);
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING 'addressOf'"
                            "\n===================\n");

        if (verbose) printf("\nTESTING addressof objects\n");

        if (veryVerbose) printf("\nTesting addressOf(int)\n");

        int                  i = 0;
        int const           ci = 0;
        int       volatile  vi = 0;
        int const volatile cvi = 0;

        ASSERT(&  i == bsls::Util::addressOf(  i));
        ASSERT(& ci == bsls::Util::addressOf( ci));
        ASSERT(& vi == bsls::Util::addressOf( vi));
        ASSERT(&cvi == bsls::Util::addressOf(cvi));

        ASSERT(CVQ_UNQUALIFIED    == cvqOfPtr(bsls::Util::addressOf(  i)));
        ASSERT(CVQ_CONST          == cvqOfPtr(bsls::Util::addressOf( ci)));
        ASSERT(CVQ_VOLATILE       == cvqOfPtr(bsls::Util::addressOf( vi)));
        ASSERT(CVQ_CONST_VOLATILE == cvqOfPtr(bsls::Util::addressOf(cvi)));

        if (veryVerbose) printf("\nTesting addressOf(EvilType)\n");

        EvilType                  x(0);
        EvilType const           cx(0);
        EvilType       volatile  vx(0);
        EvilType const volatile cvx(0);

        ASSERT(  x.realAddress() == bsls::Util::addressOf(  x));
        ASSERT( cx.realAddress() == bsls::Util::addressOf( cx));
        ASSERT( vx.realAddress() == bsls::Util::addressOf( vx));
        ASSERT(cvx.realAddress() == bsls::Util::addressOf(cvx));

        ASSERT(CVQ_UNQUALIFIED    == cvqOfPtr(bsls::Util::addressOf(  x)));
        ASSERT(CVQ_CONST          == cvqOfPtr(bsls::Util::addressOf( cx)));
        ASSERT(CVQ_VOLATILE       == cvqOfPtr(bsls::Util::addressOf( vx)));
        ASSERT(CVQ_CONST_VOLATILE == cvqOfPtr(bsls::Util::addressOf(cvx)));

        if (verbose) printf("\nTESTING addressof references\n");

        if (veryVerbose) printf("\nTesting addressOf(reference to int)\n");

        int               &   ri = i;
        int const         &  cri = i;
        int       volatile&  vri = i;
        int const volatile& cvri = i;

        ASSERT(&i == bsls::Util::addressOf(  ri));
        ASSERT(&i == bsls::Util::addressOf( cri));
        ASSERT(&i == bsls::Util::addressOf( vri));
        ASSERT(&i == bsls::Util::addressOf(cvri));

        ASSERT(CVQ_UNQUALIFIED    == cvqOfPtr(bsls::Util::addressOf(  ri)));
        ASSERT(CVQ_CONST          == cvqOfPtr(bsls::Util::addressOf( cri)));
        ASSERT(CVQ_VOLATILE       == cvqOfPtr(bsls::Util::addressOf( vri)));
        ASSERT(CVQ_CONST_VOLATILE == cvqOfPtr(bsls::Util::addressOf(cvri)));

        if (veryVerbose)
                        printf("\nTesting addressOf(reference to EvilType)\n");

        EvilType               &   rx = x;
        EvilType const         &  crx = x;
        EvilType       volatile&  vrx = x;
        EvilType const volatile& cvrx = x;

        ASSERT(x.realAddress() == bsls::Util::addressOf(  rx));
        ASSERT(x.realAddress() == bsls::Util::addressOf( crx));
        ASSERT(x.realAddress() == bsls::Util::addressOf( vrx));
        ASSERT(x.realAddress() == bsls::Util::addressOf(cvrx));

        ASSERT(CVQ_UNQUALIFIED    == cvqOfPtr(bsls::Util::addressOf(  rx)));
        ASSERT(CVQ_CONST          == cvqOfPtr(bsls::Util::addressOf( crx)));
        ASSERT(CVQ_VOLATILE       == cvqOfPtr(bsls::Util::addressOf( vrx)));
        ASSERT(CVQ_CONST_VOLATILE == cvqOfPtr(bsls::Util::addressOf(cvrx)));

        ASSERT(TestFuncs::a == bsls::Util::addressOf(TestFuncs::a));
        ASSERT(TestFuncs::b == bsls::Util::addressOf(TestFuncs::b));
        ASSERT(TestFuncs::c == bsls::Util::addressOf(TestFuncs::c));
      } break;
      case 1: {
        // --------------------------------------------------------------------
        // TESTING TEST APPARATUS
        //
        // Concerns:
        //: 1 That 'cvqOfPtr' returns the correct result for each
        //:   pointer-to-cv-qualified type.
        //:
        //: 2 That 'realAddress' returns the true address of a 'EvilType'
        //:   object.
        //:
        //: 3 That 'EvilType' overloads 'operator&' such that it returns
        //:   something other than the address of the object.
        //
        // Test Plan:
        //: 1 Call 'cvqOfPtr' with pointers of each of the four different
        //:   cv-qualifications and verify the returned value. (C-1)
        //:
        //: 2 Construct a 'EvilType' object at a known address, by using an
        //:   array of sufficient 'char's.  Initialize a reference of each
        //:   cv-qualification type referring to this object, and verify that
        //:   calling 'realAddress' returns the same address as the backing
        //:   array. (C-2)
        //:
        //: 3 Call 'operator&' on each reference above and verify that they
        //:   never return the same result as the 'realAddress' method. (C-3)
        //
        // Testing:
        //   CvQualification cvqOfPtr(T *p);
        //   EvilType *EvilType::operator&();
        //   EvilType *EvilType::realAddress();
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING TEST APPARATUS"
                            "\n======================\n");

        if (verbose) printf("\nTesting cvqOfPtr\n");

        int dummy = 7;

        void                *  p = &dummy;
        void const          * cp = &dummy;
        int        volatile * vp = &dummy;
        int  const volatile *cvp = &dummy;

        ASSERT(CVQ_UNQUALIFIED    == cvqOfPtr(  p));
        ASSERT(CVQ_CONST          == cvqOfPtr( cp));
        ASSERT(CVQ_VOLATILE       == cvqOfPtr( vp));
        ASSERT(CVQ_CONST_VOLATILE == cvqOfPtr(cvp));

        if (verbose) printf("\nTesting EvilType::realAddress()\n");

        char buffer[sizeof(EvilType)];
        void * const trueAddress = buffer;

        EvilType *pX = new(trueAddress)EvilType(0);

        EvilType               &   x  = *pX;
        EvilType const         &  cx  = *pX;
        EvilType       volatile&  vx  = *pX;
        EvilType const volatile& cvx  = *pX;

        ASSERT(trueAddress ==   x.realAddress());
        ASSERT(trueAddress ==  cx.realAddress());
        ASSERT(trueAddress ==  vx.realAddress());
        ASSERT(trueAddress == cvx.realAddress());

        if (verbose) printf("\nTesting operator&(EvilType)\n");

        ASSERT(&  x !=   x.realAddress());
        ASSERT(& cx !=  cx.realAddress());
        ASSERT(& vx !=  vx.realAddress());
        ASSERT(&cvx != cvx.realAddress());
      } break;
      default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }

    return testStatus;
}

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


text:
package org.apache.sling.testing.mock.sling.servlet;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Before;
import org.junit.Test;

public class MockRequestPathInfoTest {

    private MockRequestPathInfo requestPathInfo;

    @Before
    public void setUp() throws Exception {
        this.requestPathInfo = new MockRequestPathInfo();
    }

    @Test
    public void testExtension() {
        assertNull(this.requestPathInfo.getExtension());
        this.requestPathInfo.setExtension("ext");
        assertEquals("ext", this.requestPathInfo.getExtension());
    }

    @Test
    public void testResourcePath() {
        assertNull(this.requestPathInfo.getResourcePath());
        this.requestPathInfo.setResourcePath("/path");
        assertEquals("/path", this.requestPathInfo.getResourcePath());
    }

    @Test
    public void testSelector() {
        assertNull(this.requestPathInfo.getSelectorString());
        assertEquals(0, this.requestPathInfo.getSelectors().length);
        this.requestPathInfo.setSelectorString("aa.bb");
        assertEquals("aa.bb", this.requestPathInfo.getSelectorString());
        assertEquals(2, this.requestPathInfo.getSelectors().length);
        assertArrayEquals(new String[] { "aa", "bb" }, this.requestPathInfo.getSelectors());
    }

    @Test
    public void testSuffix() {
        assertNull(this.requestPathInfo.getSuffix());
        this.requestPathInfo.setSuffix("/suffix");
        assertEquals("/suffix", this.requestPathInfo.getSuffix());
    }

}


text:
<title> / linq.HelperFunctions.CastShortList</title>
<link rel="stylesheet" href="..\..\style.css">

linq / HelperFunctions / CastShortList

CastShortList

fun CastShortList(list: List<Any>): List<Short>

Casts a list of Object to a List of Short

Parameters

list - the List to cast

Return

A List of all the input objects that are Short


text:
/*
 * @test
 * @summary check strict method conversion allows loose method reference conversion
 * @compile MethodReference26.java
 */

class MethodReference26 {

    static void m(Integer i) { }

    interface SAM {
        void m(int x);
    }

    static void call(int i, SAM s) {   }
    static void call(Integer i, SAM s) {   }

    static void test() {
        call(1, MethodReference26::m); //ok
    }
}


text:
using System;
using System.Drawing;
using System.Windows.Forms;

using BizHawk.Client.Common;
using BizHawk.Emulation.Common;

//Just because this code was mostly rewritten, dont think it isnt still awful

namespace BizHawk.Client.EmuHawk
{
	public sealed class AnalogStickPanel : Panel
	{
		private int _x = 0;
		private int _y = 0;

		public int X
		{
			get
			{
				return _x;
			}

			set
			{
				if (value < MinX) { _x = MinX; }
				else if (value > MaxX) { _x = MaxX; }
				else { _x = value; }
				SetAnalog();
			}
		}

		public int Y
		{
			get
			{
				return _y;
			}

			set
			{
				if (value < MinY) { _y = MinY; }
				else if (value > MaxY) { _y = MaxY; }
				else { _y = value; }
				SetAnalog();
			}
		}

		public bool HasValue = false;
		public bool ReadOnly { get; set; }

		public string XName = "";
		public string YName = "";

		private IController _previous = null;

		float UserRangePercentageX = 100, UserRangePercentageY = 100;

		public void SetUserRange(float rx, float ry)
		{
			UserRangePercentageX = rx;
			UserRangePercentageY = ry;
			Rerange();
			Refresh();
		}

		public void SetRangeX(float[] range)
		{
			for (int i = 0; i < 3; i++) ActualRangeX[i] = range[i];
			Rerange();
		}

		public void SetRangeY(float[] range)
		{
			for (int i = 0; i < 3; i++) ActualRangeY[i] = range[i];
			Rerange();
		}

		public float[] RangeX = new float[] { -128f, 0.0f, 127f };
		public float[] RangeY = new float[] { -128f, 0.0f, 127f };
		public float[] ActualRangeX = new float[] { -128f, 0.0f, 127f };
		public float[] ActualRangeY = new float[] { -128f, 0.0f, 127f };

		float flipx = 1, flipy = 1;

		void Rerange()
		{
			//baseline:
			//Array.Copy(ActualRangeX, RangeX, 3);
			//Array.Copy(ActualRangeY, RangeY, 3);

			float rx = ActualRangeX[2] - ActualRangeX[0];
			float ry = ActualRangeY[2] - ActualRangeY[0];
			float midx = rx / 2 + ActualRangeX[0];
			float midy = ry / 2 + ActualRangeY[0];
			rx *= UserRangePercentageX / 100;
			ry *= UserRangePercentageY / 100;
			float minx = midx - rx / 2;
			float maxx = minx + rx;
			float miny = midy - ry / 2;
			float maxy = miny + ry;

			if (minx > maxx)
			{
				float temp = minx;
				minx = maxx;
				maxx = temp;
				flipx = -1;
			}

			if (miny > maxy)
			{
				float temp = miny;
				miny = maxy;
				maxy = temp;
				flipy = -1;
			}

			//Range?[1] isn't really used
			RangeX[0] = minx;
			RangeX[2] = maxx;
			RangeY[0] = miny;
			RangeY[2] = maxy;

			Clamp();
		}

		//dont count on this working. it's never been tested.
		//but it kind of must be, or else nothing here would work...
		public float ScaleX = 0.60f;
		public float ScaleY = 0.60f;

		int MinX { get { return (int)(RangeX[0]); } }
		int MinY { get { return (int)(RangeY[0]); } }
		int MaxX { get { return (int)(RangeX[2]); } }
		int MaxY { get { return (int)(RangeY[2]); } }
		int RangeSizeX { get { return (int)(MaxX - MinX + 1); } }
		int RangeSizeY { get { return (int)(MaxY - MinY + 1); } }

		int PixelSizeX { get { return (int)(RangeSizeX * ScaleX); } }
		int PixelSizeY { get { return (int)(RangeSizeY * ScaleY); } }
		int PixelMinX { get { return (Size.Width - PixelSizeX) / 2; } }
		int PixelMinY { get { return (Size.Height - PixelSizeY) / 2; } }
		int PixelMidX { get { return PixelMinX + PixelSizeX / 2; } }
		int PixelMidY { get { return PixelMinY + PixelSizeY / 2; } }
		int PixelMaxX { get { return PixelMinX + PixelSizeX - 1; } }
		int PixelMaxY { get { return PixelMinY + PixelSizeY - 1; } }

		private int RealToGfxX(int val)
		{
			int v = val;
			if (flipx == -1)
				v = (MaxX - val) + MinX;
			v = (int)(((float)v - MinX) * ScaleX);
			v += PixelMinX;
			return v;
		}

		private int RealToGfxY(int val)
		{
			int v = val;
			if (flipy == -1)
				v = (MaxY - val) + MinY;
			v = (int)(((float)v - MinY) * ScaleY);
			v += PixelMinY;
			return v;
		}

		private int GfxToRealX(int val)
		{
			val -= PixelMinX;
			float v = ((float)val / ScaleX + MinX);
			if (v < MinX) v = MinX;
			if (v > MaxX) v = MaxX;
			if (flipx == -1)
				v = (MaxX - v) + MinX;
			return (int)v;
		}

		private int GfxToRealY(int val)
		{
			val -= PixelMinY;
			float v;
			v = ((float)val / ScaleY + MinY);
			if (v < MinX) v = MinX;
			if (v > MaxX) v = MaxX;
			if(flipy == -1)
				v = (MaxY - v) + MinY;
			return (int)v;
		}

		private readonly Brush WhiteBrush = Brushes.White;
		private readonly Brush GrayBrush = Brushes.LightGray;
		private readonly Brush RedBrush = Brushes.Red;
		private readonly Brush OffWhiteBrush = Brushes.Beige;

		private readonly Pen BlackPen = new Pen(Brushes.Black);
		private readonly Pen BluePen = new Pen(Brushes.Blue, 2);
		private readonly Pen GrayPen = new Pen(Brushes.Gray, 2);

		private readonly Bitmap Dot = new Bitmap(7, 7);
		private readonly Bitmap GrayDot = new Bitmap(7, 7);

		public Action ClearCallback { get; set; }

		private void DoClearCallback()
		{
			if (ClearCallback != null)
			{
				ClearCallback();
			}
		}

		public AnalogStickPanel()
		{
			Size = new Size(PixelSizeX + 1, PixelSizeY + 1);
			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.UserPaint, true);
			SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
			SetStyle(ControlStyles.SupportsTransparentBackColor, true);
			SetStyle(ControlStyles.Opaque, true);
			BackColor = Color.Gray;
			Paint += AnalogControlPanel_Paint;
			BorderStyle = BorderStyle.Fixed3D;

			// Draw the dot into a bitmap
			using (var g = Graphics.FromImage(Dot))
			{
				g.Clear(Color.Transparent);
				g.FillRectangle(RedBrush, 2, 0, 3, 7);
				g.FillRectangle(RedBrush, 1, 1, 5, 5);
				g.FillRectangle(RedBrush, 0, 2, 7, 3);
			}

			using (var gg = Graphics.FromImage(GrayDot))
			{
				gg.Clear(Color.Transparent);
				gg.FillRectangle(Brushes.Gray, 2, 0, 3, 7);
				gg.FillRectangle(Brushes.Gray, 1, 1, 5, 5);
				gg.FillRectangle(Brushes.Gray, 0, 2, 7, 3);
			}
		}

		private void SetAnalog()
		{
			var xn = HasValue ? X : (int?)null;
			var yn = HasValue ? Y : (int?)null;
			Global.StickyXORAdapter.SetFloat(XName, xn);
			Global.StickyXORAdapter.SetFloat(YName, yn);

			Refresh();
		}

		private void AnalogControlPanel_Paint(object sender, PaintEventArgs e)
		{
			unchecked
			{
				// Background
				e.Graphics.Clear(Color.LightGray);

				e.Graphics.FillRectangle(GrayBrush, PixelMinX, PixelMinY, PixelMaxX - PixelMinX, PixelMaxY- PixelMinY);
				e.Graphics.FillEllipse(ReadOnly ? OffWhiteBrush : WhiteBrush, PixelMinX, PixelMinY, PixelMaxX - PixelMinX - 2, PixelMaxY - PixelMinY - 3);
				e.Graphics.DrawEllipse(BlackPen, PixelMinX, PixelMinY, PixelMaxX - PixelMinX - 2, PixelMaxY - PixelMinY - 3);
				e.Graphics.DrawLine(BlackPen, PixelMidX, 0, PixelMidX, PixelMaxY);
				e.Graphics.DrawLine(BlackPen, 0, PixelMidY, PixelMaxX, PixelMidY);

				// Previous frame
				if (_previous != null)
				{
					var pX = (int)_previous.GetFloat(XName);
					var pY = (int)_previous.GetFloat(YName);
					e.Graphics.DrawLine(GrayPen, PixelMidX, PixelMidY, RealToGfxX(pX), RealToGfxY(pY));
					e.Graphics.DrawImage(GrayDot, RealToGfxX(pX) - 3, RealToGfxY(MaxY) - RealToGfxY(pY) - 3);
				}

				// Line
				if (HasValue)
				{
					e.Graphics.DrawLine(BluePen, PixelMidX, PixelMidY, RealToGfxX(X), RealToGfxY(Y));
					e.Graphics.DrawImage(ReadOnly ? GrayDot : Dot, RealToGfxX(X) - 3, RealToGfxY(Y) - 3);
				}
			}
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			if (!ReadOnly)
			{
				if (e.Button == MouseButtons.Left)
				{
					X = GfxToRealX(e.X);
					Y = GfxToRealY(e.Y);
					Clamp();
					HasValue = true;
					SetAnalog();
				}
				else if (e.Button == MouseButtons.Right)
				{
					Clear();
				}

				Refresh();
				base.OnMouseMove(e);
			}
		}

		protected override void OnMouseUp(MouseEventArgs e)
		{
			base.OnMouseUp(e);
			Capture = false;
		}

		protected override void WndProc(ref Message m)
		{
			if (m.Msg == 0x007B) // WM_CONTEXTMENU
			{
				// Don't let parent controls get this. We handle the right mouse button ourselves
				return;
			}

			base.WndProc(ref m);
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			if (!ReadOnly)
			{
				if (e.Button == MouseButtons.Left)
				{
					X = GfxToRealX(e.X);
					Y = GfxToRealY(e.Y);
					Clamp();
					HasValue = true;
				}
				if (e.Button == MouseButtons.Right)
				{
					Clear();
				}

				Refresh();
			}
		}

		public void Clear()
		{
			if (X != 0 || Y != 0 || HasValue)
			{
				X = Y = 0;
				HasValue = false;
				DoClearCallback();
				Refresh();
			}
		}

		public void Set(IController controller)
		{
			var newX = (int)controller.GetFloat(XName);
			var newY = (int)controller.GetFloat(YName);
			var changed = newX != X || newY != Y;
			if (changed)
			{
				SetPosition(newX, newY);
			}
		}

		public void SetPrevious(IController previous)
		{
			_previous = previous;
		}

		public void SetPosition(int xval, int yval)
		{
			X = xval;
			Y = yval;
			Clamp();
			HasValue = true;

			Refresh();
		}

		private void Clamp()
		{
			if (X > MaxX)
			{
				X = MaxX;
			}
			else if (X < MinX)
			{
				X = MinX;
			}

			if (Y > MaxY)
			{
				Y = MaxY;
			}
			else if (Y < MinY)
			{
				Y = MinY;
			}
		}
	}
}


text:
package org.apache.sis.io.wkt;

import java.util.Locale;
import org.apache.sis.test.TestCase;
import org.apache.sis.util.StringBuilders;
import org.junit.Test;

import static org.apache.sis.test.Assert.*;

/**
 * Tests the {@link Symbols} class.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.1
 * @since   0.4
 * @module
 */
public final strictfp class SymbolsTest extends TestCase {
    /**
     * Tests the {@link Symbols#containsElement(CharSequence, String)} method.
     */
    @Test
    public void testContainsElement() {
        assertContainsAxis("At beginning of a line.",   true,                  "AXIS["Long", EAST]");
        assertContainsAxis("Embeded in GEOGCS.",        true,  "GEOGCS["WGS84", AXIS["Long", EAST]]");
        assertContainsAxis("Using different brackets.", true,  "GEOGCS["WGS84", AXIS ("Long", EAST)]");
        assertContainsAxis("Mixed cases.",              true,  "GEOGCS["WGS84", aXis["Long", EAST]]");
        assertContainsAxis("AXIS in quoted text.",      false, "GEOGCS["AXIS"]");
        assertContainsAxis("Without opening bracket.",  false, "GEOGCS["WGS84", AXIS]");
        assertContainsAxis("No AXIS.",                  false, "GEOGCS["WGS84"]");
    }

    /**
     * Asserts that the call to {@code Symbols.containsElement(wkt, "AXIS")} produce the given result.
     * This method expects an array using the {@code "…"} quotation marks, which will be replaced by
     * the standard {@code '"'} quotation mark after we tested the given string.
     */
    private static void assertContainsAxis(final String message, final boolean expected, final String wkt) {
        assertEquals(message, expected, Symbols.getDefault().containsElement(wkt, "AXIS"));
        final StringBuilder buffer = new StringBuilder(wkt);
        StringBuilders.replace(buffer, '"', '"');
        StringBuilders.replace(buffer, '"', '"');
        assertFalse(wkt.contentEquals(buffer));
        assertEquals(message, expected, Symbols.getDefault().containsElement(buffer, "AXIS"));
    }

    /**
     * Ensures that the static constants are immutable.
     */
    @Test
    public void testImmutability() {
        try {
            Symbols.SQUARE_BRACKETS.setPairedBrackets("()", "[]");
            fail("Constant shall be immutable.");
        } catch (UnsupportedOperationException e) {
            // This is the expected exception.
            final String message = e.getMessage();
            assertTrue(message, message.contains("Symbols"));
        }
        try {
            Symbols.CURLY_BRACKETS.setLocale(Locale.FRENCH);
            fail("Constant shall be immutable.");
        } catch (UnsupportedOperationException e) {
            // This is the expected exception.
            final String message = e.getMessage();
            assertTrue(message, message.contains("Symbols"));
        }
    }

    /**
     * Tests {@link Symbols} serialization.
     */
    @Test
    public void testSerialization() {
        assertSame(Symbols.SQUARE_BRACKETS, assertSerializedEquals(Symbols.SQUARE_BRACKETS));
        assertSame(Symbols.CURLY_BRACKETS,  assertSerializedEquals(Symbols.CURLY_BRACKETS));
        /*
         * Test with a new instance using a closing quote symbol different than the opening one.
         * This is necessary in order to ensure that the symbol is recomputed correctly.
         */
        final Symbols symbols = new Symbols(Symbols.CURLY_BRACKETS);
        assertEquals("quote", "\"", symbols.getQuote());
        symbols.setPairedQuotes("""", "\"\"");
        assertEquals("quote", """, symbols.getQuote());
        final Symbols c = assertSerializedEquals(symbols);
        assertNotSame("Expected a new instance.", symbols, c);
        assertEquals("quote", """, c.getQuote());               // Verify the recomputed value.
    }
}


text:
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { hasPermission } from '../../app/authorization';
import { Users, Subscriptions, Messages } from '../../app/models';
import { settings } from '../../app/settings';
import { api } from '../sdk/api';
import { Team } from '../sdk';

Meteor.methods({
	addRoomModerator(rid, userId) {
		check(rid, String);
		check(userId, String);

		if (!Meteor.userId()) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', {
				method: 'addRoomModerator',
			});
		}

		if (!hasPermission(Meteor.userId(), 'set-moderator', rid)) {
			throw new Meteor.Error('error-not-allowed', 'Not allowed', {
				method: 'addRoomModerator',
			});
		}

		const user = Users.findOneById(userId);

		if (!user || !user.username) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', {
				method: 'addRoomModerator',
			});
		}

		const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id);

		if (!subscription) {
			throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
				method: 'addRoomModerator',
			});
		}

		if (Array.isArray(subscription.roles) === true && subscription.roles.includes('moderator') === true) {
			throw new Meteor.Error('error-user-already-moderator', 'User is already a moderator', {
				method: 'addRoomModerator',
			});
		}

		Subscriptions.addRoleById(subscription._id, 'moderator');

		const fromUser = Users.findOneById(Meteor.userId());

		Messages.createSubscriptionRoleAddedWithRoomIdAndUser(rid, user, {
			u: {
				_id: fromUser._id,
				username: fromUser.username,
			},
			role: 'moderator',
		});

		const team = Promise.await(Team.getOneByMainRoomId(rid));
		if (team) {
			Promise.await(Team.addRolesToMember(team._id, userId, ['moderator']));
		}

		if (settings.get('UI_DisplayRoles')) {
			api.broadcast('user.roleUpdate', {
				type: 'added',
				_id: 'moderator',
				u: {
					_id: user._id,
					username: user.username,
					name: fromUser.name,
				},
				scope: rid,
			});
		}

		return true;
	},
});


text:
CREATE TABLE PERSON (
  ID BIGINT AUTO_INCREMENT PRIMARY KEY,
  LAST_NAME VARCHAR(30),
  FIRST_NAME VARCHAR(30)
);


text:
package com.tikinou.schedulesdirect.core.domain.program;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Sebastien Astie.
 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class EpisodeMetadata {
    @JsonProperty("seriesid")
    private String seriesId;
    private Integer season;
    private Integer episode;
    private String url;

    public String getSeriesId() {
        return seriesId;
    }

    public void setSeriesId(String seriesId) {
        this.seriesId = seriesId;
    }

    public Integer getSeason() {
        return season;
    }

    public void setSeason(Integer season) {
        this.season = season;
    }

    public Integer getEpisode() {
        return episode;
    }

    public void setEpisode(Integer episode) {
        this.episode = episode;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "EpisodeMetadata{" +
                "seriesId='" + seriesId + '\'' +
                ", season=" + season +
                ", episode=" + episode +
                ", url='" + url + '\'' +
                '}';
    }

}


text:
.include <bsd.own.mk>
.include "${.CURDIR}/../Makefile.inc"

.PATH: ${IDIST}/html

.if ${MKDOC} != "no"
NTP_DOCFILES= \
		accopt.html \
		assoc.html \
		audio.html \
		authopt.html \
		bugs.html \
		build.html \
		clockopt.html \
		comdex.html \
		config.html \
		confopt.html \
		copyright.html \
		debug.html \
		decode.html \
		drivers/driver1.html \
		drivers/driver3.html \
		drivers/driver4.html \
		drivers/driver5.html \
		drivers/driver6.html \
		drivers/driver7.html \
		drivers/driver8.html \
		drivers/driver9.html \
		drivers/driver10.html \
		drivers/driver11.html \
		drivers/driver12.html \
		drivers/driver16.html \
		drivers/driver18.html \
		drivers/driver19.html \
		drivers/driver20.html \
		drivers/driver22.html \
		drivers/driver26.html \
		drivers/driver27.html \
		drivers/driver28.html \
		drivers/driver29.html \
		drivers/driver30.html \
		drivers/driver31.html \
		drivers/driver32.html \
		drivers/driver33.html \
		drivers/driver34.html \
		drivers/driver35.html \
		drivers/driver36.html \
		drivers/driver37.html \
		drivers/driver38.html \
		drivers/driver39.html \
		drivers/driver40.html \
		drivers/driver42.html \
		drivers/driver43.html \
		drivers/driver44.html \
		drivers/mx4200data.html \
		drivers/oncore-shmem.html \
		drivers/scripts/footer.txt \
		drivers/scripts/style.css \
		drivers/tf582_4.html \
		extern.html \
		hints.html \
		howto.html \
		index.html \
		kern.html \
		kernpps.html \
		keygen.html \
		miscopt.html \
		monopt.html \
		msyslog.html \
		ntp_conf.html \
		ntpd.html \
		ntpdate.html \
		ntpdc.html \
		ntpdsim.html \
		ntpdsim_new.html \
		ntpq.html \
		ntptime.html \
		ntptrace.html \
		parsedata.html \
		parsenew.html \
		pps.html \
		prefer.html \
		quick.html \
		rate.html \
		rdebug.html \
		refclock.html \
		release.html \
		scripts/accopt.txt \
		scripts/audio.txt \
		scripts/authopt.txt \
		scripts/clockopt.txt \
		scripts/command.txt \
		scripts/config.txt \
		scripts/confopt.txt \
		scripts/external.txt \
		scripts/footer.txt \
		scripts/install.txt \
		scripts/manual.txt \
		scripts/misc.txt \
		scripts/miscopt.txt \
		scripts/monopt.txt \
		scripts/refclock.txt \
		scripts/style.css \
		sitemap.html \
		sntp.html \
		tickadj.html \
		xleave.html

.for F in ${NTP_DOCFILES:O:u}
_FDIR:=		ntp/${F:H}				# subdir
_FDIR:=		${_FDIR:S,/.$,,}			# remove trivial directory
_FNAME:=	${F:T}					# name override
_F:=		${DESTDIR}${NTP_HTMLDIR}/${_FDIR}/${_FNAME}		# installed path
_FILE:=		${F}

.if ${MKUPDATE} == "no"
${_F}!		${_FILE} __fileinstall			# install rule
.if !defined(BUILD) && !make(all) && !make(${_FILE})
${_F}!		.MADE					# no build at install
.endif
.else
${_F}:		${_FILE} __fileinstall			# install rule
.if !defined(BUILD) && !make(all) && !make(${_FILE})
${_F}:		.MADE					# no build at install
.endif
.endif

filesinstall::	${_F}
.PRECIOUS: 	${_F}					# keep if install fails
.endfor

.endif

.include <bsd.prog.mk>


text:
package org.omg.DynamicAny;

/**
* org/omg/DynamicAny/DynArray.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u91/7017/corba/src/share/classes/org/omg/DynamicAny/DynamicAny.idl
* Friday, May 20, 2016 5:44:10 PM PDT
*/

/**
    * DynArray objects support the manipulation of IDL arrays.
    * Note that the dimension of the array is contained in the TypeCode which is accessible
    * through the type attribute. It can also be obtained by calling the component_count operation.
    */
public interface DynArray extends DynArrayOperations, org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity
{
} // interface DynArray


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Proxy
{
    public class ProcessException
    {
        private static Logger log = new Logger();
        public static void Process(Exception e)
        {
            //MessageBox.Show(e.ToString());
            log.Error(e.ToString());
        }

        public static void Process(string Message)
        {
            //MessageBox.Show(Message);
            log.Error(Message);
        }
    }
}


text:
/**
 */
package org.mobadsl.semantic.model.moba;

/**
 *
 * A representation of the model object 'Data'.
 *
 *
 *
 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaData()
 * @model abstract="true"
 * @generated
 */
public interface MobaData extends MobaApplicationFeature {
} // MobaData


text:
module Test.Sandbox.Compose (
  module Test.Sandbox.Compose.Type
, setupServices
, runServices
, runService
, killServices
, killService
, runServer
  )
where

import Test.Sandbox.Compose.Type
import Test.Sandbox.Compose.Core
import Test.Sandbox.Compose.Server


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2017 Carl-Philipp Harmant

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 -->

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="fr.cph.stock.repository.CurrencyData">
	<insert id="insertOneCurrencyData" parameterType="CurrencyData">
		insert into currency (id, currency1, currency2, value)
		values (0, #{currency1}, #{currency2},
		#{value})
	</insert>
	<select id="selectOneCurrencyData" parameterType="String" resultType="CurrencyData">
		select * from currency where id = #{id}
	</select>
	<update id="updateOneCurrencyData" parameterType="CurrencyData">
		update currency set value = #{value}, lastUpdate = NOW() where id = #{id};
	</update>
	<delete id="deleteOneCurrencyData" parameterType="CurrencyData">
		delete from currency where id = #{id}
	</delete>
	<select id="selectListCurrencyData" parameterType="String" resultType="CurrencyData">
		select * from currency where currency2 = #{id}
	</select>
	<select id="selectListAllCurrencyData" resultType="CurrencyData">
		select id, currency1, currency2, value, lastUpdate from currency
	</select>
	<select id="selectOneCurrencyDataWithParam" parameterType="CurrencyData" resultType="CurrencyData">
		select * from currency where currency1 = #{currency1} and currency2 = #{currency2}
	</select>
</mapper>


text:
#import "ABI43_0_0RCTWrapperExampleViewController.h"

#import <ABI43_0_0RCTWrapper/ABI43_0_0RCTWrapper.h>

#import "ABI43_0_0RCTWrapperExampleView.h"

@implementation ABI43_0_0RCTWrapperExampleViewController

- (void)loadView {
  self.view = [ABI43_0_0RCTWrapperExampleView new];
}

@end

ABI43_0_0RCT_WRAPPER_FOR_VIEW_CONTROLLER(ABI43_0_0RCTWrapperExampleViewController)


text:
CREATE TABLE currentconfiguration (
    root JSON NOT NULL,
    metadata JSON NOT NULL,
    createdAt TIMESTAMP NOT NULL,
    id varchar(1024) NOT NULL
);

CREATE TABLE configurationmetadata (
    metadata JSON NOT NULL,
    createdAt TIMESTAMP NOT NULL,
    id varchar(1024) PRIMARY KEY
);

CREATE TABLE futureconfigurationmetadata (
    metadata JSON NOT NULL,
    createdAt TIMESTAMP NOT NULL,
    id varchar(1024) PRIMARY KEY
);

CREATE TABLE configuration (
    root JSON NOT NULL,
    metadata JSON NOT NULL,
    createdAt TIMESTAMP NOT NULL,
    id varchar(1024) PRIMARY KEY
);

CREATE TABLE futureconfiguration (
    root JSON NOT NULL,
    metadata JSON NOT NULL,
    createdAt TIMESTAMP NOT NULL,
    id varchar(1024) PRIMARY KEY
);

CREATE INDEX ix_configuration_createdat on configuration (createdAt);

CREATE INDEX ix_futureconfiguration_createdat on futureconfiguration (createdAt);


text:
<?php

/**
 * XForm
 * @author jan.kristinus[at]redaxo[dot]org Jan Kristinus
 * @author www.yakamara.de
 */

class rex_xform_remembervalues extends rex_xform_abstract
{

    function postValidateAction()
    {
        if ($this->params['send'] == 0) {
            $fields = explode(',', $this->getElement(3));
            $cookiename = $this->getName();
            if ($cookiename == '') {
                $cookiename = 'dummyremembercookie';
            }
            if (isset($_COOKIE[$cookiename])) {
                $fields = unserialize(base64_decode($_COOKIE[$cookiename]));
            } else {
                $fields = array();
            }
            if (is_array($fields)) {
                foreach ($this->obj as $o) {
                    if (array_key_exists($o->getName(), $fields)) {
                        $o->setValue($fields[$o->getName()]);
                        $this->setValue(1); // checked = ' checked="checked"';
                    }
                }
            }
        }

    }

    function enterObject()
    {
        $this->params['form_output'][$this->getId()] = $this->parse('value.checkbox.tpl.php');
    }

    function postFormAction()
    {
        if ($this->params['send'] == 1) {
            $c = array();
            if ($this->getValue() == 1) {
                $fields = explode(',', $this->getElement(3));
                foreach ($this->obj as $o) {
                    if (in_array($o->getName(), $fields)) {
                        $c[$o->getName()] = $o->getValue();
                    }
                }
            }
            $c = base64_encode(serialize($c));
            $cookiename = $this->getName();
            if ($cookiename == '') {
                $cookiename = 'dummyremembercookie';
            }
            $lastfor = (int) $this->getElement(5);
            if ($lastfor < 3600) {
                $lastfor = 4 * 7 * 24 * 60 * 60;
            } // if < 1 hour -> one month
            setcookie($cookiename, $c , time() + $lastfor, '/');
        }
    }

    function getDescription()
    {
        return 'remembervalues -> Beispiel: remembervalues|name|label|label1,label2,label3,label4|opt:default:1/0|opt:dauerinsekunden';
    }

}


text:
import kr.projectn.vdl.util.ExceptionCollector;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.junit.Test;

public class loggerTest {
    @Test
    public void loggerTest1() {
        Logger logger = LogManager.getRootLogger();
        logger.info("Info log test");
        logger.debug("Debug log test");
        logger.warn("Warn log test");
        /*logger.error("Error log test");
        ExceptionCollector.collect(new TestException());
        ExceptionCollector.collect("test");*/
    }

    private class TestException extends Exception {
        @Override
        public String getMessage() {
            return "Test exception.";
        }
    }
}


text:
package com.intellij.lang.properties.psi.impl;

import com.intellij.lang.ASTFactory;
import com.intellij.lang.properties.parsing.PropertiesTokenTypes;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IFileElementType;
import org.jetbrains.annotations.Nullable;

/**
 * @author cdr
 */
public class PropertiesASTFactory extends ASTFactory {
  @Nullable
  public CompositeElement createComposite(final IElementType type) {
    if (type instanceof IFileElementType) {
      return new FileElement(type, null);
    }
    return new CompositeElement(type);
  }

  @Nullable
  public LeafElement createLeaf(final IElementType type, CharSequence text) {
    if (type == PropertiesTokenTypes.VALUE_CHARACTERS) {
      return new PropertyValueImpl(type, text);
    }

    if (type == PropertiesTokenTypes.END_OF_LINE_COMMENT) {
      return new PsiCommentImpl(type, text);
    }

    return new LeafPsiElement(type, text);
  }
}


text:
$(window).resize(function(){
	if ($("body").css("padding") == "10px" ){
		// your code here
		$("#skin-select #toggle.active").css({"display":"none"});

	}
});


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Golden_landing</title>
	<link href='https://fonts.googleapis.com/css?family=Montserrat|Droid+Serif:400,400italic|Roboto+Slab:400,300' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="css/base.css">
	<link rel="stylesheet" href="css/partners.css">


text:
namespace cresper {

#define MAKE_BULK_STRING(stringToEncode)                      \
  (BULK_STRING_PREFIX                                         \
    + std::to_string(stringToEncode->ToString()->Utf8Length())\
    + CRLF                                                    \
    + string(*Nan::Utf8String(stringToEncode)) + CRLF)

#define MAKE_BUFFER(string)                                   \
  (Nan::CopyBuffer((string).c_str(), (string).length()))

#define RETURN_STRING_BUFFER(info, strResult)                 \
  std::string str = strResult;                                \
  info.GetReturnValue()                                       \
    .Set(Nan::CopyBuffer(str.c_str(), str.length())           \
    .ToLocalChecked());

#define CHECK_ARG(isInvalid, info)                            \
  if (!isInvalid) {                                           \
    Nan::ThrowTypeError(info);                                \
    return;                                                   \
  }

extern const std::string CRLF;
extern const std::string STRING_PREFIX;
extern const std::string INT_PREFIX;
extern const std::string ERROR_PREFIX;
extern const std::string BULK_STRING_PREFIX;
extern const std::string ARRAY_PREFIX;

class Cresper : public Nan::ObjectWrap {
public:
  static void Init (v8::Local<v8::Object>);

private:
  ~Cresper() = default;

  static inline Nan::Persistent<v8::Function>& constructor () {
    static Nan::Persistent<v8::Function> crepser_contructor;
    return crepser_contructor;
  };
  static void New (const Nan::FunctionCallbackInfo<v8::Value>& info);

  // Encoding functions
  static NAN_METHOD(encodeString);
  static NAN_METHOD(encodeError);
  static NAN_METHOD(encodeInt);
  static NAN_METHOD(encodeBulkString);
  static NAN_METHOD(encodeNull);
  static NAN_METHOD(encodeNullArray);
  static NAN_METHOD(encodeArray);
  static NAN_METHOD(encodeRequestArray);

  // Decoding functions
  static NAN_METHOD(decode);
};

}

#endif // !__CRSPER_H__


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef NET_UDP_UDP_SOCKET_LIBEVENT_H_
#define NET_UDP_UDP_SOCKET_LIBEVENT_H_

#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/threading/non_thread_safe.h"
#include "net/base/completion_callback.h"
#include "net/base/net_export.h"
#include "net/base/rand_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_log.h"
#include "net/udp/datagram_socket.h"

namespace net {

class NET_EXPORT UDPSocketLibevent : public base::NonThreadSafe {
 public:
  UDPSocketLibevent(DatagramSocket::BindType bind_type,
                    const RandIntCallback& rand_int_cb,
                    net::NetLog* net_log,
                    const net::NetLog::Source& source);
  virtual ~UDPSocketLibevent();

  // Connect the socket to connect with a certain |address|.
  // Returns a net error code.
  int Connect(const IPEndPoint& address);

  // Bind the address/port for this socket to |address|.  This is generally
  // only used on a server.
  // Returns a net error code.
  int Bind(const IPEndPoint& address);

  // Close the socket.
  void Close();

  // Copy the remote udp address into |address| and return a network error code.
  int GetPeerAddress(IPEndPoint* address) const;

  // Copy the local udp address into |address| and return a network error code.
  // (similar to getsockname)
  int GetLocalAddress(IPEndPoint* address) const;

  // IO:
  // Multiple outstanding read requests are not supported.
  // Full duplex mode (reading and writing at the same time) is supported

  // Read from the socket.
  // Only usable from the client-side of a UDP socket, after the socket
  // has been connected.
  int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);

  // Write to the socket.
  // Only usable from the client-side of a UDP socket, after the socket
  // has been connected.
  int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);

  // Read from a socket and receive sender address information.
  // |buf| is the buffer to read data into.
  // |buf_len| is the maximum amount of data to read.
  // |address| is a buffer provided by the caller for receiving the sender
  //   address information about the received data.  This buffer must be kept
  //   alive by the caller until the callback is placed.
  // |address_length| is a ptr to the length of the |address| buffer.  This
  //   is an input parameter containing the maximum size |address| can hold
  //   and also an output parameter for the size of |address| upon completion.
  // |callback| the callback on completion of the Recv.
  // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
  // If ERR_IO_PENDING is returned, the caller must keep |buf|, |address|,
  // and |address_length| alive until the callback is called.
  int RecvFrom(IOBuffer* buf,
               int buf_len,
               IPEndPoint* address,
               const CompletionCallback& callback);

  // Send to a socket with a particular destination.
  // |buf| is the buffer to send
  // |buf_len| is the number of bytes to send
  // |address| is the recipient address.
  // |address_length| is the size of the recipient address
  // |callback| is the user callback function to call on complete.
  // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
  // If ERR_IO_PENDING is returned, the caller must keep |buf| and |address|
  // alive until the callback is called.
  int SendTo(IOBuffer* buf,
             int buf_len,
             const IPEndPoint& address,
             const CompletionCallback& callback);

  // Set the receive buffer size (in bytes) for the socket.
  bool SetReceiveBufferSize(int32 size);

  // Set the send buffer size (in bytes) for the socket.
  bool SetSendBufferSize(int32 size);

  // Returns true if the socket is already connected or bound.
  bool is_connected() const { return socket_ != kInvalidSocket; }

  const BoundNetLog& NetLog() const { return net_log_; }

  // Sets corresponding flags in |socket_options_| to allow the socket
  // to share the local address to which the socket will be bound with
  // other processes. Should be called before Bind().
  void AllowAddressReuse();

  // Sets corresponding flags in |socket_options_| to allow sending
  // and receiving packets to and from broadcast addresses. Should be
  // called before Bind().
  void AllowBroadcast();

  // Join the multicast group.
  // |group_address| is the group address to join, could be either
  // an IPv4 or IPv6 address.
  // Return a network error code.
  int JoinGroup(const IPAddressNumber& group_address) const;

  // Leave the multicast group.
  // |group_address| is the group address to leave, could be either
  // an IPv4 or IPv6 address. If the socket hasn't joined the group,
  // it will be ignored.
  // It's optional to leave the multicast group before destroying
  // the socket. It will be done by the OS.
  // Return a network error code.
  int LeaveGroup(const IPAddressNumber& group_address) const;

  // Set the time-to-live option for UDP packets sent to the multicast
  // group address. The default value of this option is 1.
  // Cannot be negative or more than 255.
  // Should be called before Bind().
  // Return a network error code.
  int SetMulticastTimeToLive(int time_to_live);

  // Set the loopback flag for UDP socket. If this flag is true, the host
  // will receive packets sent to the joined group from itself.
  // The default value of this option is true.
  // Should be called before Bind().
  // Return a network error code.
  //
  // Note: the behavior of |SetMulticastLoopbackMode| is slightly
  // different between Windows and Unix-like systems. The inconsistency only
  // happens when there are more than one applications on the same host
  // joined to the same multicast group while having different settings on
  // multicast loopback mode. On Windows, the applications with loopback off
  // will not RECEIVE the loopback packets; while on Unix-like systems, the
  // applications with loopback off will not SEND the loopback packets to
  // other applications on the same host. See MSDN: http://goo.gl/6vqbj
  int SetMulticastLoopbackMode(bool loopback);

 private:
  static const int kInvalidSocket = -1;

  enum SocketOptions {
    SOCKET_OPTION_REUSE_ADDRESS  = 1 << 0,
    SOCKET_OPTION_BROADCAST      = 1 << 1,
    SOCKET_OPTION_MULTICAST_LOOP = 1 << 2
  };

  class ReadWatcher : public MessageLoopForIO::Watcher {
   public:
    explicit ReadWatcher(UDPSocketLibevent* socket) : socket_(socket) {}

    // MessageLoopForIO::Watcher methods

    virtual void OnFileCanReadWithoutBlocking(int /* fd */) OVERRIDE;

    virtual void OnFileCanWriteWithoutBlocking(int /* fd */) OVERRIDE {}

   private:
    UDPSocketLibevent* const socket_;

    DISALLOW_COPY_AND_ASSIGN(ReadWatcher);
  };

  class WriteWatcher : public MessageLoopForIO::Watcher {
   public:
    explicit WriteWatcher(UDPSocketLibevent* socket) : socket_(socket) {}

    // MessageLoopForIO::Watcher methods

    virtual void OnFileCanReadWithoutBlocking(int /* fd */) OVERRIDE {}

    virtual void OnFileCanWriteWithoutBlocking(int /* fd */) OVERRIDE;

   private:
    UDPSocketLibevent* const socket_;

    DISALLOW_COPY_AND_ASSIGN(WriteWatcher);
  };

  void DoReadCallback(int rv);
  void DoWriteCallback(int rv);
  void DidCompleteRead();
  void DidCompleteWrite();

  // Handles stats and logging. |result| is the number of bytes transferred, on
  // success, or the net error code on failure. On success, LogRead takes in a
  // sockaddr and its length, which are mandatory, while LogWrite takes in an
  // optional IPEndPoint.
  void LogRead(int result, const char* bytes, socklen_t addr_len,
               const sockaddr* addr) const;
  void LogWrite(int result, const char* bytes, const IPEndPoint* address) const;

  // Returns the OS error code (or 0 on success).
  int CreateSocket(const IPEndPoint& address);

  // Same as SendTo(), except that address is passed by pointer
  // instead of by reference. It is called from Write() with |address|
  // set to NULL.
  int SendToOrWrite(IOBuffer* buf,
                    int buf_len,
                    const IPEndPoint* address,
                    const CompletionCallback& callback);

  int InternalConnect(const IPEndPoint& address);
  int InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address);
  int InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address);

  // Applies |socket_options_| to |socket_|. Should be called before
  // Bind().
  int SetSocketOptions();
  int DoBind(const IPEndPoint& address);
  int RandomBind(const IPEndPoint& address);

  int socket_;
  int addr_family_;

  // Bitwise-or'd combination of SocketOptions. Specifies the set of
  // options that should be applied to |socket_| before Bind().
  int socket_options_;

  // Multicast socket options cached for SetSocketOption.
  // Cannot be used after Bind().
  int multicast_time_to_live_;

  // How to do source port binding, used only when UDPSocket is part of
  // UDPClientSocket, since UDPServerSocket provides Bind.
  DatagramSocket::BindType bind_type_;

  // PRNG function for generating port numbers.
  RandIntCallback rand_int_cb_;

  // These are mutable since they're just cached copies to make
  // GetPeerAddress/GetLocalAddress smarter.
  mutable scoped_ptr<IPEndPoint> local_address_;
  mutable scoped_ptr<IPEndPoint> remote_address_;

  // The socket's libevent wrappers
  MessageLoopForIO::FileDescriptorWatcher read_socket_watcher_;
  MessageLoopForIO::FileDescriptorWatcher write_socket_watcher_;

  // The corresponding watchers for reads and writes.
  ReadWatcher read_watcher_;
  WriteWatcher write_watcher_;

  // The buffer used by InternalRead() to retry Read requests
  scoped_refptr<IOBuffer> read_buf_;
  int read_buf_len_;
  IPEndPoint* recv_from_address_;

  // The buffer used by InternalWrite() to retry Write requests
  scoped_refptr<IOBuffer> write_buf_;
  int write_buf_len_;
  scoped_ptr<IPEndPoint> send_to_address_;

  // External callback; called when read is complete.
  CompletionCallback read_callback_;

  // External callback; called when write is complete.
  CompletionCallback write_callback_;

  BoundNetLog net_log_;

  DISALLOW_COPY_AND_ASSIGN(UDPSocketLibevent);
};

}  // namespace net

#endif  // NET_UDP_UDP_SOCKET_LIBEVENT_H_