text:
#include "config.h"
#include "TiledBackingStore.h"

#if USE(TILED_BACKING_STORE)

#include "GraphicsContext.h"
#include "TiledBackingStoreClient.h"

namespace WebCore {

static const int defaultTileDimension = 512;

static IntPoint innerBottomRight(const IntRect& rect)
{
    // Actually, the rect does not contain rect.maxX(). Refer to IntRect::contain.
    return IntPoint(rect.maxX() - 1, rect.maxY() - 1);
}

TiledBackingStore::TiledBackingStore(TiledBackingStoreClient* client, PassOwnPtr<TiledBackingStoreBackend> backend)
    : m_client(client)
    , m_backend(backend)
    , m_tileBufferUpdateTimer(this, &TiledBackingStore::tileBufferUpdateTimerFired)
    , m_backingStoreUpdateTimer(this, &TiledBackingStore::backingStoreUpdateTimerFired)
    , m_tileSize(defaultTileDimension, defaultTileDimension)
    , m_coverAreaMultiplier(2.0f)
    , m_contentsScale(1.f)
    , m_pendingScale(0)
    , m_commitTileUpdatesOnIdleEventLoop(false)
    , m_contentsFrozen(false)
    , m_supportsAlpha(false)
    , m_pendingTileCreation(false)
{
}

TiledBackingStore::~TiledBackingStore()
{
}

void TiledBackingStore::setTileSize(const IntSize& size)
{
    m_tileSize = size;
    m_tiles.clear();
    startBackingStoreUpdateTimer();
}

void TiledBackingStore::setTrajectoryVector(const FloatPoint& trajectoryVector)
{
    m_pendingTrajectoryVector = trajectoryVector;
    m_pendingTrajectoryVector.normalize();
}

void TiledBackingStore::coverWithTilesIfNeeded()
{
    IntRect visibleRect = this->visibleRect();
    IntRect rect = mapFromContents(m_client->tiledBackingStoreContentsRect());

    bool didChange = m_trajectoryVector != m_pendingTrajectoryVector || m_visibleRect != visibleRect || m_rect != rect;
    if (didChange || m_pendingTileCreation)
        createTiles();
}

void TiledBackingStore::invalidate(const IntRect& contentsDirtyRect)
{
    IntRect dirtyRect(mapFromContents(contentsDirtyRect));
    IntRect keepRectFitToTileSize = tileRectForCoordinate(tileCoordinateForPoint(m_keepRect.location()));
    keepRectFitToTileSize.unite(tileRectForCoordinate(tileCoordinateForPoint(innerBottomRight(m_keepRect))));

    // Only iterate on the part of the rect that we know we might have tiles.
    IntRect coveredDirtyRect = intersection(dirtyRect, keepRectFitToTileSize);
    Tile::Coordinate topLeft = tileCoordinateForPoint(coveredDirtyRect.location());
    Tile::Coordinate bottomRight = tileCoordinateForPoint(innerBottomRight(coveredDirtyRect));

    for (int yCoordinate = topLeft.y(); yCoordinate <= bottomRight.y(); ++yCoordinate) {
        for (int xCoordinate = topLeft.x(); xCoordinate <= bottomRight.x(); ++xCoordinate) {
            RefPtr<Tile> currentTile = tileAt(Tile::Coordinate(xCoordinate, yCoordinate));
            if (!currentTile)
                continue;
            // Pass the full rect to each tile as coveredDirtyRect might not
            // contain them completely and we don't want partial tile redraws.
            currentTile->invalidate(dirtyRect);
        }
    }

    startTileBufferUpdateTimer();
}

void TiledBackingStore::updateTileBuffers()
{
    if (m_contentsFrozen)
        return;

    m_client->tiledBackingStorePaintBegin();

    Vector<IntRect> paintedArea;
    Vector<RefPtr<Tile> > dirtyTiles;
    TileMap::iterator end = m_tiles.end();
    for (TileMap::iterator it = m_tiles.begin(); it != end; ++it) {
        if (!it->value->isDirty())
            continue;
        dirtyTiles.append(it->value);
    }

    if (dirtyTiles.isEmpty()) {
        m_client->tiledBackingStorePaintEnd(paintedArea);
        return;
    }

    // FIXME: In single threaded case, tile back buffers could be updated asynchronously
    // one by one and then swapped to front in one go. This would minimize the time spent
    // blocking on tile updates.
    unsigned size = dirtyTiles.size();
    for (unsigned n = 0; n < size; ++n) {
        Vector<IntRect> paintedRects = dirtyTiles[n]->updateBackBuffer();
        paintedArea.appendVector(paintedRects);
        dirtyTiles[n]->swapBackBufferToFront();
    }

    m_client->tiledBackingStorePaintEnd(paintedArea);
}

void TiledBackingStore::paint(GraphicsContext* context, const IntRect& rect)
{
    context->save();

    // Assumes the backing store is painted with the scale transform applied.
    // Since tile content is already scaled, first revert the scaling from the painter.
    context->scale(FloatSize(1.f / m_contentsScale, 1.f / m_contentsScale));

    IntRect dirtyRect = mapFromContents(rect);

    Tile::Coordinate topLeft = tileCoordinateForPoint(dirtyRect.location());
    Tile::Coordinate bottomRight = tileCoordinateForPoint(innerBottomRight(dirtyRect));

    for (int yCoordinate = topLeft.y(); yCoordinate <= bottomRight.y(); ++yCoordinate) {
        for (int xCoordinate = topLeft.x(); xCoordinate <= bottomRight.x(); ++xCoordinate) {
            Tile::Coordinate currentCoordinate(xCoordinate, yCoordinate);
            RefPtr<Tile> currentTile = tileAt(currentCoordinate);
            if (currentTile && currentTile->isReadyToPaint())
                currentTile->paint(context, dirtyRect);
            else {
                IntRect tileRect = tileRectForCoordinate(currentCoordinate);
                IntRect target = intersection(tileRect, dirtyRect);
                if (target.isEmpty())
                    continue;
                m_backend->paintCheckerPattern(context, FloatRect(target));
            }
        }
    }
    context->restore();
}

IntRect TiledBackingStore::visibleRect() const
{
    return mapFromContents(m_client->tiledBackingStoreVisibleRect());
}

void TiledBackingStore::setContentsScale(float scale)
{
    if (m_pendingScale == m_contentsScale) {
        m_pendingScale = 0;
        return;
    }
    m_pendingScale = scale;
    if (m_contentsFrozen)
        return;
    commitScaleChange();
}

void TiledBackingStore::commitScaleChange()
{
    m_contentsScale = m_pendingScale;
    m_pendingScale = 0;
    m_tiles.clear();
    coverWithTilesIfNeeded();
}

double TiledBackingStore::tileDistance(const IntRect& viewport, const Tile::Coordinate& tileCoordinate) const
{
    if (viewport.intersects(tileRectForCoordinate(tileCoordinate)))
        return 0;

    IntPoint viewCenter = viewport.location() + IntSize(viewport.width() / 2, viewport.height() / 2);
    Tile::Coordinate centerCoordinate = tileCoordinateForPoint(viewCenter);

    return std::max(abs(centerCoordinate.y() - tileCoordinate.y()), abs(centerCoordinate.x() - tileCoordinate.x()));
}

// Returns a ratio between 0.0f and 1.0f of the surface of contentsRect covered by rendered tiles.
float TiledBackingStore::coverageRatio(const WebCore::IntRect& contentsRect) const
{
    IntRect dirtyRect = mapFromContents(contentsRect);
    float rectArea = dirtyRect.width() * dirtyRect.height();
    float coverArea = 0.0f;

    Tile::Coordinate topLeft = tileCoordinateForPoint(dirtyRect.location());
    Tile::Coordinate bottomRight = tileCoordinateForPoint(innerBottomRight(dirtyRect));

    for (int yCoordinate = topLeft.y(); yCoordinate <= bottomRight.y(); ++yCoordinate) {
        for (int xCoordinate = topLeft.x(); xCoordinate <= bottomRight.x(); ++xCoordinate) {
            Tile::Coordinate currentCoordinate(xCoordinate, yCoordinate);
            RefPtr<Tile> currentTile = tileAt(currentCoordinate);
            if (currentTile && currentTile->isReadyToPaint()) {
                IntRect coverRect = intersection(dirtyRect, currentTile->rect());
                coverArea += coverRect.width() * coverRect.height();
            }
        }
    }
    return coverArea / rectArea;
}

bool TiledBackingStore::visibleAreaIsCovered() const
{
    IntRect boundedVisibleContentsRect = intersection(m_client->tiledBackingStoreVisibleRect(), m_client->tiledBackingStoreContentsRect());
    return coverageRatio(boundedVisibleContentsRect) == 1.0f;
}

void TiledBackingStore::createTiles()
{
    // Guard here as as these can change before the timer fires.
    if (isBackingStoreUpdatesSuspended())
        return;

    // Update our backing store geometry.
    const IntRect previousRect = m_rect;
    m_rect = mapFromContents(m_client->tiledBackingStoreContentsRect());
    m_trajectoryVector = m_pendingTrajectoryVector;
    m_visibleRect = visibleRect();

    if (m_rect.isEmpty()) {
        setCoverRect(IntRect());
        setKeepRect(IntRect());
        return;
    }

    /* We must compute cover and keep rects using the visibleRect, instead of the rect intersecting the visibleRect with m_rect,
     * because TBS can be used as a backing store of GraphicsLayer and the visible rect usually does not intersect with m_rect.
     * In the below case, the intersecting rect is an empty.
     *
     *  +---------------+
     *  |               |
     *  |   m_rect      |
     *  |       +-------|-----------------------+
     *  |       | HERE  |  cover or keep        |
     *  +---------------+      rect             |
     *          |         +---------+           |
     *          |         | visible |           |
     *          |         |  rect   |           |
     *          |         +---------+           |
     *          |                               |
     *          |                               |
     *          +-------------------------------+
     *
     * We must create or keep the tiles in the HERE region.
     */

    IntRect coverRect;
    IntRect keepRect;
    computeCoverAndKeepRect(m_visibleRect, coverRect, keepRect);

    setCoverRect(coverRect);
    setKeepRect(keepRect);

    if (coverRect.isEmpty())
        return;

    // Resize tiles at the edge in case the contents size has changed, but only do so
    // after having dropped tiles outside the keep rect.
    bool didResizeTiles = false;
    if (previousRect != m_rect)
        didResizeTiles = resizeEdgeTiles();

    // Search for the tile position closest to the viewport center that does not yet contain a tile.
    // Which position is considered the closest depends on the tileDistance function.
    double shortestDistance = std::numeric_limits<double>::infinity();
    Vector<Tile::Coordinate> tilesToCreate;
    unsigned requiredTileCount = 0;

    // Cover areas (in tiles) with minimum distance from the visible rect. If the visible rect is
    // not covered already it will be covered first in one go, due to the distance being 0 for tiles
    // inside the visible rect.
    Tile::Coordinate topLeft = tileCoordinateForPoint(coverRect.location());
    Tile::Coordinate bottomRight = tileCoordinateForPoint(innerBottomRight(coverRect));
    for (int yCoordinate = topLeft.y(); yCoordinate <= bottomRight.y(); ++yCoordinate) {
        for (int xCoordinate = topLeft.x(); xCoordinate <= bottomRight.x(); ++xCoordinate) {
            Tile::Coordinate currentCoordinate(xCoordinate, yCoordinate);
            if (tileAt(currentCoordinate))
                continue;
            ++requiredTileCount;
            double distance = tileDistance(m_visibleRect, currentCoordinate);
            if (distance > shortestDistance)
                continue;
            if (distance < shortestDistance) {
                tilesToCreate.clear();
                shortestDistance = distance;
            }
            tilesToCreate.append(currentCoordinate);
        }
    }

    // Now construct the tile(s) within the shortest distance.
    unsigned tilesToCreateCount = tilesToCreate.size();
    for (unsigned n = 0; n < tilesToCreateCount; ++n) {
        Tile::Coordinate coordinate = tilesToCreate[n];
        setTile(coordinate, m_backend->createTile(this, coordinate));
    }
    requiredTileCount -= tilesToCreateCount;

    // Paint the content of the newly created tiles or resized tiles.
    if (tilesToCreateCount || didResizeTiles)
        updateTileBuffers();

    // Re-call createTiles on a timer to cover the visible area with the newest shortest distance.
    m_pendingTileCreation = requiredTileCount;
    if (m_pendingTileCreation) {
        if (!m_commitTileUpdatesOnIdleEventLoop) {
            m_client->tiledBackingStoreHasPendingTileCreation();
            return;
        }

        static const double tileCreationDelay = 0.01;
        startBackingStoreUpdateTimer(tileCreationDelay);
    }
}

void TiledBackingStore::adjustForContentsRect(IntRect& rect) const
{
    IntRect bounds = m_rect;
    IntSize candidateSize = rect.size();

    rect.intersect(bounds);

    if (rect.size() == candidateSize)
        return;

    /*
     * In the following case, there is no intersection of the contents rect and the cover rect.
     * Thus the latter should not be inflated.
     *
     *  +---------------+
     *  |   m_rect      |
     *  +---------------+
     *
     *          +-------------------------------+
     *          |          cover rect           |
     *          |         +---------+           |
     *          |         | visible |           |
     *          |         |  rect   |           |
     *          |         +---------+           |
     *          +-------------------------------+
     */
    if (rect.isEmpty())
        return;

    // Try to create a cover rect of the same size as the candidate, but within content bounds.
    int pixelsCovered = candidateSize.width() * candidateSize.height();

    if (rect.width() < candidateSize.width())
        rect.inflateY(((pixelsCovered / rect.width()) - rect.height()) / 2);
    if (rect.height() < candidateSize.height())
        rect.inflateX(((pixelsCovered / rect.height()) - rect.width()) / 2);

    rect.intersect(bounds);
}

void TiledBackingStore::computeCoverAndKeepRect(const IntRect& visibleRect, IntRect& coverRect, IntRect& keepRect) const
{
    coverRect = visibleRect;
    keepRect = visibleRect;

    // If we cover more that the actual viewport we can be smart about which tiles we choose to render.
    if (m_coverAreaMultiplier > 1) {
        // The initial cover area covers equally in each direction, according to the coverAreaMultiplier.
        coverRect.inflateX(visibleRect.width() * (m_coverAreaMultiplier - 1) / 2);
        coverRect.inflateY(visibleRect.height() * (m_coverAreaMultiplier - 1) / 2);
        keepRect = coverRect;

        if (m_trajectoryVector != FloatPoint::zero()) {
            // A null trajectory vector (no motion) means that tiles for the coverArea will be created.
            // A non-null trajectory vector will shrink the covered rect to visibleRect plus its expansion from its
            // center toward the cover area edges in the direction of the given vector.

            // E.g. if visibleRect == (10,10)5x5 and coverAreaMultiplier == 3.0:
            // a (0,0) trajectory vector will create tiles intersecting (5,5)15x15,
            // a (1,0) trajectory vector will create tiles intersecting (10,10)10x5,
            // and a (1,1) trajectory vector will create tiles intersecting (10,10)10x10.

            // Multiply the vector by the distance to the edge of the cover area.
            float trajectoryVectorMultiplier = (m_coverAreaMultiplier - 1) / 2;

            // Unite the visible rect with a "ghost" of the visible rect moved in the direction of the trajectory vector.
            coverRect = visibleRect;
            coverRect.move(coverRect.width() * m_trajectoryVector.x() * trajectoryVectorMultiplier,
                           coverRect.height() * m_trajectoryVector.y() * trajectoryVectorMultiplier);

            coverRect.unite(visibleRect);
        }
        ASSERT(keepRect.contains(coverRect));
    }

    adjustForContentsRect(coverRect);

    // The keep rect is an inflated version of the cover rect, inflated in tile dimensions.
    keepRect.unite(coverRect);
    keepRect.inflateX(m_tileSize.width() / 2);
    keepRect.inflateY(m_tileSize.height() / 2);
    keepRect.intersect(m_rect);

    ASSERT(coverRect.isEmpty() || keepRect.contains(coverRect));
}

bool TiledBackingStore::isBackingStoreUpdatesSuspended() const
{
    return m_contentsFrozen;
}

bool TiledBackingStore::isTileBufferUpdatesSuspended() const
{
    return m_contentsFrozen;
}

bool TiledBackingStore::resizeEdgeTiles()
{
    bool wasResized = false;
    Vector<Tile::Coordinate> tilesToRemove;
    TileMap::iterator end = m_tiles.end();
    for (TileMap::iterator it = m_tiles.begin(); it != end; ++it) {
        Tile::Coordinate tileCoordinate = it->value->coordinate();
        IntRect tileRect = it->value->rect();
        IntRect expectedTileRect = tileRectForCoordinate(tileCoordinate);
        if (expectedTileRect.isEmpty())
            tilesToRemove.append(tileCoordinate);
        else if (expectedTileRect != tileRect) {
            it->value->resize(expectedTileRect.size());
            wasResized = true;
        }
    }
    unsigned removeCount = tilesToRemove.size();
    for (unsigned n = 0; n < removeCount; ++n)
        removeTile(tilesToRemove[n]);
    return wasResized;
}

void TiledBackingStore::setKeepRect(const IntRect& keepRect)
{
    // Drop tiles outside the new keepRect.

    FloatRect keepRectF = keepRect;

    Vector<Tile::Coordinate> toRemove;
    TileMap::iterator end = m_tiles.end();
    for (TileMap::iterator it = m_tiles.begin(); it != end; ++it) {
        Tile::Coordinate coordinate = it->value->coordinate();
        FloatRect tileRect = it->value->rect();
        if (!tileRect.intersects(keepRectF))
            toRemove.append(coordinate);
    }
    unsigned removeCount = toRemove.size();
    for (unsigned n = 0; n < removeCount; ++n)
        removeTile(toRemove[n]);

    m_keepRect = keepRect;
}

void TiledBackingStore::removeAllNonVisibleTiles()
{
    IntRect boundedVisibleRect = mapFromContents(intersection(m_client->tiledBackingStoreVisibleRect(), m_client->tiledBackingStoreContentsRect()));
    setKeepRect(boundedVisibleRect);
}

PassRefPtr<Tile> TiledBackingStore::tileAt(const Tile::Coordinate& coordinate) const
{
    return m_tiles.get(coordinate);
}

void TiledBackingStore::setTile(const Tile::Coordinate& coordinate, PassRefPtr<Tile> tile)
{
    m_tiles.set(coordinate, tile);
}

void TiledBackingStore::removeTile(const Tile::Coordinate& coordinate)
{
    m_tiles.remove(coordinate);
}

IntRect TiledBackingStore::mapToContents(const IntRect& rect) const
{
    return enclosingIntRect(FloatRect(rect.x() / m_contentsScale,
        rect.y() / m_contentsScale,
        rect.width() / m_contentsScale,
        rect.height() / m_contentsScale));
}

IntRect TiledBackingStore::mapFromContents(const IntRect& rect) const
{
    return enclosingIntRect(FloatRect(rect.x() * m_contentsScale,
        rect.y() * m_contentsScale,
        rect.width() * m_contentsScale,
        rect.height() * m_contentsScale));
}

IntRect TiledBackingStore::tileRectForCoordinate(const Tile::Coordinate& coordinate) const
{
    IntRect rect(coordinate.x() * m_tileSize.width(),
                 coordinate.y() * m_tileSize.height(),
                 m_tileSize.width(),
                 m_tileSize.height());

    rect.intersect(m_rect);
    return rect;
}

Tile::Coordinate TiledBackingStore::tileCoordinateForPoint(const IntPoint& point) const
{
    int x = point.x() / m_tileSize.width();
    int y = point.y() / m_tileSize.height();
    return Tile::Coordinate(std::max(x, 0), std::max(y, 0));
}

void TiledBackingStore::startTileBufferUpdateTimer()
{
    if (!m_commitTileUpdatesOnIdleEventLoop)
        return;

    if (m_tileBufferUpdateTimer.isActive() || isTileBufferUpdatesSuspended())
        return;
    m_tileBufferUpdateTimer.startOneShot(0);
}

void TiledBackingStore::tileBufferUpdateTimerFired(Timer<TiledBackingStore>*)
{
    ASSERT(m_commitTileUpdatesOnIdleEventLoop);
    updateTileBuffers();
}

void TiledBackingStore::startBackingStoreUpdateTimer(double interval)
{
    if (!m_commitTileUpdatesOnIdleEventLoop)
        return;

    if (m_backingStoreUpdateTimer.isActive() || isBackingStoreUpdatesSuspended())
        return;
    m_backingStoreUpdateTimer.startOneShot(interval);
}

void TiledBackingStore::backingStoreUpdateTimerFired(Timer<TiledBackingStore>*)
{
    ASSERT(m_commitTileUpdatesOnIdleEventLoop);
    createTiles();
}

void TiledBackingStore::setContentsFrozen(bool freeze)
{
    if (m_contentsFrozen == freeze)
        return;

    m_contentsFrozen = freeze;

    // Restart the timers. There might be pending invalidations that
    // were not painted or created because tiles are not created or
    // painted when in frozen state.
    if (m_contentsFrozen)
        return;
    if (m_pendingScale)
        commitScaleChange();
    else {
        startBackingStoreUpdateTimer();
        startTileBufferUpdateTimer();
    }
}

void TiledBackingStore::setSupportsAlpha(bool a)
{
    if (a == m_supportsAlpha)
        return;
    m_supportsAlpha = a;
    invalidate(m_rect);
}

}

