text:
package net.jxta.impl.content.defprovider;

import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.Element;
import net.jxta.impl.content.AbstractPipeContentShareAdvertisement;

/**
 * This class is a simple re-badging of the more generic abstract version,
 * AbstractPipeContentAdvertisement.  This allows us to use the same
 * advertisement structure yet identify the pipes which will understand
 * the protocol used by the SRDI socket transfer provider.
 */
public class DefaultContentShareAdvertisementImpl
        extends AbstractPipeContentShareAdvertisement {
    /**
     * ContentID field.
     */
    private static final String contentIDTag = "ContentID";

    /**
     * Fields to index on.
     */
    private static final String [] fields = {
        contentIDTag
    };

    /**
     *  Returns the identifying type of this Advertisement.
     *
     * @return String the type of advertisement
     */
    public static String getAdvertisementType() {
        return "jxta:DefaultContent";
    }

    /**
     * Instantiator for this Advertisement type.
     */
    public static class Instantiator
            implements AdvertisementFactory.Instantiator {
        /**
         *  {@inheritDoc}
         */
        public String getAdvertisementType() {
            return DefaultContentShareAdvertisementImpl.getAdvertisementType();
        }

        /**
         *  {@inheritDoc}
         */
        public Advertisement newInstance() {
            return new DefaultContentShareAdvertisementImpl();
        }

        /**
         *  {@inheritDoc}
         */
        public Advertisement newInstance( Element root ) {
            return new DefaultContentShareAdvertisementImpl( root );
        }
    };

    /**
     *  Construct a new AbstractPipeContentAdvertisement.
     */
    public DefaultContentShareAdvertisementImpl() {
        // Empty.
    }

    /**
     *  Construct a new AbstractPipeContentAdvertisement.
     */
    public DefaultContentShareAdvertisementImpl(Element root) {
        super(root);
    }

    /**
     * Clone this SRDISocketContentAdvertisement.
     *
     * @return a copy of this SRDISocketContentAdvertisement
     */
    @Override
    public DefaultContentShareAdvertisementImpl clone() {
        // All members are either immutable or never modified nor allowed to
        // be modified: all accessors return clones.
        DefaultContentShareAdvertisementImpl clone =
                (DefaultContentShareAdvertisementImpl) super.clone();
        return clone;
    }

    /**
     *  {@inheritDoc}
     */
    @Override
    public String [] getIndexFields() {
        return fields;
    }

}


text:
LFEvent *lfevent;
QGraphicsScene *MainScene;
GraphicsView *MainView;
JSVM *MainJSVM;

#ifdef SelfAdaption
float adaptiveRatioX;
float adaptiveRatioY;
#endif

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    Initialization();//开始初始化
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

//程序启动时调用的函数
void Widget::Initialization()
{
    lfevent=new LFEvent;//初始化全局变量
    //编码校正
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(codec);
    //注册普通类型
    RegisterJSType(ParametersStru,"ParametersStru");
    RegisterJSType(ParametersStru*,"ParametersStru*"); //被逼无奈
    RegisterJSType(LFEvent*,"LFEvent*");
    RegisterJSType(Item*,"Item*");
    RegisterJSType(String,"String");
    RegisterJSType(VideoPlayer*,"VideoPlayer*");
    RegisterJSType(GraphicsView*,"GraphicsView*");
    RegisterJSType(CaluThread*,"CaluThread*");
    RegisterJSType(AnimationType,"AnimationType");
    RegisterJSType(Pixmap*,"Pixmap*");
    RegisterJSType(MusicPlayer*,"MusicPlayer*");
    RegisterJSType(GraphicsScene*,"GraphicsScene*");
    RegisterJSType(Key,"Key");
    RegisterJSType(JSVM*,"JSVM*");
    #ifdef SelfAdaption
    //计算自适应比
    int scWidth=GetScreenWidth();
    int scHeigh=GetScreenHeigh();
    adaptiveRatioX=float(scWidth)/float(WindowsWidth);
    adaptiveRatioY=float(scHeigh)/float(WindowsHeigh);
    setGeometry(0,0,scWidth,scHeigh);
    setFixedSize(GetScreenWidth(),GetScreenHeigh());
    #else
    //计算窗口出现位置
    int widX=(GetScreenWidth()-WindowsWidth)/2;
    int widY=(GetScreenHeigh()-WindowsHeigh)/2;
    setGeometry(widX,widY,WindowsWidth,WindowsHeigh);
    setFixedSize(WindowsWidth,WindowsHeigh);
    #endif
    setWindowTitle(title);
    MainScene=AddScene(MaximumWidth,MaximunHeigh);
    MainView=AddView(0,0,WindowsWidth,WindowsHeigh);
    SetViewScene();
}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.Diagnostics.Runtime
{
    internal static class ClrHandleKindExtension
    {
        public static string GetName(this ClrHandleKind kind) => kind switch
        {
            ClrHandleKind.WeakShort => "weak short handle",
            ClrHandleKind.WeakLong => "weak long handle",
            ClrHandleKind.Strong => "strong handle",
            ClrHandleKind.Pinned => "pinned handle",
            ClrHandleKind.RefCounted => "ref counted handle",
            ClrHandleKind.Dependent => "dependent handle",
            ClrHandleKind.AsyncPinned => "async pinned handle",
            ClrHandleKind.SizedRef => "sized ref handle",
            ClrHandleKind.WeakWinRT => "weak WinRT handle",
            _ => "unknown handle"
        };
    }
}


text:
package org.postgresql.java.model;

/**
 * Use in indexes and constraints
 *
 *     [ WITH ( storage_parameter = value [, ... ] ) ]
 */
public class STORAGE_PARAMETER {

    //
}


text:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace Steam4NET
{

	[StructLayout(LayoutKind.Sequential,Pack=8)]
	public struct TSteamAppDependencyInfo
	{
		public UInt32 AppId;
		public UInt32 IsRequired;
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
		public string szMountName;
	};

}


text:
<?php

namespace Dotdigitalgroup\Email\Block\Adminhtml\Config\Dynamic\Wishlist;

class Crosssell extends \Magento\Config\Block\System\Config\Form\Field
{

    /**
     * @var \Dotdigitalgroup\Email\Helper\Data
     */
    public $dataHelper;

    /**
     * Crosssell constructor.
     *
     * @param \Dotdigitalgroup\Email\Helper\Data $dataHelper
     * @param \Magento\Backend\Block\Template\Context $context
     */
    public function __construct(
        \Dotdigitalgroup\Email\Helper\Data $dataHelper,
        \Magento\Backend\Block\Template\Context $context
    ) {
        $this->dataHelper = $dataHelper;

        parent::__construct($context);
    }

    /**
     * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
     *
     * @return string
     */
    public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        //passcode to append for url
        $passcode = $this->dataHelper->getPasscode();
        //last order id witch information will be generated
        $customerId = $this->dataHelper->getMappedCustomerId();

        if (empty($passcode)) {
            $passcode = '[PLEASE SET UP A PASSCODE]';
        }
        if (!$customerId) {
            $customerId = '[PLEASE MAP THE CUSTOMER ID]';
        }

        //generate the base url and display for default store id
        $baseUrl = $this->dataHelper->generateDynamicUrl();

        //display the full url
        $text = sprintf('%sconnector/wishlist/crosssell/code/%s/customer_id/@%s@', $baseUrl, $passcode, $customerId);
        $element->setData('value', $text);

        return parent::_getElementHtml($element);
    }
}


text:
// ideas taken from:
//     . The ocean spray in your face [Jeff Lander]
//        http://www.double.co.nz/dust/col0798.pdf
//     . Building an Advanced Particle System [John van der Burg]
//        http://www.gamasutra.com/features/20000623/vanderburg_01.htm
//   . LOVE game engine
//        http://love2d.org/
//
//
// Radius mode support, from 71 squared
//        http://particledesigner.71squared.com/
//
// IMPORTANT: Particle Designer is supported by cocos2d, but
// 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guaranteed in cocos2d,
//  cocos2d uses a another approach, but the results are almost identical.
//

#include "CCParticleSystem.h"

#include <string>

#include "CCParticleBatchNode.h"
#include "2d/ccTypes.h"
#include "CCTextureCache.h"
#include "2d/CCTextureAtlas.h"
#include "base64.h"
#include "2d/platform/CCFileUtils.h"
#include "2d/platform/CCImage.h"
#include "ZipUtils.h"
#include "2d/CCDirector.h"
#include "CCProfiling.h"
// opengl
#include "CCGL.h"

using namespace std;

NS_CC_BEGIN

// ideas taken from:
//     . The ocean spray in your face [Jeff Lander]
//        http://www.double.co.nz/dust/col0798.pdf
//     . Building an Advanced Particle System [John van der Burg]
//        http://www.gamasutra.com/features/20000623/vanderburg_01.htm
//   . LOVE game engine
//        http://love2d.org/
//
//
// Radius mode support, from 71 squared
//        http://particledesigner.71squared.com/
//
// IMPORTANT: Particle Designer is supported by cocos2d, but
// 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guaranteed in cocos2d,
//  cocos2d uses a another approach, but the results are almost identical.
//