#endif


text: declare module 'chartjs-plugin-datalabels';

redpajama_set_name: RedPajamaGithub


text:
/*
http://www.cgsoso.com/forum-211-1.html

CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!

CGSOSO 主打游戏开发,影视设计等CG资源素材。

插件如若商用,请务必官网购买!

daily assets update for try.

U should buy the asset from home store if u use it in your project!
*/

#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)

using System;

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;

namespace Org.BouncyCastle.Crypto.Generators
{
    /**
     * a ElGamal key pair generator.
     *

     * This Generates keys consistent for use with ElGamal as described in
     * page 164 of "Handbook of Applied Cryptography".

     */
    public class ElGamalKeyPairGenerator
		: IAsymmetricCipherKeyPairGenerator
    {
        private ElGamalKeyGenerationParameters param;

        public void Init(
			KeyGenerationParameters parameters)
        {
            this.param = (ElGamalKeyGenerationParameters) parameters;
        }

        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
			DHKeyGeneratorHelper helper = DHKeyGeneratorHelper.Instance;
			ElGamalParameters egp = param.Parameters;
			DHParameters dhp = new DHParameters(egp.P, egp.G, null, 0, egp.L);

			BigInteger x = helper.CalculatePrivate(dhp, param.Random);
			BigInteger y = helper.CalculatePublic(dhp, x);

			return new AsymmetricCipherKeyPair(
                new ElGamalPublicKeyParameters(y, egp),
                new ElGamalPrivateKeyParameters(x, egp));
        }
    }

}

#endif


text:
#ifndef _SDL_config_iphoneos_h
#define _SDL_config_iphoneos_h

#include "SDL_platform.h"

#ifdef __LP64__
#define SIZEOF_VOIDP 8
#else
#define SIZEOF_VOIDP 4
#endif

#define HAVE_GCC_ATOMICS    1

#define HAVE_ALLOCA_H       1
#define HAVE_SYS_TYPES_H    1
#define HAVE_STDIO_H    1
#define STDC_HEADERS    1
#define HAVE_STRING_H   1
#define HAVE_INTTYPES_H 1
#define HAVE_STDINT_H   1
#define HAVE_CTYPE_H    1
#define HAVE_MATH_H 1
#define HAVE_SIGNAL_H   1

/* C library functions */
#define HAVE_MALLOC 1
#define HAVE_CALLOC 1
#define HAVE_REALLOC    1
#define HAVE_FREE   1
#define HAVE_ALLOCA 1
#define HAVE_GETENV 1
#define HAVE_SETENV 1
#define HAVE_PUTENV 1
#define HAVE_SETENV 1
#define HAVE_UNSETENV   1
#define HAVE_QSORT  1
#define HAVE_ABS    1
#define HAVE_BCOPY  1
#define HAVE_MEMSET 1
#define HAVE_MEMCPY 1
#define HAVE_MEMMOVE    1
#define HAVE_MEMCMP 1
#define HAVE_STRLEN 1
#define HAVE_STRLCPY    1
#define HAVE_STRLCAT    1
#define HAVE_STRDUP 1
#define HAVE_STRCHR 1
#define HAVE_STRRCHR    1
#define HAVE_STRSTR 1
#define HAVE_STRTOL 1
#define HAVE_STRTOUL    1
#define HAVE_STRTOLL    1
#define HAVE_STRTOULL   1
#define HAVE_STRTOD 1
#define HAVE_ATOI   1
#define HAVE_ATOF   1
#define HAVE_STRCMP 1
#define HAVE_STRNCMP    1
#define HAVE_STRCASECMP 1
#define HAVE_STRNCASECMP 1
#define HAVE_VSSCANF 1
#define HAVE_VSNPRINTF  1
#define HAVE_M_PI   1
#define HAVE_ATAN   1
#define HAVE_ATAN2  1
#define HAVE_CEIL   1
#define HAVE_COPYSIGN   1
#define HAVE_COS    1
#define HAVE_COSF   1
#define HAVE_FABS   1
#define HAVE_FLOOR  1
#define HAVE_LOG    1
#define HAVE_POW    1
#define HAVE_SCALBN 1
#define HAVE_SIN    1
#define HAVE_SINF   1
#define HAVE_SQRT   1
#define HAVE_SIGACTION  1
#define HAVE_SETJMP 1
#define HAVE_NANOSLEEP  1
#define HAVE_SYSCONF    1
#define HAVE_SYSCTLBYNAME 1

/* Paste generated code here */

/* Set max recognized G-force from accelerometer
   See src/joystick/uikit/SDLUIAccelerationDelegate.m for notes on why this is needed
 */
#define SDL_IPHONE_MAX_GFORCE 5.0

#endif /* _SDL_config_iphoneos_h */


text:
from PIL import Image
import argparse
import sys
import io