ParticleSystem::ParticleSystem()
: _isBlendAdditive(false)
, _isAutoRemoveOnFinish(false)
, _plistFile("")
, _elapsed(0)
, _particles(nullptr)
, _configName("")
, _emitCounter(0)
, _particleIdx(0)
, _batchNode(nullptr)
, _atlasIndex(0)
, _transformSystemDirty(false)
, _allocatedParticles(0)
, _isActive(true)
, _particleCount(0)
, _duration(0)
, _sourcePosition(Vector2::ZERO)
, _posVar(Vector2::ZERO)
, _life(0)
, _lifeVar(0)
, _angle(0)
, _angleVar(0)
, _emitterMode(Mode::GRAVITY)
, _startSize(0)
, _startSizeVar(0)
, _endSize(0)
, _endSizeVar(0)
, _startSpin(0)
, _startSpinVar(0)
, _endSpin(0)
, _endSpinVar(0)
, _emissionRate(0)
, _totalParticles(0)
, _texture(nullptr)
, _blendFunc(BlendFunc::ALPHA_PREMULTIPLIED)
, _opacityModifyRGB(false)
, _yCoordFlipped(0)
, _positionType(PositionType::FREE)
{
    modeA.gravity = Vector2::ZERO;
    modeA.speed = 0;
    modeA.speedVar = 0;
    modeA.tangentialAccel = 0;
    modeA.tangentialAccelVar = 0;
    modeA.radialAccel = 0;
    modeA.radialAccelVar = 0;
    modeA.rotationIsDir = false;
    modeB.startRadius = 0;
    modeB.startRadiusVar = 0;
    modeB.endRadius = 0;
    modeB.endRadiusVar = 0;
    modeB.rotatePerSecond = 0;
    modeB.rotatePerSecondVar = 0;
}
// implementation ParticleSystem

ParticleSystem * ParticleSystem::create(const std::string& plistFile)
{
    ParticleSystem *ret = new ParticleSystem();
    if (ret && ret->initWithFile(plistFile))
    {
        ret->autorelease();
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return ret;
}

ParticleSystem* ParticleSystem::createWithTotalParticles(int numberOfParticles)
{
    ParticleSystem *ret = new ParticleSystem();
    if (ret && ret->initWithTotalParticles(numberOfParticles))
    {
        ret->autorelease();
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return ret;
}

bool ParticleSystem::init()
{
    return initWithTotalParticles(150);
}

bool ParticleSystem::initWithFile(const std::string& plistFile)
{
    bool ret = false;
    _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile);
    ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(_plistFile.c_str());

    CCASSERT( !dict.empty(), "Particles: file not found");

    // XXX compute path from a path, should define a function somewhere to do it
    string listFilePath = plistFile;
    if (listFilePath.find('/') != string::npos)
    {
        listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1);
        ret = this->initWithDictionary(dict, listFilePath.c_str());
    }
    else
    {
        ret = this->initWithDictionary(dict, "");
    }

    return ret;
}

bool ParticleSystem::initWithDictionary(ValueMap& dictionary)
{
    return initWithDictionary(dictionary, "");
}

bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname)
{
    bool ret = false;
    unsigned char *buffer = nullptr;
    unsigned char *deflated = nullptr;
    Image *image = nullptr;
    do
    {
        int maxParticles = dictionary["maxParticles"].asInt();
        // self, not super
        if(this->initWithTotalParticles(maxParticles))
        {
            // Emitter name in particle designer 2.0
            _configName = dictionary["configName"].asString();

            // angle
            _angle = dictionary["angle"].asFloat();
            _angleVar = dictionary["angleVariance"].asFloat();

            // duration
            _duration = dictionary["duration"].asFloat();

            // blend function
            if (_configName.length()>0)
            {
                _blendFunc.src = dictionary["blendFuncSource"].asFloat();
            }
            else
            {
                _blendFunc.src = dictionary["blendFuncSource"].asInt();
            }
            _blendFunc.dst = dictionary["blendFuncDestination"].asInt();

            // color
            _startColor.r = dictionary["startColorRed"].asFloat();
            _startColor.g = dictionary["startColorGreen"].asFloat();
            _startColor.b = dictionary["startColorBlue"].asFloat();
            _startColor.a = dictionary["startColorAlpha"].asFloat();

            _startColorVar.r = dictionary["startColorVarianceRed"].asFloat();
            _startColorVar.g = dictionary["startColorVarianceGreen"].asFloat();
            _startColorVar.b = dictionary["startColorVarianceBlue"].asFloat();
            _startColorVar.a = dictionary["startColorVarianceAlpha"].asFloat();

            _endColor.r = dictionary["finishColorRed"].asFloat();
            _endColor.g = dictionary["finishColorGreen"].asFloat();
            _endColor.b = dictionary["finishColorBlue"].asFloat();
            _endColor.a = dictionary["finishColorAlpha"].asFloat();

            _endColorVar.r = dictionary["finishColorVarianceRed"].asFloat();
            _endColorVar.g = dictionary["finishColorVarianceGreen"].asFloat();
            _endColorVar.b = dictionary["finishColorVarianceBlue"].asFloat();
            _endColorVar.a = dictionary["finishColorVarianceAlpha"].asFloat();

            // particle size
            _startSize = dictionary["startParticleSize"].asFloat();
            _startSizeVar = dictionary["startParticleSizeVariance"].asFloat();
            _endSize = dictionary["finishParticleSize"].asFloat();
            _endSizeVar = dictionary["finishParticleSizeVariance"].asFloat();

            // position
            float x = dictionary["sourcePositionx"].asFloat();
            float y = dictionary["sourcePositiony"].asFloat();
            this->setPosition( Vector2(x,y) );
            _posVar.x = dictionary["sourcePositionVariancex"].asFloat();
            _posVar.y = dictionary["sourcePositionVariancey"].asFloat();

            // Spinning
            _startSpin = dictionary["rotationStart"].asFloat();
            _startSpinVar = dictionary["rotationStartVariance"].asFloat();
            _endSpin= dictionary["rotationEnd"].asFloat();
            _endSpinVar= dictionary["rotationEndVariance"].asFloat();

            _emitterMode = (Mode) dictionary["emitterType"].asInt();

            // Mode A: Gravity + tangential accel + radial accel
            if (_emitterMode == Mode::GRAVITY)
            {
                // gravity
                modeA.gravity.x = dictionary["gravityx"].asFloat();
                modeA.gravity.y = dictionary["gravityy"].asFloat();

                // speed
                modeA.speed = dictionary["speed"].asFloat();
                modeA.speedVar = dictionary["speedVariance"].asFloat();

                // radial acceleration
                modeA.radialAccel = dictionary["radialAcceleration"].asFloat();
                modeA.radialAccelVar = dictionary["radialAccelVariance"].asFloat();

                // tangential acceleration
                modeA.tangentialAccel = dictionary["tangentialAcceleration"].asFloat();
                modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].asFloat();

                // rotation is dir
                modeA.rotationIsDir = dictionary["rotationIsDir"].asBool();
            }

            // or Mode B: radius movement
            else if (_emitterMode == Mode::RADIUS)
            {
                if (_configName.length()>0)
                {
                    modeB.startRadius = dictionary["maxRadius"].asInt();
                }
                else
                {
                    modeB.startRadius = dictionary["maxRadius"].asFloat();
                }
                modeB.startRadiusVar = dictionary["maxRadiusVariance"].asFloat();
                if (_configName.length()>0)
                {
                    modeB.endRadius = dictionary["minRadius"].asInt();
                }
                else
                {
                    modeB.endRadius = dictionary["minRadius"].asFloat();
                }

                if (dictionary.find("minRadiusVariance") != dictionary.end())
                {
                    modeB.endRadiusVar = dictionary["minRadiusVariance"].asFloat();
                }
                else
                {
                    modeB.endRadiusVar = 0.0f;
                }

                if (_configName.length()>0)
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asInt();
                }
                else
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asFloat();
                }
                modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].asFloat();

            } else {
                CCASSERT( false, "Invalid emitterType in config file");
                CC_BREAK_IF(true);
            }

            // life span
            _life = dictionary["particleLifespan"].asFloat();
            _lifeVar = dictionary["particleLifespanVariance"].asFloat();

            // emission Rate
            _emissionRate = _totalParticles / _life;

            //don't get the internal texture if a batchNode is used
            if (!_batchNode)
            {
                // Set a compatible default for the alpha transfer
                _opacityModifyRGB = false;

                // texture
                // Try to get the texture from the cache
                std::string textureName = dictionary["textureFileName"].asString();

                size_t rPos = textureName.rfind('/');

                if (rPos != string::npos)
                {
                    string textureDir = textureName.substr(0, rPos + 1);

                    if (!dirname.empty() && textureDir != dirname)
                    {
                        textureName = textureName.substr(rPos+1);
                        textureName = dirname + textureName;
                    }
                }
                else if (!dirname.empty() && !textureName.empty())
                {
                	textureName = dirname + textureName;
                }

                Texture2D *tex = nullptr;

                if (textureName.length() > 0)
                {
                    // set not pop-up message box when load image failed
                    bool notify = FileUtils::getInstance()->isPopupNotify();
                    FileUtils::getInstance()->setPopupNotify(false);
                    tex = Director::getInstance()->getTextureCache()->addImage(textureName);
                    // reset the value of UIImage notify
                    FileUtils::getInstance()->setPopupNotify(notify);
                }

                if (tex)
                {
                    setTexture(tex);
                }
                else
                {
                    std::string textureData = dictionary["textureImageData"].asString();
                    CCASSERT(!textureData.empty(), "");

                    auto dataLen = textureData.size();
                    if (dataLen != 0)
                    {
                        // if it fails, try to get it from the base64-gzipped data
                        int decodeLen = base64Decode((unsigned char*)textureData.c_str(), (unsigned int)dataLen, &buffer);
                        CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData");
                        CC_BREAK_IF(!buffer);

                        ssize_t deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated);
                        CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData");
                        CC_BREAK_IF(!deflated);

                        // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage()
                        image = new Image();
                        bool isOK = image->initWithImageData(deflated, deflatedLen);
                        CCASSERT(isOK, "CCParticleSystem: error init image with Data");
                        CC_BREAK_IF(!isOK);

                        setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str()));

                        image->release();
                    }
                }

                if (!_configName.empty())
                {
                    _yCoordFlipped = dictionary["yCoordFlipped"].asInt();
                }

                CCASSERT( this->_texture != nullptr, "CCParticleSystem: error loading the texture");
            }
            ret = true;
        }
    } while (0);
    free(buffer);
    free(deflated);
    return ret;
}