def bit_sequence_to_int(l):
    return sum(j<<i for i,j in enumerate(reversed(l)))

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Extracts palette from an image at stdin to raw binary on stdout.')
    parser.add_argument('-c', '--colors', default=256, type=int,  help='Number of colors to store.')
    parser.add_argument('-f', '--format', default='00rrrrrr00gggggg00bbbbbb', help='Bit format, defaults to 00rrrrrr00gggggg00bbbbbb for VGA')
    args = parser.parse_args()

    file = sys.stdout.buffer

    #Image.open needs seek(), but stdin can't do that, so we dump all the bytes
    #and re-create the stream from that
    image = Image.open(io.BytesIO(sys.stdin.buffer.read()))

    lut = image.palette.getdata()[1]
    for index in range(min(args.colors,len(lut)//3)):
        color = (lut[index*3],lut[index*3 + 1],lut[index*3 + 2])
        colorBit = [0x80,0x80,0x80]
        colorChar = {'r':0,'g':1,'b':2}
        bits = []
        for c in args.format:
            if c is '0':
                bits.append(0)
            elif c is '1':
                bits.append(1)
            else:
                i = colorChar[c]
                bits.append(1 if (color[i] & colorBit[i]) else 0)
                colorBit[i] >>= 1
        file.write(bytes(map(bit_sequence_to_int, chunker(bits,8))))


text:
/**
 * Horizontal sprites with nasty combination of repeats causing a fairly large
 * sprite height (lowest common multiply of heights of all repeated images).
 */

#h1 {
  background-repeat: repeat-y;
  background-image: url('../img/sprite-horizontal.png');
  background-position: -0px top;
}

#h2 {
  background-repeat: repeat-y;
  background-image: url('../img/sprite-horizontal.png');
  background-position: -17px top;
}

#h1 {
  background-repeat: repeat-x;
  background-image: url('../img/sprite-vertical.png');
  background-position: left -0px;
}

#h2 {
  background-repeat: repeat-x;
  background-image: url('../img/sprite-vertical.png');
  background-position: left -17px;
}


text:
package io.joynr.test.interlanguage;

import joynr.exceptions.ProviderRuntimeException;
import joynr.interlanguagetest.Enumeration;
import joynr.interlanguagetest.namedTypeCollection2.BaseStruct;
import joynr.interlanguagetest.namedTypeCollection2.ExtendedEnumerationWithPartlyDefinedValues;
import joynr.interlanguagetest.namedTypeCollection2.ExtendedExtendedBaseStruct;
import joynr.interlanguagetest.namedTypeCollection2.MapStringString;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.junit.Test;
import static org.junit.Assert.fail;

public class IltConsumerGetterSetterTest extends IltConsumerTest {
    private static final Logger LOG = LoggerFactory.getLogger(IltConsumerTest.class);

    /*
     * GETTER AND SETTER CALLS
     */

    @Test
    public void callGetAttributeUInt8() {
        LOG.info(name.getMethodName() + "");
        try {
            Byte result;

            // must set the value before it can be retrieved again
            byte byteArg = 127;
            testInterfaceProxy.setAttributeUInt8(byteArg);

            result = testInterfaceProxy.getAttributeUInt8();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (result != 127) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeUInt8() {
        LOG.info(name.getMethodName() + "");
        try {
            byte byteArg = 127;
            testInterfaceProxy.setAttributeUInt8(byteArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeDouble() {
        LOG.info(name.getMethodName() + "");
        try {
            Double result;

            // must set the value before it can be retrieved again
            double doubleArg = 1.1d;
            testInterfaceProxy.setAttributeDouble(doubleArg);

            result = testInterfaceProxy.getAttributeDouble();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (!IltUtil.cmpDouble(result, 1.1d)) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeDouble() {
        LOG.info(name.getMethodName() + "");
        try {
            double doubleArg = 1.1d;
            testInterfaceProxy.setAttributeDouble(doubleArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeBooleanReadOnly() {
        LOG.info(name.getMethodName() + "");
        try {
            Boolean result;
            // value is hardcoded on provider side since it is readonly
            result = testInterfaceProxy.getAttributeBooleanReadonly();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (result != true) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    // there is no setter for attributeBooleanReadOnly, but this cannot
    // be checked since it would create a compiler error

    @Test
    public void callGetAttributeStringNoSubscriptions() {
        LOG.info(name.getMethodName() + "");
        try {
            String result;

            // must set the value before it can be retrieved again
            String stringArg = "Hello world";
            testInterfaceProxy.setAttributeStringNoSubscriptions(stringArg);

            result = testInterfaceProxy.getAttributeStringNoSubscriptions();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (!result.equals("Hello world")) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeStringNoSubscriptions() {
        LOG.info(name.getMethodName() + "");
        try {
            String stringArg = "Hello world";
            testInterfaceProxy.setAttributeStringNoSubscriptions(stringArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeInt8readonlyNoSubscriptions() {
        LOG.info(name.getMethodName() + "");
        try {
            Byte result;
            // value is hardcoded on provider side since it is readonly
            result = testInterfaceProxy.getAttributeInt8readonlyNoSubscriptions();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (result != -128) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    // no setter for attributeInt8readonlyNoSubscriptions

    @Test
    public void callGetAttributeArrayOfStringImplicit() {
        LOG.info(name.getMethodName() + "");
        try {
            String[] result;

            // must set the value before it can be retrieved again
            String[] stringArrayArg = IltUtil.createStringArray();
            testInterfaceProxy.setAttributeArrayOfStringImplicit(stringArrayArg);

            result = testInterfaceProxy.getAttributeArrayOfStringImplicit();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (!IltUtil.checkStringArray(result)) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeArrayOfStringImplicit() {
        LOG.info(name.getMethodName() + "");
        try {
            String[] stringArrayArg = IltUtil.createStringArray();
            testInterfaceProxy.setAttributeArrayOfStringImplicit(stringArrayArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeEnumeration() {
        LOG.info(name.getMethodName() + "");
        try {
            Enumeration result;

            // must set the value before it can be retrieved again
            Enumeration enumerationArg = Enumeration.ENUM_0_VALUE_2;
            testInterfaceProxy.setAttributeEnumeration(enumerationArg);

            result = testInterfaceProxy.getAttributeEnumeration();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (result != Enumeration.ENUM_0_VALUE_2) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeEnumeration() {
        LOG.info(name.getMethodName() + "");
        try {
            Enumeration enumerationArg = Enumeration.ENUM_0_VALUE_2;
            testInterfaceProxy.setAttributeEnumeration(enumerationArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeExtendedEnumerationReadonly() {
        LOG.info(name.getMethodName() + "");
        try {
            ExtendedEnumerationWithPartlyDefinedValues result;

            // value is hardcoded on provider side since it is readonly
            result = testInterfaceProxy.getAttributeExtendedEnumerationReadonly();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (result != ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    // no setter for attributeExtendedEnumerationReadonly

    @Test
    public void callGetAttributeBaseStruct() {
        LOG.info(name.getMethodName() + "");
        try {
            BaseStruct result;

            // must set the value before it can be retrieved again
            BaseStruct baseStructArg = IltUtil.createBaseStruct();
            testInterfaceProxy.setAttributeBaseStruct(baseStructArg);

            result = testInterfaceProxy.getAttributeBaseStruct();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (!IltUtil.checkBaseStruct(result)) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeBaseStruct() {
        LOG.info(name.getMethodName() + "");
        try {
            BaseStruct baseStructArg = IltUtil.createBaseStruct();
            testInterfaceProxy.setAttributeBaseStruct(baseStructArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeExtendedExtendedBaseStruct() {
        LOG.info(name.getMethodName() + "");
        try {
            ExtendedExtendedBaseStruct result;

            // must set the value before it can be retrieved again
            ExtendedExtendedBaseStruct extendedExtendedBaseStructArg = IltUtil.createExtendedExtendedBaseStruct();
            testInterfaceProxy.setAttributeExtendedExtendedBaseStruct(extendedExtendedBaseStructArg);

            result = testInterfaceProxy.getAttributeExtendedExtendedBaseStruct();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            if (!IltUtil.checkExtendedExtendedBaseStruct(result)) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeExtendedExtendedBaseStruct() {
        LOG.info(name.getMethodName() + "");
        try {
            ExtendedExtendedBaseStruct extendedExtendedBaseStructArg = IltUtil.createExtendedExtendedBaseStruct();
            testInterfaceProxy.setAttributeExtendedExtendedBaseStruct(extendedExtendedBaseStructArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeMapStringString() {
        LOG.info(name.getMethodName() + "");
        try {
            MapStringString attributeMapStringStringArg = new MapStringString();
            attributeMapStringStringArg.put("keyString1", "valueString1");
            attributeMapStringStringArg.put("keyString2", "valueString2");
            attributeMapStringStringArg.put("keyString3", "valueString3");
            testInterfaceProxy.setAttributeMapStringString(attributeMapStringStringArg);
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callGetAttributeMapStringString() {
        LOG.info(name.getMethodName() + "");
        try {
            // must set the value before it can be retrieved again
            MapStringString attributeMapStringStringArg = new MapStringString();
            attributeMapStringStringArg.put("keyString1", "valueString1");
            attributeMapStringStringArg.put("keyString2", "valueString2");
            attributeMapStringStringArg.put("keyString3", "valueString3");
            testInterfaceProxy.setAttributeMapStringString(attributeMapStringStringArg);

            MapStringString result = testInterfaceProxy.getAttributeMapStringString();
            if (result == null) {
                fail(name.getMethodName() + " - FAILED - got no result");
                return;
            }
            MapStringString expected = new MapStringString();
            expected.put("keyString1", "valueString1");
            expected.put("keyString2", "valueString2");
            expected.put("keyString3", "valueString3");
            if (!result.equals(expected)) {
                fail(name.getMethodName() + " - FAILED - got invalid result");
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    /*
     * GETTER AND SETTER CALLS WITH EXCEPTION
     */

    @Test
    public void callGetAttributeWithExceptionFromGetter() {
        LOG.info(name.getMethodName() + "");
        try {
            testInterfaceProxy.getAttributeWithExceptionFromGetter();
            fail(name.getMethodName() + " - FAILED - unexpected return without exception");
            return;
        } catch (ProviderRuntimeException e) {
            if (e.getMessage() == null
                    || !e.getMessage().endsWith("Exception from getAttributeWithExceptionFromGetter")) {
                fail(name.getMethodName() + " - FAILED - caught invalid exception: " + e.getMessage());
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }

    @Test
    public void callSetAttributeWithExceptionFromSetter() {
        LOG.info(name.getMethodName() + "");
        try {
            testInterfaceProxy.setAttributeWithExceptionFromSetter(false);
            fail(name.getMethodName() + " - FAILED - got no result");
            return;
        } catch (ProviderRuntimeException e) {
            if (e.getMessage() == null
                    || !e.getMessage().endsWith("Exception from setAttributeWithExceptionFromSetter")) {
                fail(name.getMethodName() + " - FAILED - caught invalid exception: " + e.getMessage());
                return;
            }
        } catch (Exception e) {
            fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + e.getMessage());
            return;
        }

        LOG.info(name.getMethodName() + " - OK");
    }
}


text:
from __future__ import absolute_import
import click
from djay.application import get_current_application
from djay.utils.system import stdout

@click.command()
def info():
    """Display app info.

    Examples:

    $ dj info
    No application, try running dj init.

    $ dj info
    Application:
      foo @ 2.7.9
    Requirements:
      Django == 1.10

    """
    application = get_current_application()
    info = application.info()
    stdout.write(info)
    return info


text:
#ifndef ___INANITY_EMPTY_FILE_HPP___
#define ___INANITY_EMPTY_FILE_HPP___

#include "File.hpp"

/*
Файл содержит класс пустого файла нулевой длины, который нельзя читать.
*/

BEGIN_INANITY

/// Класс пустого файла.
/** Пригодится в вырожденных случаях, когда нужно выдать файл нулевой длины. */
class EmptyFile : public File
{
public:
	void* GetData() const;
	size_t GetSize() const;
};

END_INANITY

#endif


text:
@class PSPDFDocument;

/// saves various data of a page. Managed within PSPDFDocument.
@interface PSPDFPageInfo : NSObject

/// autoreleased object with page and rotation.
+ (id)pageInfoWithRect:(CGRect)rect rotation:(NSUInteger)rotation;

/// init object with page and rotation.
- (id)initWithRect:(CGRect)rect rotation:(NSUInteger)rotation;

/// saved aspect ratio of current page.
@property(nonatomic, assign) CGRect pageRect;

/// returns corrected, rotated bounds of pageRect.
@property(nonatomic, assign, readonly) CGRect rotatedPageRect;

/// saved page rotation of current page. Value between 0 and 270.
@property(nonatomic, assign) NSUInteger pageRotation;

/// referenced page.
@property(nonatomic, assign) NSUInteger page;

/// referenced document, weak.
@property(nonatomic, ps_weak) PSPDFDocument *document;

@end

/// saves various page coordinates.
@interface PSPDFPageCoordinates : NSObject

/// initializes coordinate class, autoreleased.
+ (id)pageCoordinatesWithpdfPoint:(CGPoint)pdfPoint screenPoint:(CGPoint)screenPoint viewPoint:(CGPoint)viewPoint pageSize:(CGSize)pageSize zoomScale:(CGFloat)zoomScale;

/// initializes coordinate class, autoreleased.
- (id)initCoordinatesWithpdfPoint:(CGPoint)pdfPoint screenPoint:(CGPoint)screenPoint viewPoint:(CGPoint)viewPoint pageSize:(CGSize)pageSize zoomScale:(CGFloat)zoomScale;

/// point relative to pdf coordinates.
@property(nonatomic, assign, readonly) CGPoint pdfPoint;

/// point relative to screen.
@property(nonatomic, assign, readonly) CGPoint screenPoint;

/// point realtive to view where pdf is displayed.
@property(nonatomic, assign, readonly) CGPoint viewPoint;

/// page size. (pdf may be upscaled AND zoomd via the scrollview)
@property(nonatomic, assign, readonly) CGSize pageSize;

/// current active zoomScale.
@property(nonatomic, assign, readonly) CGFloat zoomScale;

@end


text:
package de.iss.mv2.messaging;

/**
 * The response to a {@link DomainNamesRequest} containing the available domain names.
 * @author Marcel Singer
 *
 */
public class DomainNamesResponse extends MV2Message {

	/**
	 * Creates a new instance of  {@link DomainNamesResponse}.
	 */
	public DomainNamesResponse() {
		super(STD_MESSAGE.DOMAIN_NAMES_RESPONSE);
	}

	/**
	 * Sets the available domain names.
	 * @param domainNames The domain names to set.
	 */
	public void setAvailableDomainNames(String[] domainNames){
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<domainNames.length; i++){
			if(i > 0) sb.append(";");
			sb.append(domainNames[i]);
		}
		setMessageField(new MessageField(DEF_MESSAGE_FIELD.CONTENT_PLAIN, sb.toString()), true);
	}

	/**
	 * Returns the available domain names.
	 * @return The available domain names.
	 */
	public String[] getAvailableDomainNames(){
		String cont = getFieldStringValue(DEF_MESSAGE_FIELD.CONTENT_PLAIN, null);
		if(cont == null) return new String[0];
		return cont.split(";");
	}

}


text: pub mod vector;


text:
/* This stylesheet generated by Transfonter (http://transfonter.org) on September 24, 2016 9:58 AM */

@font-face {
	font-family: '.SF NS Text';
	src: url('hinted-.SFNSText-Regular.eot');
	src: local('.SF NS Text Regular'), local('.SFNSText-Regular'),
		url('hinted-.SFNSText-Regular.eot?#iefix') format('embedded-opentype'),
		url('hinted-.SFNSText-Regular.woff') format('woff'),
		url('hinted-.SFNSText-Regular.ttf') format('truetype');
	font-weight: normal;
	font-style: normal;
}


text:
module Nomenklatura
  class Client
    include HTTParty
    format :json

    def initialize(options = {})
      options = { api_prefix: '/api/2/' }.merge(options)
      host = options[:host] || ENV['NOMENKLATURA_HOST']
      key = options[:api_key] || ENV['NOMENKLATURA_APIKEY']
      fail 'host or api_key are missing' if host.nil? || key.nil?
      self.class.base_uri(host)
      self.class.default_params(api_key: key)
      if host[-1] == '/' && options[:api_prefix][0] == '/'
        options[:api_prefix] = options[:api_prefix][1..-1]
      end
      @api_prefix = options[:api_prefix]
    end

    def full_path(endpoint)
      endpoint = endpoint[1..-1] if endpoint[0] == '/'
      @api_prefix + endpoint
    end

    def get(path, params)
      self.class.get(full_path(path), query: params)
    end

    def post(path, body)
      body = body.to_json # FIXME: rails
      self.class.post(full_path(path), body: body, headers: { 'Content-Type' => 'application/json' })
    end
  end

  class Error < StandardError
    attr_reader :raw, :status, :errors

    def initialize(data = {})
      @raw = data
      @status = data.try(:[], 'status')
      @errors = data.try(:[], 'errors')
      super(data.try(:[], 'description') || "Unknown error: #{data}")
    end
  end

  class ServiceNotAvailable < StandardError; end
  class InvalidRequest < Error; end
  class NoMatch < Error; end

  class Dataset
    def initialize(name, client_options = {})
      @name = name
      @client = Client.new(client_options)
    end

    def self.create(name, label, client_options = {})
      data = { name: name, label: label }
      client = Client.new(client_options)
      resp = client.post('/datasets', data)
      fail InvalidRequest, resp.parsed_response if resp.code != 200
      Dataset.new(name, client_options)
    end

    def entity_by_name(entityname, params = {})
      resp = @client.get(format('/datasets/%s/find', @name), params.merge(name: entityname))
      if resp.code == 404
        fail NoMatch, resp.parsed_response
      elsif resp.code == 500
        fail ServiceNotAvailable.new(resp)
      elsif resp.code != 200
        fail InvalidRequest, resp.parsed_response
      end
      Entity.new(@client, resp.parsed_response)
    end

    def create_entity(name, attributes: {}, reviewed: false, invalid: false, canonical: nil, **kw)
      kw.update(
        'name' => name,
        'attributes' => attributes,
        'reviewed' => reviewed,
        'invalid' => invalid,
        'canonical' => canonical,
        'dataset' => @name
      )
      resp = @client.post('/entities', kw)
      if resp.code == 400
        fail InvalidRequest, resp.parsed_response
      end
      Entity.new(@client, resp.parsed_response)
    end

    # PORT from API version 1
    #
    # look for an entity by name, if it doesn't exist, create one. return cleaned/same name
    # or nil if invalid
    def lookup(name, attributes: {})
      entity = entity_by_name(name).dereference
      return nil if entity.invalid?
      return entity.name
    rescue NoMatch
      begin
        create_entity(name, attributes: attributes)
      rescue InvalidRequest => inv
        # caching problem on api side
        raise unless inv.errors.try(:[], 'name') == 'Entity already exists.'
        entity = entity_by_name(name, cachebreaker: Time.now.to_i).dereference
        return entity.name
      end
      return name
    end
  end

  class Entity
    def initialize(client, data)
      @client = client
      @data = data
    end

    # FIXME: nicer accessors for ['name', 'invalid', 'reviewed', 'canonical', 'attributes']
    def name; @data.try(:[], 'name'); end
    def invalid?; @data.try(:[], 'invalid'); end
    def reviewed?; @data.try(:[], 'reviewed'); end
    def attributes; @data.try(:[], 'attributes'); end

    def canonical
      c = @data.try(:[], 'canonical')
      Entity.new(@client, c) unless c.nil?
    end

    def dereference
      return canonical.dereference unless canonical.nil?
      self
    end
  end
end


text:
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { JhiConfigService } from './config.service';
import { ProfileService } from '../../layouts/profiles/profile.service';
import { JhiApplicationsService } from '../';
import { JhiRefreshService } from '../../shared/refresh/refresh.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'jhi-config',
    templateUrl: './config.component.html'
})
export class JhiConfigComponent implements OnInit, OnDestroy {
    application: string;
    profile: string;
    label: string;
    activeRegistryProfiles: any;
    isNative: boolean;
    nativeSearchLocation: string;
    gitUri: string;
    gitSearchLocation: string;
    configAsYaml: any;
    configAsProperties: any;
    configAsJson: any;
    configAsKeyValuePairs: any;
    applicationList: Array<string>;

    refreshReloadSubscription: Subscription;

    constructor(private configService: JhiConfigService,
                private profileService: ProfileService,
                private applicationsService: JhiApplicationsService,
                private refreshService: JhiRefreshService
    ) {
        this.application = 'application';
        this.profile = 'prod';
        this.label = 'master';
        this.activeRegistryProfiles = [];
        this.isNative = true;
        this.applicationList = ['application'];
    }

    ngOnInit() {
        this.load();
        this.refresh();
    }

    ngOnDestroy() {
        this.refreshReloadSubscription.unsubscribe();
    }

    load() {
        this.profileService.getProfileInfo().subscribe((response) => {
            this.activeRegistryProfiles = response.activeProfiles;
            this.isNative = this.activeRegistryProfiles.includes('native');
            this.nativeSearchLocation = response.nativeSearchLocation;
            this.gitUri = response.gitUri;
            this.gitSearchLocation = response.gitSearchLocation;
        });

        this.refreshReloadSubscription = this.refreshService.refreshReload$.subscribe((empty) => this.refresh());
    }

    refresh() {
        this.configService.getConfigAsYaml(this.application, this.profile, this.label).subscribe((response) => {
            this.configAsYaml = response;
        }, () => {
            this.configAsYaml = '';
        });

        this.configService.getConfigAsProperties(this.application, this.profile, this.label).subscribe((response) => {
            console.log(response);
            this.configAsProperties = response;

            const keyValueArray = [];
            this.configAsProperties.split('\n').forEach((property) => {
                const keyValueSplit = property.split(': ');
                keyValueArray.push({key: keyValueSplit[0], value: keyValueSplit[1]});
            });
            this.configAsKeyValuePairs = keyValueArray;
        }, () => {
            this.configAsProperties = '';
        });

        this.configService.getConfigAsJson(this.application, this.profile, this.label).subscribe((response) => {
            this.configAsJson = response;
        }, () => {
            this.configAsJson = {};
        });

        this.applicationsService.findAll().subscribe((data) => {
            if (data && data.applications) {
                this.applicationList = ['application'];
                data.applications.forEach((application) => {
                    const instanceId = application.instances[0].instanceId;
                    let applicationName;
                    if (instanceId.indexOf(':') === -1) {
                        applicationName = application.name.toLowerCase();
                    } else {
                        applicationName = instanceId.substr(0, instanceId.indexOf(':'));
                    }
                    this.applicationList.push(applicationName);
                });
            }
        });
    }
}


text:
package com.example.silence.flyweather.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.example.silence.flyweather.db.FlyWeatherDB;
import com.example.silence.flyweather.model.City;
import com.example.silence.flyweather.model.County;
import com.example.silence.flyweather.model.Province;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Silence on 2016/3/29.
 */
public class Utility {
    /**
     * 解析和处理服务器返回的省级数据
     */
    public synchronized static boolean handleProvinceResponse(FlyWeatherDB flyWeatherDB, String response) {
        if (!TextUtils.isEmpty(response)){
            String[] allProvinces = response.split(",");
            if (allProvinces != null && allProvinces.length > 0){
                for (String p : allProvinces){
                    String[] array = p.split("\\|");
                    Province province = new Province();
                    province.setProvinceCode(array[0]);
                    province.setProvinceName(array[1]);
                    //将解析出来的数据存储到Province表
                    flyWeatherDB.saveProvince(province);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 解析和处理服务器返回的市级数据
     */
    public static boolean handleCitiesResponse(FlyWeatherDB flyWeatherDB, String response, int provinceID){
        if (!TextUtils.isEmpty(response)){
            String[] allCities = response.split(",");
            if (allCities != null && allCities.length > 0){
                for (String c : allCities){
                    String [] array = c.split("\\|");
                    City city = new City();
                    city.setCityCode(array[0]);
                    city.setCityName(array[1]);
                    city.setProvinceId(provinceID);
                    //将解析出来的数据储存到City表
                    flyWeatherDB.savedCity(city);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 解析和处理服务器返回的县级数据
     */
    public static boolean handleCountiesResponse(FlyWeatherDB flyWeatherDB, String response, int cityId){
        if (!TextUtils.isEmpty(response)){
            String[] allCounties = response.split(",");
            if (allCounties != null && allCounties.length > 0){
                for (String c : allCounties){
                    String [] array = c.split("\\|");
                    County county = new County();
                    county.setCountyCode(array[0]);
                    county.setCountyName(array[1]);
                    county.setCityId(cityId);
                    //将解析出来的数据储存到County表
                    flyWeatherDB.savedCounty(county);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 解析服务器返回的JSON数据,并将解析出的数据储存到本地
     * @param context
     * @param response
     */
    public static void handleWeatherResponse(Context context,String response){
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
            String cityName = weatherInfo.getString("city");
            String weatherCode = weatherInfo.getString("cityid");
            String temp1 = weatherInfo.getString("temp1");
            String temp2 = weatherInfo.getString("temp2");
            String weatherDesp = weatherInfo.getString("weather");
            String publishTime = weatherInfo.getString("ptime");
            saveWeatherInfo(context,cityName,weatherCode,temp1,temp2,weatherDesp,publishTime);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    /**
     * 将服务器返回的所有天气信息储存到SharedPreferences文件中
     * @param context
     * @param cityName
     * @param weatherCode
     * @param temp1
     * @param temp2
     * @param weatherDesp
     * @param publishTime
     */
    public static void saveWeatherInfo(Context context,String cityName,String weatherCode,String temp1, String temp2, String weatherDesp, String publishTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CANADA.CHINA);
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("city_selected",true);
        editor.putString("city_name", cityName);
        editor.putString("weather_code", weatherCode);
        editor.putString("temp1", temp1);
        editor.putString("temp2", temp2);
        editor.putString("weather_desp", weatherDesp);
        editor.putString("publish_time", publishTime);
        editor.putString("current_date",sdf.format(new Date()));
        editor.commit();
    }
}


text:
@interface MSGraphUserInfo : NSObject
+ (void)getMSGraphUserInfo:(AuthenticationProvider *)provider completion:(void (^)(MSGraphUser *response, NSError *error))handler;
@end


text:
var SketchGallery = (function() {

	// Holds all public functions
	var API = {};

	var ITEMS_PER_PAGE = 8;

	// The default canvas size
	var ORIGINAL_WIDTH = 960;
	var ORIGINAL_HEIGHT = 580;

	var THUMBNAIL_WIDTH = 240;
	var THUMBNAIL_HEIGHT = 145;

	var LOAD_MORE_LABEL = "Load More";

	var scaleX = THUMBNAIL_WIDTH / ORIGINAL_WIDTH + 0.05;
	var scaleY = THUMBNAIL_HEIGHT / ORIGINAL_HEIGHT;

	var LOAD_TYPE_FEATURED = "featured";
	var LOAD_TYPE_MOST_RECENT = "mostrecent";
	var LOAD_TYPE_MOST_VIEWED = "mostviewed";

	var featuredContainer = null;
	var mostViewedContainer = null;
	var mostRecentContainer = null;

	var featuredButton = null;
	var mostViewedButton = null;
	var mostRecentButton = null;

	var featuredSketches = [];
	var mostViewedSketches = [];
	var mostRecentSketches = [];

	var loadingFeaturedItems = false;
	var loadingMostViewedItems = false;
	var loadingMostRecentItems = false;

	var renderQueue = [];
	var renderQueueTimer = -1;

	API.initialize = function() {
		featuredContainer = document.getElementById( "featured-sketches" );
		mostViewedContainer = document.getElementById( "most-viewed-sketches" );
		mostRecentContainer = document.getElementById( "most-recent-sketches" );

		featuredButton = document.getElementById( "load-more-featured" );
		mostViewedButton = document.getElementById( "load-more-most-viewed" );
		mostRecentButton = document.getElementById( "load-more-most-recent" );

		featuredButton.addEventListener( "click", function( event ) {
			loadFeatured();

			event.preventDefault();
		}, false );

		mostViewedButton.addEventListener( "click", function( event ) {
			loadMostViewed();

			event.preventDefault();
		}, false );

		mostRecentButton.addEventListener( "click", function( event ) {
			loadMostRecent();

			event.preventDefault();
		}, false );

		loadFeatured();
		loadMostViewed();
		loadMostRecent();
	}

	function loadFeatured() {
		if (!loadingFeaturedItems) {
			loadingFeaturedItems = true;

			SketchIO.loadGalleryItems( LOAD_TYPE_FEATURED, featuredSketches.length, ITEMS_PER_PAGE, function( status, sketches, rows ) {

				if( status == "success" ) {
					addSketches( featuredSketches, sketches, featuredContainer );
				}

				featuredButton.innerHTML = LOAD_MORE_LABEL + " (" + featuredSketches.length + "/" + rows + ")";
				featuredButton.style.display = featuredSketches.length < rows ? "inline-block" : "none";

				loadingFeaturedItems = false;

			} );
		}
	}

	function loadMostViewed() {
		if (!loadingMostViewedItems) {
			loadingMostViewedItems = true;

			SketchIO.loadGalleryItems( LOAD_TYPE_MOST_VIEWED, mostViewedSketches.length, ITEMS_PER_PAGE, function( status, sketches, rows ) {

				if( status == "success" ) {
					addSketches( mostViewedSketches, sketches, mostViewedContainer );
				}

				mostViewedButton.innerHTML = LOAD_MORE_LABEL + " (" + mostViewedSketches.length + "/" + rows + ")";
				mostViewedButton.style.display = mostViewedSketches.length < rows ? "inline-block" : "none";

				loadingMostViewedItems = false;

			} );
		}
	}

	function loadMostRecent() {
		if (!loadingMostRecentItems) {
			loadingMostRecentItems = true;

			SketchIO.loadGalleryItems( LOAD_TYPE_MOST_RECENT, mostRecentSketches.length, ITEMS_PER_PAGE, function( status, sketches, rows ) {

				if( status == "success" ) {
					addSketches( mostRecentSketches, sketches, mostRecentContainer );
				}

				mostRecentButton.innerHTML = LOAD_MORE_LABEL + " (" + mostRecentSketches.length + "/" + rows + ")";
				mostRecentButton.style.display = mostRecentSketches.length < rows ? "inline-block" : "none";

				loadingMostRecentItems = false;

			} );
		}
	}

	function addSketches( stack, sketches, container ) {

		for( var i = 0; i < sketches.length; i++ ) {

			var sketch = sketches[i];

			var canvasID = container.getAttribute("id") + sketch.id;

			// Create the element which will represent this sketch
			var element = document.createElement( 'li' );

			// Define the markup which will be added to our element
			var markup = "";
			markup += 	"";
			markup += 		"<canvas id='" + canvasID + "'></canvas>";
			markup += 		"
";
			markup += 			"
" + sketch.date.substr( 0, 10 ) + "
";
			markup += 			"/";
			markup += 			"
" + sketch.views + ( sketch.views == 1 ? " view" : " views" ) + "
";
			markup += 		"";
			markup += 	"";

			// Write the markup inside of the element
			element.innerHTML = markup;

			// Now add element to our container
			container.appendChild( element );

			var definition = { canvasID: canvasID, sketch: sketch };

			renderQueue.push( definition );
			stack.push( definition );

		}

		startRenderQueue();

	}

	function startRenderQueue() {
		if( renderQueue.length && renderQueueTimer == -1 ) {
			renderQueueTimer = setInterval( updateRenderQueue, 5 );
		}
 	}
	function updateRenderQueue() {
		if (renderQueue.length) {
			var item = renderQueue.shift();

			render(item.canvasID, item.sketch)
		}
		else {
			stopRenderQueue();
		}
	}
	function stopRenderQueue() {
		clearInterval( renderQueueTimer );
		renderQueueTimer = -1;
	}

	function render( canvasID, sketch ) {

		var canvas = document.getElementById( canvasID );
		var context = canvas.getContext( '2d' );

		context.clearRect( 0, 0, canvas.width, canvas.height );

		context.save();
		context.scale( scaleX, scaleY );

		var lines = sketch.lines;
		var globalPerspective = sketch.perspective;
		var lineCount = lines.length;

		// Go through each line and draw a path between its points
		while ( lineCount-- ) {

			var thickness = lines[lineCount].thickness;
			var perspective = wrapNumber( ( globalPerspective - lines[lineCount].perspective ) * 2, 2 );
			var dashed = lines[lineCount].dashed;
			var points = lines[lineCount].points;

			var p1 = points[0];
			var p2 = points[1];

			// Only begind the path if we're drawing on solid line
			if ( !dashed ) {
				context.beginPath();
			}

			for (var i = 1, len = points.length; i < len; i++) {

				// If we're drawing a dashed line, we need to begin a new
				// path on every loop
				if ( dashed ) {
					context.beginPath();
				}

				var p1x = p1.normal.x;
				var p2x = p2.normal.x;

				// Adjust the position based on depth
				p1x += perspective * ( p1.normal.x - ( ORIGINAL_WIDTH * 0.5 ) ) * ( perspective < 0 ? 1 : -1 );
				p2x += perspective * ( p2.normal.x - ( ORIGINAL_WIDTH * 0.5 ) ) * ( perspective < 0 ? 1 : -1 );

				if( i == 1 || dashed ) {
					context.moveTo(p1x, p1.normal.y);
				}

				// Draw a smooth curve between p1 and p2
				context.quadraticCurveTo(p1x, p1.normal.y, p1x + (p2x - p1x) / 2, p1.normal.y + (p2.normal.y - p1.normal.y) / 2);

				p1 = points[i];
				p2 = points[i + 1];

				// If this is a dashed line, it needs to be drawn repeatedly
				// in this loop
				if( dashed ) {
					stroke( context, ( thickness * ( 1 ) ).toFixed(2) );
				}
			}

			// If we're drawing a solid line, close it now
			if( !dashed ) {
				stroke( context, thickness );
			}

		}

		context.restore();

	}

	function stroke( context, thickness ) {
		// Draw this line
		context.lineCap = 'round';
		context.lineJoin = 'round';
		context.lineWidth = thickness;
		context.strokeStyle = 'rgba(0,0,0,0.96)';
		context.stroke();
	}

	function wrapNumber( value, limit ) {
		if (value > limit) {
			return -limit + (value % limit);
		}

		if (value < -limit) {
			return limit + (value % limit);
		}

		return value;
	}

	function distanceBetween(p1, p2) {
		var dx = p1.x-p2.x;
		var dy = p1.y-p2.y;
		return Math.sqrt(dx*dx + dy*dy);
	}

	return API;

} )();

SketchGallery.initialize();


text:
module Root::NamespaceHelper
  def translate(key, options = {})
    if key.to_s =~ /(\b|_|\.)markdown$/
      Markdown.render(super).html_safe
    else
      super
    end
  end

  alias t translate

  def flag_tag(locale = I18n.locale)
    image_tag "flags/#{locale}.png", :alt => locale
  end
end


text:
@interface SearchMainTableViewController : BaseTableViewController

@end


text:
"""
 Copyright (c) 2015 Michael Bright and Bamboo HR LLC

 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.
"""
import datetime
from sqlalchemy import Column, DateTime
# pylint: disable=no-member,too-few-public-methods

class DateModel(object):
    created_date = Column(DateTime, default=datetime.datetime.utcnow, index=True)
    start_date = Column(DateTime, index=True)
    end_date = Column(DateTime, index=True)


text:
<mvc:View
	controllerName="sap.m.sample.ActionSelect.C"
	xmlns:l="sap.ui.layout"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:core="sap.ui.core"
	xmlns="sap.m">
	<l:VerticalLayout
		class="sapUiContentPadding"
		width="100%">
		<ActionSelect
			id="select"
			items="{
				path: '/ProductCollection',
				sorter: { path: 'Name' }
			}">
			<items>
				<core:Item key="{ProductId}" text="{Name}" />
			</items>
		</ActionSelect>
	</l:VerticalLayout>
</mvc:View>


text:
package org.elasticsearch.xpack.spatial.index.mapper;

import org.apache.lucene.document.ShapeField;
import org.apache.lucene.store.ByteBuffersDataOutput;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.index.mapper.CustomDocValuesField;
import org.elasticsearch.xpack.spatial.index.fielddata.CentroidCalculator;
import org.elasticsearch.xpack.spatial.index.fielddata.GeoShapeCoordinateEncoder;
import org.elasticsearch.xpack.spatial.index.fielddata.TriangleTreeWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BinaryGeoShapeDocValuesField extends CustomDocValuesField {

    private final List<ShapeField.DecodedTriangle> triangles;
    private final CentroidCalculator centroidCalculator;

    public BinaryGeoShapeDocValuesField(String name, ShapeField.DecodedTriangle[] triangles, CentroidCalculator centroidCalculator) {
        super(name);
        this.triangles = new ArrayList<>(triangles.length);
        this.centroidCalculator = centroidCalculator;
        this.triangles.addAll(Arrays.asList(triangles));
    }

    public void add(ShapeField.DecodedTriangle[] triangles, CentroidCalculator centroidCalculator) {
        this.triangles.addAll(Arrays.asList(triangles));
        this.centroidCalculator.addFrom(centroidCalculator);
    }

    @Override
    public BytesRef binaryValue() {
        try {
            final TriangleTreeWriter writer = new TriangleTreeWriter(triangles, GeoShapeCoordinateEncoder.INSTANCE, centroidCalculator);
            ByteBuffersDataOutput output = new ByteBuffersDataOutput();
            writer.writeTo(output);
            return new BytesRef(output.toArrayCopy(), 0, Math.toIntExact(output.size()));
        } catch (IOException e) {
            throw new ElasticsearchException("failed to encode shape", e);
        }
    }
}


text:
#include <storage/Node.h>

#include "ConnectionStore.h"
#include "ContactCachedConnections.h"

#include "common/GenericStore.h"

using namespace IM;

//#pragma mark Constructor

ContactCachedConnections::ContactCachedConnections(const entry_ref &ref)
	: Contact(ref),
	fConnections(new ConnectionStore()) {

	ReloadConnections();
};

ContactCachedConnections::ContactCachedConnections(const BEntry &entry)
	: Contact(entry),
	fConnections(new ConnectionStore()) {

	ReloadConnections();
};

//#pragma mark Public

void ContactCachedConnections::ReloadConnections(void) {
	char buffer[512];

	fConnections->Clear();
	Update();

	for (int32 i = 0; i < CountConnections(); i++) {
		if (ConnectionAt(i, buffer) == B_OK) {
			IM::Connection con(buffer);
			fConnections->Add(con);
		};
	};
};

ConnectionStore *ContactCachedConnections::CachedConnections(void) {
	return fConnections;
};

ContactHandle ContactCachedConnections::Handle(void) const {
	ContactHandle us;
	us.entry = EntryRef();

	node_ref nref;
	BNode node(&us.entry);
	node.GetNodeRef(&nref);

	us.node = nref.node;

	return us;
};

//#pragma mark Operators

ContactCachedConnections::operator const entry_ref *(void) const {
	Contact *contact = (Contact *)this;
	return *contact;
};

bool ContactCachedConnections::operator == (const entry_ref & entry) const {
	return ((*(Contact *)this)) == entry;
};

bool ContactCachedConnections::operator == (const ContactHandle &handle) const {
	ContactHandle us = Handle();
	return (handle == us);
};


text:
package com.orange.engine.handler.timer;

import com.orange.engine.handler.IUpdateHandler;

/**
 * timerHandler 处理更新
 * (c) OrangeGame 2012
 * @author OrangeGame <OGEngine@orangegame.cn>
 */
public class TimerHandler implements IUpdateHandler {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================
	/**计时器每次间隔时间*/
	private float mTimerSeconds;
    /**计时器间隔时间记录值*/
	private float mTimerSecondsElapsed;
	/**是否触发*/
	private boolean mTimerCallbackTriggered;
	/**计时器触发callback*/
	protected final ITimerCallback mTimerCallback;
	/**是否自动重置*/
	private boolean mAutoReset;

	// ===========================================================
	// Constructors
	// ===========================================================
	/**
	 * 构建计时器处理
	 * @param pTimerSeconds 每次响应间隔时间
	 * @param pTimerCallback 计时器触发callback
	 */
	public TimerHandler(final float pTimerSeconds, final ITimerCallback pTimerCallback) {
		this(pTimerSeconds, false, pTimerCallback);
	}

	public TimerHandler(final float pTimerSeconds, final boolean pAutoReset, final ITimerCallback pTimerCallback) {
		if(pTimerSeconds <= 0){
			throw new IllegalStateException("pTimerSeconds must be > 0!");
		}

		this.mTimerSeconds = pTimerSeconds;
		this.mAutoReset = pAutoReset;
		this.mTimerCallback = pTimerCallback;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public boolean isAutoReset() {
		return this.mAutoReset;
	}

	public void setAutoReset(final boolean pAutoReset) {
		this.mAutoReset = pAutoReset;
	}

	public void setTimerSeconds(final float pTimerSeconds) {
		if(pTimerSeconds <= 0){
			throw new IllegalStateException("pTimerSeconds must be > 0!");
		}

		this.mTimerSeconds = pTimerSeconds;
	}

	public float getTimerSeconds() {
		return this.mTimerSeconds;
	}

	public float getTimerSecondsElapsed() {
		return this.mTimerSecondsElapsed;
	}

	public boolean isTimerCallbackTriggered() {
		return this.mTimerCallbackTriggered;
	}

	public void setTimerCallbackTriggered(boolean pTimerCallbackTriggered) {
		this.mTimerCallbackTriggered = pTimerCallbackTriggered;
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public void onUpdate(final float pSecondsElapsed) {
		if(this.mAutoReset) {
			this.mTimerSecondsElapsed += pSecondsElapsed;
			while(this.mTimerSecondsElapsed >= this.mTimerSeconds) {
				this.mTimerSecondsElapsed -= this.mTimerSeconds;
				this.mTimerCallback.onTimePassed(this);
			}
		} else {
			if(!this.mTimerCallbackTriggered) {
				this.mTimerSecondsElapsed += pSecondsElapsed;
				if(this.mTimerSecondsElapsed >= this.mTimerSeconds) {
					this.mTimerCallbackTriggered = true;
					this.mTimerCallback.onTimePassed(this);
				}
			}
		}
	}

	@Override
	public void reset() {
		this.mTimerCallbackTriggered = false;
		this.mTimerSecondsElapsed = 0;
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
package org.apache.mina.transport.tcp.nio;

import java.io.IOException;
import java.net.SocketAddress;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.mina.service.SelectorStrategy;
import org.apache.mina.transport.tcp.AbstractTcpServer;
import org.apache.mina.transport.tcp.NioSelectorProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class implements a TCP NIO based server.
 *
 * @author Apache MINA Project
 */
public class NioTcpServer extends AbstractTcpServer {
    static final Logger LOG = LoggerFactory.getLogger(NioTcpServer.class);

    // list of bound addresses
    private Set<SocketAddress> addresses = Collections.synchronizedSet(new HashSet<SocketAddress>());

    // map of the created selection keys, mainly used for cancelling them.
    // private Map<SocketAddress,NioSelectorProcessor> serverSocketChannels =
    // new ConcurrentHashMap<SocketAddress, NioSelectorProcessor>();

    // the strategy for dispatching servers and client to selector threads.
    private SelectorStrategy strategy;

    public NioTcpServer(SelectorStrategy strategy) {
        super();
        this.strategy = strategy;
    }

    @Override
    public void bind(SocketAddress... localAddress) throws IOException {
        if (localAddress == null) {
            // We should at least have one address to bind on
            throw new IllegalStateException("LocalAdress cannot be null");
        }

        for (SocketAddress address : localAddress) {
            // check if the address is already bound
            synchronized (this) {
                if (addresses.contains(address)) {
                    throw new IOException("address " + address + " already bound");
                }

                LOG.debug("binding address {}", address);

                addresses.add(address);
                NioSelectorProcessor processor = (NioSelectorProcessor) strategy.getSelectorForBindNewAddress();
                processor.bindAndAcceptAddress(this, address);
                if (addresses.size() == 1) {
                    // it's the first address bound, let's fire the event
                    fireServiceActivated();
                }
            }
        }
    }

    @Override
    public Set<SocketAddress> getLocalAddresses() {
        return addresses;
    }

    @Override
    public void unbind(SocketAddress... localAddresses) throws IOException {
        for (SocketAddress socketAddress : localAddresses) {
            LOG.debug("unbinding {}", socketAddress);
            synchronized (this) {
                strategy.unbind(socketAddress);
                addresses.remove(socketAddress);
                if (addresses.isEmpty()) {
                    fireServiceInactivated();
                }
            }
        }
    }

    @Override
    public void unbindAll() throws IOException {
        for (SocketAddress socketAddress : addresses) {
            unbind(socketAddress);
        }
    }

}