bool ParticleSystem::initWithTotalParticles(int numberOfParticles)
{
    _totalParticles = numberOfParticles;

    CC_SAFE_FREE(_particles);

    _particles = (tParticle*)calloc(_totalParticles, sizeof(tParticle));

    if( ! _particles )
    {
        CCLOG("Particle system: not enough memory");
        this->release();
        return false;
    }
    _allocatedParticles = numberOfParticles;

    if (_batchNode)
    {
        for (int i = 0; i < _totalParticles; i++)
        {
            _particles[i].atlasIndex=i;
        }
    }
    // default, active
    _isActive = true;

    // default blend function
    _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;

    // default movement type;
    _positionType = PositionType::FREE;

    // by default be in mode A:
    _emitterMode = Mode::GRAVITY;

    // default: modulate
    // XXX: not used
    //    colorModulate = YES;

    _isAutoRemoveOnFinish = false;

    // Optimization: compile updateParticle method
    //updateParticleSel = @selector(updateQuadWithParticle:newPosition:);
    //updateParticleImp = (CC_UPDATE_PARTICLE_IMP) [self methodForSelector:updateParticleSel];
    //for batchNode
    _transformSystemDirty = false;

    return true;
}

ParticleSystem::~ParticleSystem()
{
    // Since the scheduler retains the "target (in this case the ParticleSystem)
	// it is not needed to call "unscheduleUpdate" here. In fact, it will be called in "cleanup"
    //unscheduleUpdate();
    CC_SAFE_FREE(_particles);
    CC_SAFE_RELEASE(_texture);
}

bool ParticleSystem::addParticle()
{
    if (this->isFull())
    {
        return false;
    }

    tParticle * particle = &_particles[ _particleCount ];
    this->initParticle(particle);
    ++_particleCount;

    return true;
}

void ParticleSystem::initParticle(tParticle* particle)
{
    // timeToLive
    // no negative life. prevent division by 0
    particle->timeToLive = _life + _lifeVar * CCRANDOM_MINUS1_1();
    particle->timeToLive = MAX(0, particle->timeToLive);

    // position
    particle->pos.x = _sourcePosition.x + _posVar.x * CCRANDOM_MINUS1_1();

    particle->pos.y = _sourcePosition.y + _posVar.y * CCRANDOM_MINUS1_1();

    // Color
    Color4F start;
    start.r = clampf(_startColor.r + _startColorVar.r * CCRANDOM_MINUS1_1(), 0, 1);
    start.g = clampf(_startColor.g + _startColorVar.g * CCRANDOM_MINUS1_1(), 0, 1);
    start.b = clampf(_startColor.b + _startColorVar.b * CCRANDOM_MINUS1_1(), 0, 1);
    start.a = clampf(_startColor.a + _startColorVar.a * CCRANDOM_MINUS1_1(), 0, 1);

    Color4F end;
    end.r = clampf(_endColor.r + _endColorVar.r * CCRANDOM_MINUS1_1(), 0, 1);
    end.g = clampf(_endColor.g + _endColorVar.g * CCRANDOM_MINUS1_1(), 0, 1);
    end.b = clampf(_endColor.b + _endColorVar.b * CCRANDOM_MINUS1_1(), 0, 1);
    end.a = clampf(_endColor.a + _endColorVar.a * CCRANDOM_MINUS1_1(), 0, 1);

    particle->color = start;
    particle->deltaColor.r = (end.r - start.r) / particle->timeToLive;
    particle->deltaColor.g = (end.g - start.g) / particle->timeToLive;
    particle->deltaColor.b = (end.b - start.b) / particle->timeToLive;
    particle->deltaColor.a = (end.a - start.a) / particle->timeToLive;

    // size
    float startS = _startSize + _startSizeVar * CCRANDOM_MINUS1_1();
    startS = MAX(0, startS); // No negative value

    particle->size = startS;

    if (_endSize == START_SIZE_EQUAL_TO_END_SIZE)
    {
        particle->deltaSize = 0;
    }
    else
    {
        float endS = _endSize + _endSizeVar * CCRANDOM_MINUS1_1();
        endS = MAX(0, endS); // No negative values
        particle->deltaSize = (endS - startS) / particle->timeToLive;
    }

    // rotation
    float startA = _startSpin + _startSpinVar * CCRANDOM_MINUS1_1();
    float endA = _endSpin + _endSpinVar * CCRANDOM_MINUS1_1();
    particle->rotation = startA;
    particle->deltaRotation = (endA - startA) / particle->timeToLive;

    // position
    if (_positionType == PositionType::FREE)
    {
        particle->startPos = this->convertToWorldSpace(Vector2::ZERO);
    }
    else if (_positionType == PositionType::RELATIVE)
    {
        particle->startPos = _position;
    }

    // direction
    float a = CC_DEGREES_TO_RADIANS( _angle + _angleVar * CCRANDOM_MINUS1_1() );

    // Mode Gravity: A
    if (_emitterMode == Mode::GRAVITY)
    {
        Vector2 v(cosf( a ), sinf( a ));
        float s = modeA.speed + modeA.speedVar * CCRANDOM_MINUS1_1();

        // direction
        particle->modeA.dir = v * s ;

        // radial accel
        particle->modeA.radialAccel = modeA.radialAccel + modeA.radialAccelVar * CCRANDOM_MINUS1_1();

        // tangential accel
        particle->modeA.tangentialAccel = modeA.tangentialAccel + modeA.tangentialAccelVar * CCRANDOM_MINUS1_1();

        // rotation is dir
        if(modeA.rotationIsDir)
            particle->rotation = -CC_RADIANS_TO_DEGREES(particle->modeA.dir.getAngle());
    }

    // Mode Radius: B
    else
    {
        // Set the default diameter of the particle from the source position
        float startRadius = modeB.startRadius + modeB.startRadiusVar * CCRANDOM_MINUS1_1();
        float endRadius = modeB.endRadius + modeB.endRadiusVar * CCRANDOM_MINUS1_1();

        particle->modeB.radius = startRadius;

        if (modeB.endRadius == START_RADIUS_EQUAL_TO_END_RADIUS)
        {
            particle->modeB.deltaRadius = 0;
        }
        else
        {
            particle->modeB.deltaRadius = (endRadius - startRadius) / particle->timeToLive;
        }

        particle->modeB.angle = a;
        particle->modeB.degreesPerSecond = CC_DEGREES_TO_RADIANS(modeB.rotatePerSecond + modeB.rotatePerSecondVar * CCRANDOM_MINUS1_1());
    }
}

void ParticleSystem::onEnter()
{
    Node::onEnter();

    // update after action in run!
    this->scheduleUpdateWithPriority(1);
}

void ParticleSystem::onExit()
{
    this->unscheduleUpdate();
    Node::onExit();
}

void ParticleSystem::stopSystem()
{
    _isActive = false;
    _elapsed = _duration;
    _emitCounter = 0;
}

void ParticleSystem::resetSystem()
{
    _isActive = true;
    _elapsed = 0;
    for (_particleIdx = 0; _particleIdx < _particleCount; ++_particleIdx)
    {
        tParticle *p = &_particles[_particleIdx];
        p->timeToLive = 0;
    }
}
bool ParticleSystem::isFull()
{
    return (_particleCount == _totalParticles);
}

// ParticleSystem - MainLoop
void ParticleSystem::update(float dt)
{
    CC_PROFILER_START_CATEGORY(kProfilerCategoryParticles , "CCParticleSystem - update");

    if (_isActive && _emissionRate)
    {
        float rate = 1.0f / _emissionRate;
        //issue #1201, prevent bursts of particles, due to too high emitCounter
        if (_particleCount < _totalParticles)
        {
            _emitCounter += dt;
        }

        while (_particleCount < _totalParticles && _emitCounter > rate)
        {
            this->addParticle();
            _emitCounter -= rate;
        }

        _elapsed += dt;
        if (_duration != -1 && _duration < _elapsed)
        {
            this->stopSystem();
        }
    }

    _particleIdx = 0;

    Vector2 currentPosition = Vector2::ZERO;
    if (_positionType == PositionType::FREE)
    {
        currentPosition = this->convertToWorldSpace(Vector2::ZERO);
    }
    else if (_positionType == PositionType::RELATIVE)
    {
        currentPosition = _position;
    }

    {
        while (_particleIdx < _particleCount)
        {
            tParticle *p = &_particles[_particleIdx];

            // life
            p->timeToLive -= dt;

            if (p->timeToLive > 0)
            {
                // Mode A: gravity, direction, tangential accel & radial accel
                if (_emitterMode == Mode::GRAVITY)
                {
                    Vector2 tmp, radial, tangential;

                    radial = Vector2::ZERO;
                    // radial acceleration
                    if (p->pos.x || p->pos.y)
                    {
                        radial = p->pos.normalize();
                    }
                    tangential = radial;
                    radial = radial * p->modeA.radialAccel;

                    // tangential acceleration
                    float newy = tangential.x;
                    tangential.x = -tangential.y;
                    tangential.y = newy;
                    tangential = tangential * p->modeA.tangentialAccel;

                    // (gravity + radial + tangential) * dt
                    tmp = radial + tangential + modeA.gravity;
                    tmp = tmp * dt;
                    p->modeA.dir = p->modeA.dir + tmp;
					if (_configName.length()>0)
					{
						if (_yCoordFlipped == -1)
						{
							 tmp = p->modeA.dir * dt;
						}
						else
						{
							 tmp = p->modeA.dir * -dt;
						}
					}
					else
					{
						 tmp = p->modeA.dir * dt;
					}
                    p->pos = p->pos + tmp;
                }

                // Mode B: radius movement
                else
                {
                    // Update the angle and radius of the particle.
                    p->modeB.angle += p->modeB.degreesPerSecond * dt;
                    p->modeB.radius += p->modeB.deltaRadius * dt;

                    p->pos.x = - cosf(p->modeB.angle) * p->modeB.radius;
                    p->pos.y = - sinf(p->modeB.angle) * p->modeB.radius;
                    if (_yCoordFlipped == 1)
                    {
                      p->pos.y = -p->pos.y;
                    }
				}

                // color
                p->color.r += (p->deltaColor.r * dt);
                p->color.g += (p->deltaColor.g * dt);
                p->color.b += (p->deltaColor.b * dt);
                p->color.a += (p->deltaColor.a * dt);

                // size
                p->size += (p->deltaSize * dt);
                p->size = MAX( 0, p->size );

                // angle
                p->rotation += (p->deltaRotation * dt);

                //
                // update values in quad
                //

                Vector2    newPos;

                if (_positionType == PositionType::FREE || _positionType == PositionType::RELATIVE)
                {
                    Vector2 diff = currentPosition - p->startPos;
                    newPos = p->pos - diff;
                }
                else
                {
                    newPos = p->pos;
                }

                // translate newPos to correct position, since matrix transform isn't performed in batchnode
                // don't update the particle with the new position information, it will interfere with the radius and tangential calculations
                if (_batchNode)
                {
                    newPos.x+=_position.x;
                    newPos.y+=_position.y;
                }

                updateQuadWithParticle(p, newPos);
                //updateParticleImp(self, updateParticleSel, p, newPos);

                // update particle counter
                ++_particleIdx;
            }
            else
            {
                // life < 0
                int currentIndex = p->atlasIndex;
                if( _particleIdx != _particleCount-1 )
                {
                    _particles[_particleIdx] = _particles[_particleCount-1];
                }
                if (_batchNode)
                {
                    //disable the switched particle
                    _batchNode->disableParticle(_atlasIndex+currentIndex);

                    //switch indexes
                    _particles[_particleCount-1].atlasIndex = currentIndex;
                }

                --_particleCount;

                if( _particleCount == 0 && _isAutoRemoveOnFinish )
                {
                    this->unscheduleUpdate();
                    _parent->removeChild(this, true);
                    return;
                }
            }
        } //while
        _transformSystemDirty = false;
    }

    // only update gl buffer when visible
    if (_visible && ! _batchNode)
    {
        postStep();
    }

    CC_PROFILER_STOP_CATEGORY(kProfilerCategoryParticles , "CCParticleSystem - update");
}

void ParticleSystem::updateWithNoTime(void)
{
    this->update(0.0f);
}

void ParticleSystem::updateQuadWithParticle(tParticle* particle, const Vector2& newPosition)
{
    CC_UNUSED_PARAM(particle);
    CC_UNUSED_PARAM(newPosition);
    // should be overridden
}

void ParticleSystem::postStep()
{
    // should be overridden
}

// ParticleSystem - Texture protocol
void ParticleSystem::setTexture(Texture2D* var)
{
    if (_texture != var)
    {
        CC_SAFE_RETAIN(var);
        CC_SAFE_RELEASE(_texture);
        _texture = var;
        updateBlendFunc();
    }
}

void ParticleSystem::updateBlendFunc()
{
    CCASSERT(! _batchNode, "Can't change blending functions when the particle is being batched");

    if(_texture)
    {
        bool premultiplied = _texture->hasPremultipliedAlpha();

        _opacityModifyRGB = false;

        if( _texture && ( _blendFunc.src == CC_BLEND_SRC && _blendFunc.dst == CC_BLEND_DST ) )
        {
            if( premultiplied )
            {
                _opacityModifyRGB = true;
            }
            else
            {
                _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
            }
        }
    }
}

Texture2D * ParticleSystem::getTexture() const
{
    return _texture;
}

// ParticleSystem - Additive Blending
void ParticleSystem::setBlendAdditive(bool additive)
{
    if( additive )
    {
        _blendFunc = BlendFunc::ADDITIVE;
    }
    else
    {
        if( _texture && ! _texture->hasPremultipliedAlpha() )
            _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
        else
            _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
    }
}

bool ParticleSystem::isBlendAdditive() const
{
    return( _blendFunc.src == GL_SRC_ALPHA && _blendFunc.dst == GL_ONE);
}

// ParticleSystem - Properties of Gravity Mode
void ParticleSystem::setTangentialAccel(float t)
{
    CCASSERT( _emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.tangentialAccel = t;
}

float ParticleSystem::getTangentialAccel() const
{
    CCASSERT( _emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.tangentialAccel;
}

void ParticleSystem::setTangentialAccelVar(float t)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.tangentialAccelVar = t;
}

float ParticleSystem::getTangentialAccelVar() const
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.tangentialAccelVar;
}

void ParticleSystem::setRadialAccel(float t)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.radialAccel = t;
}

float ParticleSystem::getRadialAccel() const
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.radialAccel;
}

void ParticleSystem::setRadialAccelVar(float t)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.radialAccelVar = t;
}

float ParticleSystem::getRadialAccelVar() const
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.radialAccelVar;
}

void ParticleSystem::setRotationIsDir(bool t)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.rotationIsDir = t;
}

bool ParticleSystem::getRotationIsDir() const
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.rotationIsDir;
}

void ParticleSystem::setGravity(const Vector2& g)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.gravity = g;
}

const Vector2& ParticleSystem::getGravity()
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.gravity;
}

void ParticleSystem::setSpeed(float speed)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.speed = speed;
}

float ParticleSystem::getSpeed() const
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.speed;
}

void ParticleSystem::setSpeedVar(float speedVar)
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    modeA.speedVar = speedVar;
}

float ParticleSystem::getSpeedVar() const
{
    CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
    return modeA.speedVar;
}

// ParticleSystem - Properties of Radius Mode
void ParticleSystem::setStartRadius(float startRadius)
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    modeB.startRadius = startRadius;
}

float ParticleSystem::getStartRadius() const
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    return modeB.startRadius;
}

void ParticleSystem::setStartRadiusVar(float startRadiusVar)
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    modeB.startRadiusVar = startRadiusVar;
}

float ParticleSystem::getStartRadiusVar() const
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    return modeB.startRadiusVar;
}

void ParticleSystem::setEndRadius(float endRadius)
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    modeB.endRadius = endRadius;
}

float ParticleSystem::getEndRadius() const
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    return modeB.endRadius;
}

void ParticleSystem::setEndRadiusVar(float endRadiusVar)
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    modeB.endRadiusVar = endRadiusVar;
}

float ParticleSystem::getEndRadiusVar() const
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    return modeB.endRadiusVar;
}

void ParticleSystem::setRotatePerSecond(float degrees)
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    modeB.rotatePerSecond = degrees;
}

float ParticleSystem::getRotatePerSecond() const
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    return modeB.rotatePerSecond;
}

void ParticleSystem::setRotatePerSecondVar(float degrees)
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    modeB.rotatePerSecondVar = degrees;
}

float ParticleSystem::getRotatePerSecondVar() const
{
    CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
    return modeB.rotatePerSecondVar;
}

bool ParticleSystem::isActive() const
{
    return _isActive;
}

int ParticleSystem::getTotalParticles() const
{
    return _totalParticles;
}

void ParticleSystem::setTotalParticles(int var)
{
    CCASSERT( var <= _allocatedParticles, "Particle: resizing particle array only supported for quads");
    _totalParticles = var;
}

const BlendFunc& ParticleSystem::getBlendFunc() const
{
    return _blendFunc;
}

void ParticleSystem::setBlendFunc(const BlendFunc &blendFunc)
{
    if( _blendFunc.src != blendFunc.src || _blendFunc.dst != blendFunc.dst ) {
        _blendFunc = blendFunc;
        this->updateBlendFunc();
    }
}

bool ParticleSystem::isAutoRemoveOnFinish() const
{
    return _isAutoRemoveOnFinish;
}

void ParticleSystem::setAutoRemoveOnFinish(bool var)
{
    _isAutoRemoveOnFinish = var;
}

// ParticleSystem - methods for batchNode rendering

ParticleBatchNode* ParticleSystem::getBatchNode(void) const
{
    return _batchNode;
}

void ParticleSystem::setBatchNode(ParticleBatchNode* batchNode)
{
    if( _batchNode != batchNode ) {

        _batchNode = batchNode; // weak reference

        if( batchNode ) {
            //each particle needs a unique index
            for (int i = 0; i < _totalParticles; i++)
            {
                _particles[i].atlasIndex=i;
            }
        }
    }
}

//don't use a transform matrix, this is faster
void ParticleSystem::setScale(float s)
{
    _transformSystemDirty = true;
    Node::setScale(s);
}

void ParticleSystem::setRotation(float newRotation)
{
    _transformSystemDirty = true;
    Node::setRotation(newRotation);
}

void ParticleSystem::setScaleX(float newScaleX)
{
    _transformSystemDirty = true;
    Node::setScaleX(newScaleX);
}

void ParticleSystem::setScaleY(float newScaleY)
{
    _transformSystemDirty = true;
    Node::setScaleY(newScaleY);
}

NS_CC_END


text:
<#
.SYNOPSIS
    Generates a list of random GUIDs
.DESCRIPTION
    The Get-RandomGuid cmdlet generates a list of random GUIDs based on the input number
.PARAMETER Number
    Number of GUIDs to generate.
.EXAMPLE
    Get-RandomGuid -Number 10
    Accept input data from the parameter
.EXAMPLE
    10 | Get-RandomGuid
    Accept input data from the pipeline
.INPUTS
    System.Int
.OUTPUTS
    System.Guid
#>

    [CmdletBinding(
        PositionalBinding = $true)]
    [OutputType([System.Guid])]
    Param (
        [Parameter(
            Mandatory = $true,
            Position = 0,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Int]
        $Number
    )

begin {
    Write-Verbose "Runbook started at time: $(Get-Date -Format R)"
}

process {
    1..$Number | ForEach-Object { New-Guid }
}

end {
    Write-Verbose "Runbook ended at time: $(Get-Date -Format R)"
}


text: {pymdgen:vaping.plugins.zeromq}


text:
package com.github.zxl0714.leveldb;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Assert;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

/**
 * Created by xiaolu on 4/30/15.
 */
public class TestTableBuilder {

    private static Options options;

    public static Slice reverse(Slice key) {
        byte[] r = new byte[key.size()];
        for (int i = key.size() - 1; i >= 0; i--) {
            r[key.size() - 1 - i] = key.data()[i];
        }
        return new Slice(r);
    }

    public static class ReverseKeyComparator implements Comparator {

        private BytewiseComparator cmp = new BytewiseComparator();

        @Override
        public int compare(Slice a, Slice b) {
            return cmp.compare(reverse(a), reverse(b));
        }

        @Override
        public String name() {
            return "leveldb.ReverseBytewiseComparator";
        }

        @Override
        public Slice findShortestSeparator(Slice start, Slice limit) {
            Slice s = reverse(start);
            Slice l = reverse(limit);
            return reverse(cmp.findShortestSeparator(s, l));
        }

        @Override
        public Slice findShortSuccessor(Slice key) {
            return reverse(cmp.findShortSuccessor(reverse(key)));
        }
    }

    public static class TestArgs {
        public boolean reverseCompare;
        public int restartInterval;
        public boolean useFilter;
        public TestArgs(boolean reverseCompare, int restartInterval, boolean useFilter) {
            this.reverseCompare = reverseCompare;
            this.restartInterval = restartInterval;
            this.useFilter = useFilter;
        }
    }

    public void init(TestArgs args) {
        options = new Options();
        options.compression = Options.CompressionType.NO_COMPRESSION;
        options.blockRestartInterval = args.restartInterval;
        if (args.reverseCompare) {
            options.comparator = new ReverseKeyComparator();
        }
        options.blockSize = 256;
        if (args.useFilter) {
            options.filterPolicy = new BloomFilterPolicy(10);
        }
    }

    public static class CompareKey implements java.util.Comparator<Map.Entry<Slice, Slice>> {

        private final Comparator cmp;

        public CompareKey(Comparator cmp) {
            this.cmp = cmp;
        }

        @Override
        public int compare(Map.Entry<Slice, Slice> v1, Map.Entry<Slice, Slice> v2) {
            return cmp.compare(v1.getKey(), v2.getKey());
        }
    }

    public String generateTable(Options options, Map<Slice, Slice> data) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        TableBuilder builder = new TableBuilder(options, out);
        List<Map.Entry<Slice, Slice>> dataList = Lists.newArrayList();
        dataList.addAll(data.entrySet());
        Collections.sort(dataList, new CompareKey(options.comparator));
        for (Map.Entry<Slice, Slice> entry : dataList) {
            builder.add(entry.getKey(), entry.getValue());
        }
        builder.finish();
        byte[] result = out.toByteArray();
        assertEquals(result.length, builder.fileSize());
        return Utils.escapeString(new Slice(result));
    }

    @Test
    public void testEmpty() throws IOException {
        Map<Slice, Slice> data = Maps.newHashMap();
        init(new TestArgs(false, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testEmpty.in")));
        init(new TestArgs(false, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testEmpty.in")));
        init(new TestArgs(false, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testEmpty.in")));
        init(new TestArgs(true, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testEmpty.in")));
        init(new TestArgs(true, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testEmpty.in")));
        init(new TestArgs(true, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testEmpty.in")));
    }

    @Test
    public void testSimpleEmptyKey() throws IOException {
        Map<Slice, Slice> data = Maps.newHashMap();
        data.put(new Slice(""), new Slice("v"));
        init(new TestArgs(false, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleEmptyKey.in")));
        init(new TestArgs(false, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleEmptyKey.in")));
        init(new TestArgs(false, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleEmptyKey.in")));
        init(new TestArgs(true, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleEmptyKey.in")));
        init(new TestArgs(true, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleEmptyKey.in")));
        init(new TestArgs(true, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleEmptyKey.in")));
    }

    @Test
    public void testSimpleMulti() throws IOException {
        Map<Slice, Slice> data = Maps.newTreeMap();
        data.put(new Slice("abc"), new Slice("v"));
        data.put(new Slice("abcd"), new Slice("v"));
        data.put(new Slice("ac"), new Slice("v2"));
        init(new TestArgs(false, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleMulti.in1")));
        init(new TestArgs(false, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleMulti.in2")));
        init(new TestArgs(false, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleMulti.in1")));
        init(new TestArgs(true, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleMulti.in3")));
        init(new TestArgs(true, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleMulti.in4")));
        init(new TestArgs(true, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleMulti.in3")));
    }

    @Test
    public void testSimpleSpecialKey() throws IOException {
        Map<Slice, Slice> data = Maps.newTreeMap();
        data.put(new Slice(new byte[]{(byte) 0xff, (byte) 0xff}), new Slice("v3"));
        init(new TestArgs(false, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleSpecialKey.in")));
        init(new TestArgs(true, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testSimpleSpecialKey.in")));
    }

    @Test
    public void testRandomized() throws IOException {
        Map<Slice, Slice> data = Maps.newTreeMap();
        Random rnd = new Random(306);
        for (int i = 0; i < 1000; i++) {
            Slice key = Utils.randomKey(rnd, rnd.skewed(4));
            Slice value = Utils.randomString(rnd, rnd.skewed(5));
            data.put(key, value);
        }
        init(new TestArgs(false, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testRandomized.in1")));
        init(new TestArgs(false, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testRandomized.in2")));
        init(new TestArgs(false, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testRandomized.in3")));
        init(new TestArgs(true, 16, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testRandomized.in4")));
        init(new TestArgs(true, 1, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testRandomized.in5")));
        init(new TestArgs(true, 1024, false));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testRandomized.in6")));
    }

    @Test
    public void testTableWithBloomFilterSimple() throws IOException {
        Map<Slice, Slice> data = Maps.newHashMap();
        data.put(new Slice("abc"), new Slice("v"));
        init(new TestArgs(false, 16, true));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testTableWithBloomFilterSimple.in")));
    }

    @Test
    public void testTableWithBloomFilterRandomized() throws IOException {
        Map<Slice, Slice> data = Maps.newTreeMap();
        Random rnd = new Random(306);
        for (int i = 0; i < 1000; i++) {
            Slice key = Utils.randomKey(rnd, rnd.skewed(4));
            Slice value = Utils.randomString(rnd, rnd.skewed(5));
            data.put(key, value);
        }
        init(new TestArgs(false, 16, true));
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testTableWithBloomFilterRandomized.in")));
    }

    @Test
    public void testWeirdTable() throws IOException {
        Map<Slice, Slice> data = Maps.newTreeMap();
        data.put(new Slice("k01"), new Slice("hello"));
        data.put(new Slice("k02"), new Slice("hello2"));
        byte[] v1 = new byte[10000];
        Arrays.fill(v1, (byte) 'x');
        data.put(new Slice("k03"), new Slice(v1));
        byte[] v2 = new byte[200000];
        Arrays.fill(v2, (byte) 'x');
        data.put(new Slice("k04"), new Slice(v2));
        byte[] v3 = new byte[300000];
        Arrays.fill(v3, (byte) 'x');
        data.put(new Slice("k05"), new Slice(v3));
        data.put(new Slice("k06"), new Slice("hello3"));
        byte[] v4 = new byte[100000];
        Arrays.fill(v4, (byte) 'x');
        data.put(new Slice("k07"), new Slice(v4));
        Options options = new Options();
        options.blockSize = 1024;
        options.compression = Options.CompressionType.NO_COMPRESSION;
        Assert.assertEquals(generateTable(options, data), Utils.readFile(TestTableBuilder.class.getResource("TableTest.testWeirdTable.in")));
    }
}


text:
package org.jetbrains.plugins.groovy.refactoring.rename;

import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.refactoring.RenameRefactoring;
import com.intellij.refactoring.openapi.impl.JavaRenameRefactoringImpl;
import com.intellij.refactoring.rename.RenameDialog;
import com.intellij.refactoring.rename.RenameHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod;
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;

/**
 * @author ven
 */
public class PropertyRenameHandler implements RenameHandler {
  public boolean isAvailableOnDataContext(DataContext dataContext) {
    return getProperty(dataContext) != null;
  }

  @Nullable
  private static GrField getProperty(DataContext dataContext) {
    final PsiElement element = (PsiElement)dataContext.getData(DataConstants.PSI_ELEMENT);
    if (element instanceof GrField && ((GrField)element).isProperty()) return (GrField)element;
    if (element instanceof GrAccessorMethod) return ((GrAccessorMethod)element).getProperty();
    return null;
  }

  public boolean isRenaming(DataContext dataContext) {
    return getProperty(dataContext) != null;
  }

  public void invoke(@NotNull Project project, Editor editor, PsiFile file, @Nullable DataContext dataContext) {
    final GrField property = getProperty(dataContext);
    assert property != null;
    new PropertyRenameDialog(property, editor).show();
  }

  private static class PropertyRenameDialog extends RenameDialog {

    private final GrField myProperty;

    protected PropertyRenameDialog(GrField property, final Editor editor) {
      super(property.getProject(), property, null, editor);
      myProperty = property;
    }

    protected void doAction() {
      final String newName = getNewName();
      final boolean searchInComments = isSearchInComments();
      doRename(newName, searchInComments);
      close(OK_EXIT_CODE);
    }

    private void doRename(String newName, boolean searchInComments) {
      final RenameRefactoring rename = new JavaRenameRefactoringImpl(myProperty.getProject(), myProperty, newName, searchInComments, false);

      final PsiMethod setter = myProperty.getSetter();
      if (setter != null && !(setter instanceof GrAccessorMethod)) {
        final String setterName = PropertyUtil.suggestSetterName(newName);
        rename.addElement(setter, setterName);
      }

      rename.run();
    }

    protected boolean areButtonsValid() {
      final String newName = getNewName();
      return super.areButtonsValid() && !GroovyRefactoringUtil.KEYWORDS.contains(newName);
    }

  }

  public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, @Nullable DataContext dataContext) {
    final GrField property = getProperty(dataContext);
    if (dataContext == null || property == null) return;
    Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
    new PropertyRenameDialog(property, editor).show();
  }
}


text:
use prelude::v1::*;

use ffi::CStr;
use io::{self, ErrorKind};
use libc;
use num::{Int, SignedInt};
use num;
use old_io::{self, IoResult, IoError};
use str;
use sys_common::mkerr_libc;

macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
    static $name: Helper<$m> = Helper {
        lock: ::sync::MUTEX_INIT,
        cond: ::sync::CONDVAR_INIT,
        chan: ::cell::UnsafeCell { value: 0 as *mut Sender<$m> },
        signal: ::cell::UnsafeCell { value: 0 },
        initialized: ::cell::UnsafeCell { value: false },
        shutdown: ::cell::UnsafeCell { value: false },
    };
) }

pub mod backtrace;
pub mod c;
pub mod condvar;
pub mod ext;
pub mod fd;
pub mod fs;  // support for std::old_io
pub mod fs2; // support for std::fs
pub mod helper_signal;
pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod pipe;
pub mod pipe2;
pub mod process;
pub mod process2;
pub mod rwlock;
pub mod stack_overflow;
pub mod sync;
pub mod tcp;
pub mod thread;
pub mod thread_local;
pub mod time;
pub mod timer;
pub mod tty;
pub mod udp;

pub mod addrinfo {
    pub use sys_common::net::get_host_addresses;
    pub use sys_common::net::get_address_name;
}

// FIXME: move these to c module
pub type sock_t = self::fs::fd_t;
pub type wrlen = libc::size_t;
pub type msglen_t = libc::size_t;
pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); }

pub fn last_error() -> IoError {
    decode_error_detailed(os::errno() as i32)
}

pub fn last_net_error() -> IoError {
    last_error()
}

extern "system" {
    fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char;
}

pub fn last_gai_error(s: libc::c_int) -> IoError {

    let mut err = decode_error(s);
    err.detail = Some(unsafe {
        let data = CStr::from_ptr(gai_strerror(s));
        str::from_utf8(data.to_bytes()).unwrap().to_string()
    });
    err
}

/// Convert an `errno` value into a high-level error variant and description.
pub fn decode_error(errno: i32) -> IoError {
    // FIXME: this should probably be a bit more descriptive...
    let (kind, desc) = match errno {
        libc::EOF => (old_io::EndOfFile, "end of file"),
        libc::ECONNREFUSED => (old_io::ConnectionRefused, "connection refused"),
        libc::ECONNRESET => (old_io::ConnectionReset, "connection reset"),
        libc::EPERM | libc::EACCES =>
            (old_io::PermissionDenied, "permission denied"),
        libc::EPIPE => (old_io::BrokenPipe, "broken pipe"),
        libc::ENOTCONN => (old_io::NotConnected, "not connected"),
        libc::ECONNABORTED => (old_io::ConnectionAborted, "connection aborted"),
        libc::EADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"),
        libc::EADDRINUSE => (old_io::ConnectionRefused, "address in use"),
        libc::ENOENT => (old_io::FileNotFound, "no such file or directory"),
        libc::EISDIR => (old_io::InvalidInput, "illegal operation on a directory"),
        libc::ENOSYS => (old_io::IoUnavailable, "function not implemented"),
        libc::EINVAL => (old_io::InvalidInput, "invalid argument"),
        libc::ENOTTY =>
            (old_io::MismatchedFileTypeForOperation,
             "file descriptor is not a TTY"),
        libc::ETIMEDOUT => (old_io::TimedOut, "operation timed out"),
        libc::ECANCELED => (old_io::TimedOut, "operation aborted"),
        libc::consts::os::posix88::EEXIST =>
            (old_io::PathAlreadyExists, "path already exists"),

        // These two constants can have the same value on some systems,
        // but different values on others, so we can't use a match
        // clause
        x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
            (old_io::ResourceUnavailable, "resource temporarily unavailable"),

        _ => (old_io::OtherIoError, "unknown error")
    };
    IoError { kind: kind, desc: desc, detail: None }
}

pub fn decode_error_detailed(errno: i32) -> IoError {
    let mut err = decode_error(errno);
    err.detail = Some(os::error_string(errno));
    err
}

pub fn decode_error_kind(errno: i32) -> ErrorKind {
    match errno as libc::c_int {
        libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
        libc::ECONNRESET => ErrorKind::ConnectionReset,
        libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
        libc::EPIPE => ErrorKind::BrokenPipe,
        libc::ENOTCONN => ErrorKind::NotConnected,
        libc::ECONNABORTED => ErrorKind::ConnectionAborted,
        libc::EADDRNOTAVAIL => ErrorKind::ConnectionRefused,
        libc::EADDRINUSE => ErrorKind::ConnectionRefused,
        libc::ENOENT => ErrorKind::FileNotFound,
        libc::EISDIR => ErrorKind::InvalidInput,
        libc::EINTR => ErrorKind::Interrupted,
        libc::EINVAL => ErrorKind::InvalidInput,
        libc::ENOTTY => ErrorKind::MismatchedFileTypeForOperation,
        libc::ETIMEDOUT => ErrorKind::TimedOut,
        libc::ECANCELED => ErrorKind::TimedOut,
        libc::consts::os::posix88::EEXIST => ErrorKind::PathAlreadyExists,

        // These two constants can have the same value on some systems,
        // but different values on others, so we can't use a match
        // clause
        x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
            ErrorKind::ResourceUnavailable,

        _ => ErrorKind::Other,
    }
}

#[inline]
pub fn retry<T, F> (mut f: F) -> T where
    T: SignedInt,
    F: FnMut() -> T,
{
    let one: T = Int::one();
    loop {
        let n = f();
        if n == -one && os::errno() == libc::EINTR as i32 { }
        else { return n }
    }
}

pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
    let one: T = Int::one();
    if t == -one {
        Err(io::Error::last_os_error())
    } else {
        Ok(t)
    }
}

pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
    where T: SignedInt, F: FnMut() -> T
{
    loop {
        match cvt(f()) {
            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
            other => return other,
        }
    }
}

pub fn ms_to_timeval(ms: u64) -> libc::timeval {
    libc::timeval {
        tv_sec: (ms / 1000) as libc::time_t,
        tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
    }
}

pub fn wouldblock() -> bool {
    let err = os::errno();
    err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32
}

pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> {
    let set = nb as libc::c_int;
    mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) }))
}

// nothing needed on unix platforms
pub fn init_net() {}


text:
layout: post
title: HDJ-2000 Awesomeness
categories: []
tags: []
status: publish
type: post
comments: true
published: true
meta: {}
---
![](/static/4f331d1f8754c7ec090e554a/50fe1c99e4b01c920a89f452/50fe1c99e4b01c920a89f4b1/1259290260137/iphone-20091126195240-1.jpg/1000w)What can I say but WOW! These headphones are amazing, I had the chance to head into Store DJ today and have a listen and the sound was pristine, brilliant highs and heart pumping lows. The isolation is another key point, you can barely hear youself talk when wearing these. The construction is sturdy and they are as light as the Sony MDR-V6's that I currently own (a big selling point).  The $400+ price tag is worth it and I can't wait to buy these.Amazing


text:
homedir = "#{node.devilryprodenv.homedir}"
pidfile = "#{homedir}/devilrybuild/var/supervisord.pid"
init_service_name = "#{node.devilryprodenv.supervisord_servicename}"

#
# Stop the Devilry services
# - ignored if this is the first time we run the recipe and the init-script
#   does not exist.
#
service "#{init_service_name}" do
  only_if = "test -e #{pidfile}"
  action [ :stop ]
end


text:
package com.dezorganizacja.bridge.view.text;

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

/**
 * Created by maciek on 13.04.15.
 */

public class OrdersHandler {
    private final Map<String, Command> menuEntries = new HashMap<>();
    {
        menuEntries.put("h", Commands.newCommand(this::help, "Help system"));
        menuEntries.put("help", Commands.newCommand(this::help, "Help system"));
        menuEntries.put("credits", Commands.newCommand(this::credits, "Credits"));
        menuEntries.put("menu", Commands.newCommand(this::print_menu, "Display the possible prompt commands"));
    }

    private void help(List<String> args) {
        print("Some help should go here");
    }

    private void credits(List<String> args) {
        print("Some credits should go here");
    }

    private void print_menu(List<String> args) {
        for(Map.Entry<String, Command> menuPosition : menuEntries.entrySet()) {
            print(menuPosition.getKey() + " - " + menuPosition.getValue().details());
        }
    }

    private void print(String toPrint) {
        System.out.println(toPrint);
    }

    public void dispatchOrder(String command, List<String> args) {
        if(!menuEntries.containsKey(command)) {
            print("No such command: " + command);
        } else {
            menuEntries.get(command).runCommand(args);
        }
    }
}


text:
define([
    'services/logger',
    'plugins/dialog',
    'services/unitofwork',
    'viewmodels/utilities/comparisonEdit'
],
  function (logger, dialog, unitofwork, comparisonEditViewModel) {

    var command = function (viewmodel) {
      var self = this;

      var cmd = ko.asyncCommand({
        execute: function (dataContext, complete) {

          var newEntity = unitofwork.comparisonRepository.create();
          dataContext.comparisons.push(newEntity);
          openEditor(newEntity);

          complete();
        },
        canExecute: function (isExecuting) {
          return true;
        }
      });

      function openEditor(entity) {
        var editViewModel = new comparisonEditViewModel(entity, entity.investmentPlan());

        return dialog.show(editViewModel);
      }

      return cmd;

    };

    return command;
  });


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.devcenter.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.core.management.SystemData;
import com.azure.resourcemanager.devcenter.models.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Represents a gallery. */
@Fluent
public final class GalleryInner extends ProxyResource {
    /*
     * Gallery properties.
     */
    @JsonProperty(value = "properties")
    private GalleryProperties innerProperties;

    /*
     * Azure Resource Manager metadata containing createdBy and modifiedBy information.
     */
    @JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY)
    private SystemData systemData;

    /** Creates an instance of GalleryInner class. */
    public GalleryInner() {
    }

    /**
     * Get the innerProperties property: Gallery properties.
     *
     * @return the innerProperties value.
     */
    private GalleryProperties innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information.
     *
     * @return the systemData value.
     */
    public SystemData systemData() {
        return this.systemData;
    }

    /**
     * Get the provisioningState property: The provisioning state of the resource.
     *
     * @return the provisioningState value.
     */
    public ProvisioningState provisioningState() {
        return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
    }

    /**
     * Get the galleryResourceId property: The resource ID of the backing Azure Compute Gallery.
     *
     * @return the galleryResourceId value.
     */
    public String galleryResourceId() {
        return this.innerProperties() == null ? null : this.innerProperties().galleryResourceId();
    }

    /**
     * Set the galleryResourceId property: The resource ID of the backing Azure Compute Gallery.
     *
     * @param galleryResourceId the galleryResourceId value to set.
     * @return the GalleryInner object itself.
     */
    public GalleryInner withGalleryResourceId(String galleryResourceId) {
        if (this.innerProperties() == null) {
            this.innerProperties = new GalleryProperties();
        }
        this.innerProperties().withGalleryResourceId(galleryResourceId);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Tests.Integration.Properties;

namespace Infrastructure.IntegrationTests.Helper
{
    class SQliteConnectionHelper
    {
        public static SQLiteConnection CreateMemory()
        {
            //inmemory https://www.connectionstrings.com/sqlite/
            const string connectionString = "Data Source=:memory:;Version=3;New=True;";

            var conn = new SQLiteConnection(connectionString);

            conn.Open();
            var createTable = conn.CreateCommand();
            createTable.CommandText = "Create table [test] (value nchar(5), id integer primary key)";
            createTable.ExecuteNonQuery();

            return conn;
        }

        internal static SQLiteConnection CreateMemoryPlaylistTable()
        {
            //inmemory https://www.connectionstrings.com/sqlite/
            const string connectionString = "Data Source=:memory:;Version=3;New=True;";

            var conn = new SQLiteConnection(connectionString);

            conn.Open();
            var createTable = conn.CreateCommand();
            var createTableText = Resources.test;
            createTable.CommandText = createTableText;
            createTable.ExecuteNonQuery();

            return conn;
        }

        public static SQLiteConnection CreateFile()
        {
            //file
            const string connectionString =
            @"Data Source=C:\Users\sns.B19\Documents\webplayer\Source\webplayer.db;Version=3;";

            var conn = new SQLiteConnection(connectionString);

            conn.Open();
            var createTable = conn.CreateCommand();
            createTable.CommandText = "Create table [test] (value nchar(5), id integer primary key)";
            createTable.ExecuteNonQuery();

            return conn;
        }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.Sphera.codesp.WebService.acessos;

import com.super_bits.modulosSB.Persistencia.dao.UtilSBPersistencia;
import com.super_bits.modulosSB.SBCore.ConfigGeral.SBCore;
import com.super_bits.modulosSB.SBCore.TratamentoDeErros.ErroSB;
import com.super_bits.modulosSB.SBCore.UtilGeral.UTilSBCoreInputs;
import com.super_bits.modulosSB.SBCore.UtilGeral.UtilSBCoreStrings;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.jws.WebService;

/**
 *
 *
 *
 * @author Alline Basile
 */
@WebService(endpointInterface = "com.Sphera.codesp.WebService.acessos.ItfWSAcessosMifare")
public class WSAcessosMifare implements ItfWSAcessosMifare {

    @Override
    public boolean informaAcesso(List<CartaoDeAcesso> acessos) {
        if (acessos == null) {
            return false;
        }
        for (CartaoDeAcesso cartao : acessos) {
            if (cartao.isAcessoPermitido()) {
                // UtilSBPersistencia.executaSQL("Insert Into Ca_historico(Codigo,Credencial,Controladora,Data,Evento,Descricao) Values(seqhist.nextval,'"+cartao.getCodigoMifar()+"','G12Can01',sysdate,1,'Dispositivo Móvel')");
                //10.1.2.16:1429/crednotify.asp?ctrl=G12Can01&hora=aaaammddhhmmss&type=0&cred=y
                List<String> resposta = UTilSBCoreInputs.getStringsByURL(null);

            } else {
                // UtilSBPersistencia.executaSQL("Insert Into Ca_historico(Codigo,Credencial,Controladora,Data,Evento,Descricao) Values(seqhist.nextval,'"+cartao.getCodigoMifar()+"','G12Can01',sysdate,801,'Dispositivo Móvel')");
                //10.1.2.16:1429/crednotify.asp?ctrl=G12Can01&hora=aaaammddhhmmss&type=1&cred=y
            }

        }
        return false;
    }

    @Override
    public List<CartaoDeAcesso> getCredenciaisOperador() {
        throw new UnsupportedOperationException("NAO FOI IMPLEMENTADO."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<CartaoDeAcesso> getCredenciaisTecnico() {
        throw new UnsupportedOperationException("NAO FOI IMPLEMENTADO."); //To change body of generated methods, choose Tools | Templates.
    }

    private enum TipoOrigem {

        CSV, BANCO, TESTES
    }

    private final TipoOrigem origem = TipoOrigem.TESTES;

    protected List<CartaoDeAcesso> getCartoesPorCSV(int pGate) {
        try {

            List<String> listaacesso = UTilSBCoreInputs.getStringsByURL("http://10.1.2.16:1429/credlist.asp?gate=" + Integer.toString(pGate));
            List<CartaoDeAcesso> resposta = new ArrayList<>();
            for (String linha : listaacesso) {
                resposta.add(buildCartaoDeAcessoByLinhaCSV(linha));
            }

            List<CartaoDeAcesso> respTeste = new ArrayList<>();
            respTeste.add(resposta.get(0));
            respTeste.add(resposta.get(1));
            respTeste.add(resposta.get(2));
            return resposta;
        } catch (Exception e) {
            SBCore.RelatarErro(ErroSB.TIPO_ERRO.ALERTA_PROGRAMADOR, "Erro ao obter a lista de acessos CSV.", e);
        }
        return null;
    }

    protected List<CartaoDeAcesso> getCartoesPorBanco(int pGate) {

        List<CartaoDeAcesso> resposta = new ArrayList<>();
        List<Object[]> registros = (List<Object[]>) UtilSBPersistencia.getListaRegistrosBySQL("SELECT lpad(D.CREDENCIAL, 8, '0')CREDENCIAL, A.NOME, A.ID_PESSOA ID FROM TB_PESSOA A, TB_PESSOA_EMPRESA B, TB_PESSOA_LOCAL C, TB_CREDENCIAL_PESSOA D, TB_EMPRESA E "
                + "WHERE A.ID_PESSOA = B.ID_PESSOA AND "
                + "B.ID_PESSOA_EMPRESA = C.ID_PESSOA_EMPRESA AND "
                + "A.ID_PESSOA = D.ID_PESSOA AND "
                + "B.ID_EMPRESA = E.ID_EMPRESA AND "
                + "A.FLAG_ATIVO = 5 AND "
                + "C.FLAG_ATIVO = 7 AND "
                + "D.FLAG_ATIVO = 21 AND "
                + "B.ID_EMPRESA <> 2 AND "
                + "E.FLAG_ATIVO = 6 AND "
                + "C.ID_LOCAL = " + pGate + " group by D.CREDENCIAL, A.NOME, A.ID_PESSOA "
                + "", 0);

        for (Object[] registro : registros) {
            resposta.add(buildCartaoDeAcessoByRegistroSQL(registro));
        }
        List<CartaoDeAcesso> respTeste = new ArrayList<>();
        respTeste.add(resposta.get(0));
        respTeste.add(resposta.get(1));
        respTeste.add(resposta.get(2));

        return resposta;
    }

    protected CartaoDeAcesso buildCartaoDeAcessoByLinhaCSV(String linha) {
        CartaoDeAcesso novoCartao = new CartaoDeAcesso();
        novoCartao.setCodigoMifar(linha.substring(0, 8));
        novoCartao.setNome(linha.substring(9, linha.length()));
        novoCartao.setAcessoPermitido(true);

        return novoCartao;
    }

    /**
     * Monta o Cartão de Acesso pelo registro de SQL seguindo o padrão:
     *
     * Codigo Mifare + Nome + Obeservação
     *
     * @param registro Registro Obtido via JQPL
     * @return Cartao De acesso
     */
    protected CartaoDeAcesso buildCartaoDeAcessoByRegistroSQL(Object[] registro) {
        CartaoDeAcesso novoCartao = new CartaoDeAcesso();
        int i = 0;
        for (Object campo : registro) {
            switch (i) {
                case 0:
                    novoCartao.setCodigoMifar(campo.toString());
                    break;
                case 1:
                    novoCartao.setNome(campo.toString());
                    break;
                case 2:
                    novoCartao.setUrlFoto("http://10.1.2.8/fotos/id" + UtilSBCoreStrings.getLpad(campo.toString(), 12, "0") + ".JPG");
                    break;

            }
            novoCartao.setAcessoPermitido(true);
            i++;
        }
        return novoCartao;
    }

    private String getMiFareAleatorio() {
        Random radom = new Random();
        int numeroTmp = 0;
        String numStr = new String();
        for (int i = 0; i < 10; i++) {
            numeroTmp = radom.nextInt(10);

            numStr = numStr + numeroTmp;
        }

        BigInteger toHex = new BigInteger(numStr, 10);
        return toHex.toString(16);

    }

    protected List<CartaoDeAcesso> getCartoesTestes() {

        List<CartaoDeAcesso> resp = new ArrayList<>();
        CartaoDeAcesso cartaoChaveiro = new CartaoDeAcesso();
        cartaoChaveiro.setCodigoMifar("D9F5EA6B");
        cartaoChaveiro.setNome("Chaveiro Azul da Silva");
        cartaoChaveiro.setUrlFoto("http://sspp.codesp.com.br/fotos/id000000100465.jpg");
        cartaoChaveiro.setAcessoPermitido(true);

        for (int i = 0; i < 10; i++) {
            CartaoDeAcesso novoCartao = new CartaoDeAcesso();
            String mifairAleatorio = getMiFareAleatorio();
            novoCartao.setCodigoMifar(mifairAleatorio);
            novoCartao.setNome("Teste" + mifairAleatorio);
            novoCartao.setAcessoPermitido(true);
            resp.add(novoCartao);
        }
        CartaoDeAcesso cartaoelemento = new CartaoDeAcesso();
        cartaoelemento.setCodigoMifar("B6D1D67A");
        cartaoelemento.setNome("Alline Basile");
        cartaoelemento.setUrlFoto("http://sspp.codesp.com.br/fotos/id000000100465.jpg");
        cartaoelemento.setAcessoPermitido(true);

        CartaoDeAcesso cartaoelemento2 = new CartaoDeAcesso();
        cartaoelemento2.setCodigoMifar("041b32d4");
        cartaoelemento2.setNome("cartao bug oj");
        cartaoelemento2.setUrlFoto("http://sspp.codesp.com.br/fotos/id000000100465.jpg");
        cartaoelemento2.setAcessoPermitido(true);

        CartaoDeAcesso chico = new CartaoDeAcesso();
        chico.setCodigoMifar("1896303E");
        chico.setNome("Francisco Sphera Security ");
        chico.setUrlFoto("http://www.fotossaopaulo.com.br/clubes-de-sao-paulo/Santos/Santos1.jpg");
        chico.setAcessoPermitido(true);
        resp.add(chico);

        CartaoDeAcesso joaquim = new CartaoDeAcesso();
        joaquim.setCodigoMifar("40660915");
        joaquim.setNome("Joaquim Da Silva Marques Neto");
        joaquim.setUrlFoto("http://sspp.codesp.com.br/fotos/id000000039716.JPG");
        resp.add(joaquim);
        resp.add(cartaoelemento);
        resp.add(cartaoelemento2);
        resp.add(cartaoChaveiro);
        return resp;
    }

    @Override
    public List<CartaoDeAcesso> getAcessosPermitidosPorGate(int pGate) {
        try {
            switch (origem) {
                case BANCO:
                    return getCartoesPorBanco(pGate);
                case CSV:
                    return getCartoesPorCSV(pGate);
                case TESTES:
                    return getCartoesTestes();
            }

        } catch (Exception e) {
            SBCore.RelatarErro(ErroSB.TIPO_ERRO.ALERTA_PROGRAMADOR, "Erro ao obter a lista de acessos permitidos por gate.", e);
        }
        return null;
    }

    @Override
    public CartaoDeAcesso acessoPermitido(String pCodigoMifare, int pGate) {
        Object[] resposta = (Object[]) UtilSBPersistencia.getRegistroBySQL("SELECT A.NOME,A.ID_PESSOA ID FROM TB_PESSOA A, TB_PESSOA_EMPRESA B, TB_PESSOA_LOCAL C, TB_CREDENCIAL_PESSOA D "
                + "WHERE A.ID_PESSOA = B.ID_PESSOA AND "
                + "B.ID_PESSOA_EMPRESA = C.ID_PESSOA_EMPRESA AND "
                + "A.ID_PESSOA = D.ID_PESSOA AND "
                + "A.FLAG_ATIVO = 5 AND "
                + "C.FLAG_ATIVO = 7 AND "
                + "D.FLAG_ATIVO = 21 AND "
                + "D.CREDENCIAL = '" + pCodigoMifare + "'  AND "
                + "C.ID_LOCAL =  " + pGate + " group by D.CREDENCIAL, A.NOME, A.ID_PESSOA "
                + " ");
        System.out.println("resposta" + resposta);
        if (resposta != null) {
            CartaoDeAcesso cartao = new CartaoDeAcesso();
            cartao.setNome(resposta[0].toString());
            BigDecimal idUsuario = (BigDecimal) resposta[1];
            cartao.setUrlFoto("http://10.1.2.8/fotos/id" + UtilSBCoreStrings.getLpad(idUsuario.toString(), 12, "0") + ".JPG");
            return cartao;
        } else {
            return null;
        }

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/root_layout"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:clickable="true"
              android:gravity="center"
              android:orientation="vertical"
              android:padding="@dimen/widget_margin">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="0dip"
            android:gravity="center"
            android:baselineAligned="false"
            android:orientation="horizontal">

        <LinearLayout
                android:id="@+id/digit_0ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_0"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="0"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

        <LinearLayout
                android:id="@+id/digit_1ll"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_1"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="1"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

        <LinearLayout
                android:id="@+id/digit_2ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_2"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="2"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="0dip"
            android:gravity="center"
            android:baselineAligned="false"
            android:orientation="horizontal">

        <LinearLayout
                android:id="@+id/digit_9ll"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_9"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="9"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

        <LinearLayout
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:visibility="invisible"
                android:gravity="center">

        </LinearLayout>

        <LinearLayout
                android:id="@+id/digit_3ll"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_3"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="3"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="0dip"
            android:gravity="center"
            android:baselineAligned="false"
            android:orientation="horizontal">

        <LinearLayout
                android:id="@+id/digit_8ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_8"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="8"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

        <LinearLayout
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:visibility="invisible"
                android:gravity="center">

        </LinearLayout>

        <LinearLayout
                android:id="@+id/digit_4ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_4"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="4"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="0dip"
            android:gravity="center"
            android:baselineAligned="false"
            android:orientation="horizontal">

        <LinearLayout
                android:id="@+id/digit_7ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_7"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="7"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

        <LinearLayout
                android:id="@+id/digit_6ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_6"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="6"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

        <LinearLayout
                android:id="@+id/digit_5ll"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/digit_spacing"
                android:background="@color/default_digit_border_color"
                android:gravity="center">

            <TextView
                    android:id="@+id/digit_5"
                    style="@android:style/TextAppearance.Medium"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_margin="@dimen/digit_border_width"
                    android:gravity="center"
                    android:shadowColor="@color/default_digit_shadow_color"
                    android:shadowDx="@integer/default_digit_shadow_dx"
                    android:shadowDy="@integer/default_digit_shadow_dy"
                    android:shadowRadius="@integer/default_digit_shadow_radius"
                    android:text="5"
                    android:textColor="@color/default_digit_color"
                    android:textSize="@dimen/digit_font_size"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>


text:
package ch.ntb.inf.deep.comp.targettest.conditions;

import ch.ntb.inf.junitTarget.MaxErrors;
import ch.ntb.inf.junitTarget.Suite;

@Suite({ ConditionTest.class, LongCompTest.class, FloatDoubleCompTest.class })
@MaxErrors(100)
public class ConditionsSuite {

}


text:
        <sm-checkbox model="config.$selectAll" name="{{config.$tableName}}-select-all"></sm-checkbox>

            Sort

                            {{sortCol.title}}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Morris & Finley, Am. Midl. Nat. 77: 201 (1967)

#### Original name
Dictyocatenulata alba Finley & E.F. Morris, 1967

### Remarks
null