text:
#ifndef __D3D9HLSLProgram_H__
#define __D3D9HLSLProgram_H__

#include "OgreD3D9Prerequisites.h"
#include "OgreHighLevelGpuProgram.h"

#include <d3dx9.h>

namespace Ogre {
    /** Specialisation of HighLevelGpuProgram to provide support for D3D9
        High-Level Shader Language (HLSL).

        Note that the syntax of D3D9 HLSL is identical to nVidia's Cg language, therefore
        unless you know you will only ever be deploying on Direct3D, or you have some specific
        reason for not wanting to use the Cg plugin, I suggest you use Cg instead since that
        can produce programs for OpenGL too.
    */
    class _OgreD3D9Export D3D9HLSLProgram : public HighLevelGpuProgram
    {
    public:
        /// Command object for setting target assembler
        class CmdTarget : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };
        /// Command object for setting matrix packing in column-major order
        class CmdColumnMajorMatrices : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };
        /// Command object for setting optimisation level
        class CmdOptimisation : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /// Command object for getting/setting micro code
        class CmdMicrocode : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /// Command object for getting/setting assembler code
        class CmdAssemblerCode : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /// Command object for enabling backwards compatibility
        class CmdBackwardsCompatibility : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

    protected:

        static CmdTarget msCmdTarget;
        static CmdColumnMajorMatrices msCmdColumnMajorMatrices;
        static CmdOptimisation msCmdOptimisation;
        static CmdMicrocode msCmdMicrocode;
        static CmdAssemblerCode msCmdAssemblerCode;
        static CmdBackwardsCompatibility msCmdBackwardsCompatibility;

        void prepareImpl();
        void loadFromSource() {} // all done in prepare
        /** Internal method for creating an appropriate low-level program from this
        high-level program, must be implemented by subclasses. */
        void createLowLevelImpl(void);
        /// Internal unload implementation, must be implemented by subclasses
        void unloadHighLevelImpl(void);
        /// Populate the passed parameters with name->index map, must be overridden
        void buildConstantDefinitions() override;

        // Recursive utility method for buildParamNameMap
        void processParamElement(LPD3DXCONSTANTTABLE pConstTable, D3DXHANDLE parent, String prefix, unsigned int index);
        void populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const;

        bool mColumnMajorMatrices;
        bool mBackwardsCompatibility;

        LPD3DXBUFFER mMicroCode;

        GpuConstantDefinitionMap mParametersMap;
        size_t mParametersMapSizeAsBuffer;

    public:
        LPD3DXBUFFER getMicroCode();
    public:
        /// Shader optimisation level
        enum OptimisationLevel
        {
            /// default - no optimisation in debug mode, OPT_1 in release mode
            OPT_DEFAULT,
            /// No optimisation
            OPT_NONE,
            /// Optimisation level 0
            OPT_0,
            /// Optimisation level 1
            OPT_1,
            /// Optimisation level 2
            OPT_2,
            /// Optimisation level 3
            OPT_3
        };
    protected:
        OptimisationLevel mOptimisationLevel;

        /** Gets the microcode from the microcode cache. */
        void getMicrocodeFromCache(uint32 id);
        /** Compiles the microcode from the program source. */
        void compileMicrocode(void);
        void addMicrocodeToCache(uint32 id);
    public:
        D3D9HLSLProgram(ResourceManager* creator, const String& name, ResourceHandle handle,
            const String& group, bool isManual, ManualResourceLoader* loader);
        ~D3D9HLSLProgram();

        /** Sets the entry point for this program ie the first method called. */
        void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; }
        /** Gets the entry point defined for this program. */
        const String& getEntryPoint(void) const { return mEntryPoint; }
        /** Sets the shader target to compile down to, e.g. 'vs_1_1'. */
        void setTarget(const String& target);
        /** Gets the shader target to compile down to, e.g. 'vs_1_1'. */
        const String& getTarget(void) const;
        /** Sets whether matrix packing in column-major order. */
        void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; }
        /** Gets whether matrix packed in column-major order. */
        bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; }
        /** Sets whether backwards compatibility mode should be enabled. */
        void setBackwardsCompatibility(bool compat) { mBackwardsCompatibility = compat; }
        /** Gets whether backwards compatibility mode should be enabled. */
        bool getBackwardsCompatibility(void) const { return mBackwardsCompatibility; }
        /** Sets the optimisation level to use.
        @param opt Optimisation level
        */
        void setOptimisationLevel(OptimisationLevel opt) { mOptimisationLevel = opt; }

        /** Gets the optimisation level to use. */
        OptimisationLevel getOptimisationLevel() const { return mOptimisationLevel; }

        /// Overridden from GpuProgram
        GpuProgramParametersSharedPtr createParameters(void);
        /// Overridden from GpuProgram
        const String& getLanguage(void) const;
    };
}

#endif


text:
<?php

declare(strict_types=1);

namespace App\Service\FilesystemAdapter;

use App\Entity\User;
use App\Service\FilesystemAdapter\EnhancedFilesystem\EnhancedFilesystem;
use App\Service\FilesystemAdapter\EnhancedFilesystem\EnhancedFilesystemInterface;
use App\Service\FilesystemAdapter\EnhancedFlysystemAdapter\EnhancedSftpAdapter;
use League\Flysystem\PhpseclibV2\SftpConnectionProvider;

class Sftp extends AbstractCachedFilesystemAdapter implements FilesystemAdapterInterface
{
    /**
     * @var string
     */
    private const NAME = 'sftp';

    private readonly string $host;

    private readonly int $port;

    private readonly string $username;

    private readonly string $password;

    private readonly string $rootPath;

    private ?EnhancedFilesystemInterface $filesystem = null;

    public function __construct(
        int $fsCacheDuration,
        string $fsSftpHost,
        int $fsSftpPort,
        string $fsSftpUsername,
        string $fsSftpPassword,
        string $fsSftpRootPath
    ) {
        parent::__construct($fsCacheDuration);

        $this->host = $fsSftpHost;
        $this->port = $fsSftpPort;
        $this->username = $fsSftpUsername;
        $this->password = $fsSftpPassword;
        $this->rootPath = $fsSftpRootPath;
    }

    /**
     * {@inheritdoc}
     */
    final public static function getName(): string
    {
        return self::NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function getFilesystem(User $user): EnhancedFilesystemInterface
    {
        if ($this->filesystem === null) {
            $adapter = $this->cachedAdapter(
                new EnhancedSftpAdapter(
                    new SftpConnectionProvider(
                        $this->host,
                        $this->username,
                        $this->password,
                        null,
                        null,
                        $this->port,
                    ),
                    $this->rootPath,
                ),
                $user
            );

            $this->filesystem = new EnhancedFilesystem(
                $adapter,
                [
                    'disable_asserts' => true,
                ]
            );
        }

        return $this->filesystem;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package rest

import (
	"errors"
	"fmt"
	"net/http"

	"gopkg.in/ns1/ns1-go.v2/rest/model/account"
)

// APIKeysService handles 'account/apikeys' endpoint.
type APIKeysService service

// List returns all api keys in the account.
//
// NS1 API docs: https://ns1.com/api/#apikeys-get
func (s *APIKeysService) List() ([]*account.APIKey, *http.Response, error) {
	req, err := s.client.NewRequest("GET", "account/apikeys", nil)
	if err != nil {
		return nil, nil, err
	}

	kl := []*account.APIKey{}
	resp, err := s.client.Do(req, &kl)
	if err != nil {
		return nil, resp, err
	}

	return kl, resp, nil
}

// Get returns details of an api key, including permissions, for a single API Key.
// Note: do not use the API Key itself as the keyid in the URL — use the id of the key.
//
// NS1 API docs: https://ns1.com/api/#apikeys-id-get
func (s *APIKeysService) Get(keyID string) (*account.APIKey, *http.Response, error) {
	path := fmt.Sprintf("account/apikeys/%s", keyID)

	req, err := s.client.NewRequest("GET", path, nil)
	if err != nil {
		return nil, nil, err
	}

	var a account.APIKey
	resp, err := s.client.Do(req, &a)
	if err != nil {
		switch err.(type) {
		case *Error:
			if err.(*Error).Message == "unknown api key" {
				return nil, resp, ErrKeyMissing
			}

		}
		return nil, resp, err
	}

	return &a, resp, nil
}

// Create takes a *APIKey and creates a new account apikey.
//
// NS1 API docs: https://ns1.com/api/#apikeys-put
func (s *APIKeysService) Create(a *account.APIKey) (*http.Response, error) {
	var (
		req *http.Request
		err error
	)

	// If this is DDI then the permissions need to be transformed to DDI-compatible permissions.
	if s.client.DDI && a != nil {
		ddiAPIKey := apiKeyToDDIAPIKey(a)
		req, err = s.client.NewRequest("PUT", "account/apikeys", ddiAPIKey)
		if err != nil {
			return nil, err
		}
	} else {
		req, err = s.client.NewRequest("PUT", "account/apikeys", a)
		if err != nil {
			return nil, err
		}
	}

	// Update account fields with data from api(ensure consistent)
	resp, err := s.client.Do(req, &a)
	if err != nil {
		switch err.(type) {
		case *Error:
			if err.(*Error).Message == fmt.Sprintf("api key with name \"%s\" exists", a.Name) {
				return resp, ErrKeyExists
			}
		}
		return resp, err
	}

	return resp, nil
}

// Update changes the name or access rights for an API Key.
//
// NS1 API docs: https://ns1.com/api/#apikeys-id-post
func (s *APIKeysService) Update(a *account.APIKey) (*http.Response, error) {
	path := fmt.Sprintf("account/apikeys/%s", a.ID)

	var (
		req *http.Request
		err error
	)

	// If this is DDI then the permissions need to be transformed to DDI-compatible permissions.
	if s.client.DDI && a != nil {
		ddiAPIKey := apiKeyToDDIAPIKey(a)
		req, err = s.client.NewRequest("POST", path, ddiAPIKey)
		if err != nil {
			return nil, err
		}
	} else {
		req, err = s.client.NewRequest("POST", path, a)
		if err != nil {
			return nil, err
		}
	}

	// Update apikey fields with data from api(ensure consistent)
	resp, err := s.client.Do(req, &a)
	if err != nil {
		switch err.(type) {
		case *Error:
			if err.(*Error).Message == "unknown api key" {
				return resp, ErrKeyMissing
			}
		}
		return resp, err
	}

	return resp, nil
}

// Delete deletes an apikey.
//
// NS1 API docs: https://ns1.com/api/#apikeys-id-delete
func (s *APIKeysService) Delete(keyID string) (*http.Response, error) {
	path := fmt.Sprintf("account/apikeys/%s", keyID)

	req, err := s.client.NewRequest("DELETE", path, nil)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.Do(req, nil)
	if err != nil {
		switch err.(type) {
		case *Error:
			if err.(*Error).Message == "unknown api key" {
				return resp, ErrKeyMissing
			}
		}
		return resp, err
	}

	return resp, nil
}

var (
	// ErrKeyExists bundles PUT create error.
	ErrKeyExists = errors.New("key already exists")
	// ErrKeyMissing bundles GET/POST/DELETE error.
	ErrKeyMissing = errors.New("key does not exist")
)

func apiKeyToDDIAPIKey(k *account.APIKey) *ddiAPIKey {
	ddiAPIKey := &ddiAPIKey{
		ID:                k.ID,
		Key:               k.Key,
		LastAccess:        k.LastAccess,
		Name:              k.Name,
		TeamIDs:           k.TeamIDs,
		IPWhitelist:       k.IPWhitelist,
		IPWhitelistStrict: k.IPWhitelistStrict,
		Permissions: ddiPermissionsMap{
			DNS:  k.Permissions.DNS,
			Data: k.Permissions.Data,
			Account: permissionsDDIAccount{
				ManageUsers:           k.Permissions.Account.ManageUsers,
				ManageTeams:           k.Permissions.Account.ManageTeams,
				ManageApikeys:         k.Permissions.Account.ManageApikeys,
				ManageAccountSettings: k.Permissions.Account.ManageAccountSettings,
				ViewActivityLog:       k.Permissions.Account.ViewActivityLog,
			},
		},
	}

	if k.Permissions.Security != nil {
		ddiAPIKey.Permissions.Security = permissionsDDISecurity(*k.Permissions.Security)
	}

	if k.Permissions.DHCP != nil {
		ddiAPIKey.Permissions.DHCP = *k.Permissions.DHCP
	}

	if k.Permissions.IPAM != nil {
		ddiAPIKey.Permissions.IPAM = *k.Permissions.IPAM
	}

	return ddiAPIKey
}


text:
/**
 * @author AnnatarHe
 * @email iamhele1994@gmail.com
 * @date 2016.10.22
 */

export const MENU_STATUS = 'global/MENU_STATUS'


text:
#include "gdal_pam.h"
#include "nitflib.h"
#include "ogr_spatialref.h"
#include "gdal_proxy.h"
#include <map>

CPLErr NITFSetColorInterpretation( NITFImage *psImage,
                                   int nBand,
                                   GDALColorInterp eInterp );

/* Unused in normal builds. Caller code in nitfdataset.cpp is protected by #ifdef ESRI_BUILD */
#ifdef ESRI_BUILD
/* -------------------------------------------------------------------- */
/*      Functions in nitf_gcprpc.cpp.                                   */
/* -------------------------------------------------------------------- */

void NITFDensifyGCPs( GDAL_GCP **psGCPs, int *pnGCPCount );
void NITFUpdateGCPsWithRPC( NITFRPC00BInfo *psRPCInfo,
                            GDAL_GCP       *psGCPs,
                            int            *pnGCPCount );
#endif

/************************************************************************/
/* ==================================================================== */
/*                              NITFDataset                             */
/* ==================================================================== */
/************************************************************************/

class NITFRasterBand;
class NITFWrapperRasterBand;

class NITFDataset final: public GDALPamDataset
{
    friend class NITFRasterBand;
    friend class NITFWrapperRasterBand;

    NITFFile    *psFile;
    NITFImage   *psImage;

    GDALDataset *poJ2KDataset;
    int         bJP2Writing;

    GDALDataset *poJPEGDataset;

    int         bGotGeoTransform;
    double      adfGeoTransform[6];

    char        *pszProjection;

    int         nGCPCount;
    GDAL_GCP    *pasGCPList;
    char        *pszGCPProjection;

    GDALMultiDomainMetadata oSpecialMD;

#ifdef ESRI_BUILD
    void         InitializeNITFDESMetadata();
    void         InitializeNITFDESs();
    void         InitializeNITFTREs();
#endif
    void         InitializeNITFMetadata();
    void         InitializeCGMMetadata();
    void         InitializeTextMetadata();
    void         InitializeTREMetadata();

    GIntBig     *panJPEGBlockOffset;
    GByte       *pabyJPEGBlock;
    int          nQLevel;

    int          ScanJPEGQLevel( GUIntBig *pnDataStart, bool *pbError );
    CPLErr       ScanJPEGBlocks();
    CPLErr       ReadJPEGBlock( int, int );
    void         CheckGeoSDEInfo();
    char**       AddFile(char **papszFileList, const char* EXTENSION, const char* extension);

    int          nIMIndex;
    CPLString    osNITFFilename;

    CPLString    osRSetVRT;
    int          CheckForRSets( const char *pszFilename, char** papszSiblingFiles );

    char       **papszTextMDToWrite;
    char       **papszCgmMDToWrite;

    int          bInLoadXML;

    CPLString    m_osRPCTXTFilename;

    int          bExposeUnderlyingJPEGDatasetOverviews;
    int          ExposeUnderlyingJPEGDatasetOverviews() const { return bExposeUnderlyingJPEGDatasetOverviews; }

  protected:
    virtual int         CloseDependentDatasets() override;

  public:
                 NITFDataset();
    virtual ~NITFDataset();

    virtual CPLErr AdviseRead( int nXOff, int nYOff, int nXSize, int nYSize,
                               int nBufXSize, int nBufYSize,
                               GDALDataType eDT,
                               int nBandCount, int *panBandList,
                               char **papszOptions ) override;

    virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int,
                              void *, int, int, GDALDataType,
                              int, int *,
                              GSpacing nPixelSpace, GSpacing nLineSpace,
                              GSpacing nBandSpace,
                              GDALRasterIOExtraArg* psExtraArg ) override;

    virtual const char *GetProjectionRef() override;
    virtual CPLErr SetProjection( const char * ) override;
    virtual CPLErr GetGeoTransform( double * ) override;
    virtual CPLErr SetGeoTransform( double * ) override;
    virtual CPLErr SetGCPs( int nGCPCount, const GDAL_GCP *pasGCPList,
                            const char *pszGCPProjection ) override;

    virtual int    GetGCPCount() override;
    virtual const char *GetGCPProjection() override;
    virtual const GDAL_GCP *GetGCPs() override;
    virtual char **GetFileList() override;

    virtual char      **GetMetadataDomainList() override;
    virtual char      **GetMetadata( const char * pszDomain = "" ) override;
    virtual const char *GetMetadataItem( const char * pszName,
                                         const char * pszDomain = "" ) override;
    virtual void   FlushCache() override;
    virtual CPLErr IBuildOverviews( const char *, int, int *,
                                    int, int *, GDALProgressFunc, void * ) override;

    static int          Identify( GDALOpenInfo * );
    static GDALDataset *OpenInternal( GDALOpenInfo *, GDALDataset *poWritableJ2KDataset,
                              int bOpenForCreate);
    static GDALDataset *Open( GDALOpenInfo * );
    static GDALDataset *
    NITFCreateCopy( const char *pszFilename, GDALDataset *poSrcDS,
                    int bStrict, char **papszOptions,
                    GDALProgressFunc pfnProgress, void * pProgressData );
    static GDALDataset *
             NITFDatasetCreate( const char *pszFilename,
                                int nXSize, int nYSize, int nBands,
                                GDALDataType eType, char **papszOptions );
};

/************************************************************************/
/* ==================================================================== */
/*                            NITFRasterBand                             */
/* ==================================================================== */
/************************************************************************/

class NITFRasterBand final: public GDALPamRasterBand
{
    friend class NITFDataset;

    NITFImage   *psImage;

    GDALColorTable *poColorTable;

    GByte       *pUnpackData;

    int          bScanlineAccess;

  public:
                   NITFRasterBand( NITFDataset *, int );
    virtual ~NITFRasterBand();

    virtual CPLErr IReadBlock( int, int, void * ) override;
    virtual CPLErr IWriteBlock( int, int, void * ) override;

    virtual GDALColorInterp GetColorInterpretation() override;
    virtual CPLErr SetColorInterpretation( GDALColorInterp ) override;
    virtual GDALColorTable *GetColorTable() override;
    virtual CPLErr SetColorTable( GDALColorTable * ) override;
    virtual double GetNoDataValue( int *pbSuccess = nullptr ) override;

    void Unpack(GByte* pData);
};

/************************************************************************/
/* ==================================================================== */
/*                        NITFProxyPamRasterBand                        */
/* ==================================================================== */
/************************************************************************/

/* This class is potentially of general interest and could be moved to gdal_proxy.h */
/* We don't proxy all methods. Generally speaking, the getters go to PAM first and */
/* then to the underlying band if no value exist in PAM. The setters aren't */
/* overridden, so they go to PAM */

class NITFProxyPamRasterBand: public GDALPamRasterBand
{
    private:
        std::map<CPLString, char**> oMDMap;

    protected:
        virtual GDALRasterBand* RefUnderlyingRasterBand() = 0;
        virtual void UnrefUnderlyingRasterBand(GDALRasterBand* poUnderlyingRasterBand);

        virtual CPLErr IReadBlock( int, int, void * ) override;
        virtual CPLErr IWriteBlock( int, int, void * ) override;
        virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int,
                                void *, int, int, GDALDataType,
                                GSpacing nPixelSpace, GSpacing nLineSpace,
                                GDALRasterIOExtraArg* psExtraArg) override;

    public:
        virtual ~NITFProxyPamRasterBand();

        virtual char      **GetMetadata( const char * pszDomain = ""  ) override;
        /*virtual CPLErr      SetMetadata( char ** papszMetadata,
                                        const char * pszDomain = ""  );*/
        virtual const char *GetMetadataItem( const char * pszName,
                                            const char * pszDomain = "" ) override;
        /*virtual CPLErr      SetMetadataItem( const char * pszName,
                                            const char * pszValue,
                                            const char * pszDomain = "" );*/
        virtual CPLErr FlushCache() override;
        /*virtual char **GetCategoryNames();*/
        virtual double GetNoDataValue( int *pbSuccess = nullptr ) override;
        virtual double GetMinimum( int *pbSuccess = nullptr ) override;
        virtual double GetMaximum(int *pbSuccess = nullptr ) override;
        /*virtual double GetOffset( int *pbSuccess = NULL );
        virtual double GetScale( int *pbSuccess = NULL );*/
        /*virtual const char *GetUnitType();*/
        virtual GDALColorInterp GetColorInterpretation() override;
        virtual GDALColorTable *GetColorTable() override;
        virtual CPLErr Fill(double dfRealValue, double dfImaginaryValue = 0) override;

        /*
        virtual CPLErr SetCategoryNames( char ** );
        virtual CPLErr SetNoDataValue( double );
        virtual CPLErr SetColorTable( GDALColorTable * );
        virtual CPLErr SetColorInterpretation( GDALColorInterp );
        virtual CPLErr SetOffset( double );
        virtual CPLErr SetScale( double );
        virtual CPLErr SetUnitType( const char * );
        */

        virtual CPLErr GetStatistics( int bApproxOK, int bForce,
                                    double *pdfMin, double *pdfMax,
                                    double *pdfMean, double *padfStdDev ) override;
        virtual CPLErr ComputeStatistics( int bApproxOK,
                                        double *pdfMin, double *pdfMax,
                                        double *pdfMean, double *pdfStdDev,
                                        GDALProgressFunc, void *pProgressData ) override;
        /*virtual CPLErr SetStatistics( double dfMin, double dfMax,
                                    double dfMean, double dfStdDev );*/
        virtual CPLErr ComputeRasterMinMax( int, double* ) override;

        virtual int HasArbitraryOverviews() override;
        virtual int GetOverviewCount() override;
        virtual GDALRasterBand *GetOverview(int) override;
        virtual GDALRasterBand *GetRasterSampleOverview( GUIntBig ) override;
        virtual CPLErr BuildOverviews( const char *, int, int *,
                                    GDALProgressFunc, void * ) override;

        virtual CPLErr AdviseRead( int nXOff, int nYOff, int nXSize, int nYSize,
                                int nBufXSize, int nBufYSize,
                                GDALDataType eDT, char **papszOptions ) override;

        /*virtual CPLErr  GetHistogram( double dfMin, double dfMax,
                            int nBuckets, GUIntBig * panHistogram,
                            int bIncludeOutOfRange, int bApproxOK,
                            GDALProgressFunc, void *pProgressData );

        virtual CPLErr GetDefaultHistogram( double *pdfMin, double *pdfMax,
                                            int *pnBuckets, GUIntBig ** ppanHistogram,
                                            int bForce,
                                            GDALProgressFunc, void *pProgressData);
        virtual CPLErr SetDefaultHistogram( double dfMin, double dfMax,
                                            int nBuckets, GUIntBig *panHistogram );*/

        /*virtual const GDALRasterAttributeTable *GetDefaultRAT();
        virtual CPLErr SetDefaultRAT( const GDALRasterAttributeTable * );*/

        virtual GDALRasterBand *GetMaskBand() override;
        virtual int             GetMaskFlags() override;
        virtual CPLErr          CreateMaskBand( int nFlags ) override;
};

/************************************************************************/
/* ==================================================================== */
/*                       NITFWrapperRasterBand                          */
/* ==================================================================== */
/************************************************************************/

/* This class is used to wrap bands from JPEG or JPEG2000 datasets in */
/* bands of the NITF dataset. Previously a trick was applied in the */
/* relevant drivers to define a SetColorInterpretation() method and */
/* to make sure they keep the proper pointer to their "natural" dataset */
/* This trick is no longer necessary with the NITFWrapperRasterBand */
/* We just override the few specific methods where we want that */
/* the NITFWrapperRasterBand behaviour differs from the JPEG/JPEG2000 one */

class NITFWrapperRasterBand final: public NITFProxyPamRasterBand
{
  GDALRasterBand* poBaseBand;
  GDALColorTable* poColorTable;
  GDALColorInterp eInterp;
  int             bIsJPEG;

  protected:
    /* Pure virtual method of the NITFProxyPamRasterBand */
    virtual GDALRasterBand* RefUnderlyingRasterBand() override;

  public:
                   NITFWrapperRasterBand( NITFDataset * poDS,
                                          GDALRasterBand* poBaseBand,
                                          int nBand);
    virtual ~NITFWrapperRasterBand();

    /* Methods from GDALRasterBand we want to override */
    virtual GDALColorInterp GetColorInterpretation() override;
    virtual CPLErr          SetColorInterpretation( GDALColorInterp ) override;

    virtual GDALColorTable *GetColorTable() override;

    virtual int             GetOverviewCount() override;
    virtual GDALRasterBand *GetOverview(int) override;

    /* Specific method */
    void                    SetColorTableFromNITFBandInfo();
};


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

package org.chromium.chromoting;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

import org.chromium.base.ContextUtils;

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

/**
 * Class that manages download operation for Chromoting activity.
 */
public class ChromotingDownloadManager {
    /**
     * Callback for download manager. This will be executed on application's main thread.
     */
    public interface Callback {
        /**
         * Called when batch download is successfully finished.
         */
        public void onBatchDownloadComplete();
    }

    private Activity mActivity;
    private BroadcastReceiver mDownloadReceiver;
    private DownloadManager mDownloadManager;
    private Set<Long> mUnfinishedDownloadIds;
    private Callback mCallback;
    private String[] mNames;
    private String[] mUris;

    public ChromotingDownloadManager(Activity activity, String[] names, String[] uris,
            Callback callback) {
        assert names.length == uris.length;

        mActivity = activity;
        mCallback = callback;
        mDownloadManager =
                (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
        mNames = names.clone();
        mUris = uris.clone();
        mUnfinishedDownloadIds = new HashSet<Long>();
    }

    public ChromotingDownloadManager(Activity activity, String name, String uri,
            Callback callback) {
        this(activity, new String[] {name}, new String[] {uri}, callback);
    }

    /**
     * Download files according to given URIs and store them as given names.
     */
    public void download() {
        for (int i = 0; i < mNames.length; i++) {
            if (needToBeDownloaded(i)) {
                DownloadManager.Request request =
                        new DownloadManager.Request(Uri.parse(mUris[i]));
                request.setDestinationInExternalFilesDir(ContextUtils.getApplicationContext(),
                        Environment.DIRECTORY_DOWNLOADS, mNames[i]);
                mUnfinishedDownloadIds.add(mDownloadManager.enqueue(request));
            }
        }

        if (mUnfinishedDownloadIds.isEmpty()) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCallback.onBatchDownloadComplete();
                }
            });
        } else {
            mDownloadReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        Query query = new Query();
                        query.setFilterById(convertToArray(mUnfinishedDownloadIds));
                        query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
                        Cursor cursor = mDownloadManager.query(query);

                        // Delete finished download id from unfinished download id set.
                        for (int i = 0; i < cursor.getCount(); i++) {
                            cursor.moveToPosition(i);
                            int downloadIdIndex = cursor.getColumnIndex(DownloadManager.COLUMN_ID);
                            mUnfinishedDownloadIds.remove(cursor.getLong(downloadIdIndex));
                        }

                        if (mUnfinishedDownloadIds.isEmpty()) {
                            mCallback.onBatchDownloadComplete();
                        }
                        cursor.close();
                    }
                }
            };

            mActivity.registerReceiver(mDownloadReceiver,
                    new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }
    }

    /**
     * Perform necessary operations to close the download manager.
     */
    public void close() {
        if (!mUnfinishedDownloadIds.isEmpty()) {
            mDownloadManager.remove(convertToArray(mUnfinishedDownloadIds));
        }
        if (mDownloadReceiver != null) {
            mActivity.unregisterReceiver(mDownloadReceiver);
        }
    }

    /**
     * Check whether the file corresponding to the given index needs to be downloaded.
     */
    private boolean needToBeDownloaded(int index) {
        return !new File(getDownloadDirectory() + "/" + mNames[index]).exists();
    }

    /**
     * Get download directory path.
     */
    public String getDownloadDirectory() {
        return mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
    }

    /**
     * Convert a Set of Long to an array of long.
     */
    private long[] convertToArray(Set<Long> data) {
        long[] result = new long[data.size()];
        int index = 0;
        for (long number : data) {
            result[index] = number;
            index++;
        }
        return result;
    }
}


text:
"""
Model select antigen processing models.

APPROACH: For each training fold, we select at least min and at most max models
(where min and max are set by the --{min/max}-models-per-fold argument) using a
step-up (forward) selection procedure. The final ensemble is the union of all
selected models across all folds. AUC is used as the metric.
"""
import argparse
import os
import signal
import sys
import time
import traceback
import hashlib
from pprint import pprint

import numpy
import pandas
from sklearn.metrics import roc_auc_score

import tqdm  # progress bar
tqdm.monitor_interval = 0  # see https://github.com/tqdm/tqdm/issues/481

from .class1_processing_predictor import Class1ProcessingPredictor
from .flanking_encoding import FlankingEncoding
from .common import configure_logging
from .local_parallelism import (
    worker_pool_with_gpu_assignments_from_args,
    add_local_parallelism_args)
from .cluster_parallelism import (
    add_cluster_parallelism_args,
    cluster_results_from_args)

# To avoid pickling large matrices to send to child processes when running in
# parallel, we use this global variable as a place to store data. Data that is
# stored here before creating the thread pool will be inherited to the child
# processes upon fork() call, allowing us to share large data with the workers
# via shared memory.
GLOBAL_DATA = {}

parser = argparse.ArgumentParser(usage=__doc__)

parser.add_argument(
    "--data",
    metavar="FILE.csv",
    required=False,
    help=(
        "Model selection data CSV. Expected columns: "
        "peptide, hit, fold_0, ..., fold_N"))
parser.add_argument(
    "--models-dir",
    metavar="DIR",
    required=True,
    help="Directory to read models")
parser.add_argument(
    "--out-models-dir",
    metavar="DIR",
    required=True,
    help="Directory to write selected models")
parser.add_argument(
    "--min-models-per-fold",
    type=int,
    default=2,
    metavar="N",
    help="Min number of models to select per fold")
parser.add_argument(
    "--max-models-per-fold",
    type=int,
    default=1000,
    metavar="N",
    help="Max number of models to select per fold")
parser.add_argument(
    "--verbosity",
    type=int,
    help="Keras verbosity. Default: %(default)s",
    default=0)

add_local_parallelism_args(parser)
add_cluster_parallelism_args(parser)

def run(argv=sys.argv[1:]):
    global GLOBAL_DATA

    # On sigusr1 print stack trace
    print("To show stack trace, run:\nkill -s USR1 %d" % os.getpid())
    signal.signal(signal.SIGUSR1, lambda sig, frame: traceback.print_stack())

    args = parser.parse_args(argv)

    args.out_models_dir = os.path.abspath(args.out_models_dir)

    configure_logging(verbose=args.verbosity > 1)

    df = pandas.read_csv(args.data)
    print("Loaded data: %s" % (str(df.shape)))

    input_predictor = Class1ProcessingPredictor.load(args.models_dir)
    print("Loaded: %s" % input_predictor)

    metadata_dfs = {}

    fold_cols = [c for c in df if c.startswith("fold_")]
    num_folds = len(fold_cols)
    if num_folds <= 1:
        raise ValueError("Too few folds: ", num_folds)

    print("Num folds: ", num_folds, "fraction included:")
    print(df[fold_cols].mean())

    metadata_dfs["model_selection_data"] = df

    def make_train_peptide_hash(sub_df):
        train_peptide_hash = hashlib.sha1()
        for peptide in sorted(sub_df.peptide.values):
            train_peptide_hash.update(peptide.encode())
        return train_peptide_hash.hexdigest()

    folds_to_predictors = dict(
        (int(col.split("_")[-1]), (
            [],
            make_train_peptide_hash(df.loc[df[col] == 1])))
        for col in fold_cols)
    print(folds_to_predictors)
    for model in input_predictor.models:
        training_info = model.fit_info[-1]['training_info']
        fold_num = training_info['fold_num']
        assert num_folds == training_info['num_folds']
        (lst, hash) = folds_to_predictors[fold_num]
        train_peptide_hash = training_info['train_peptide_hash']
        numpy.testing.assert_equal(hash, train_peptide_hash)
        lst.append(model)

    work_items = []
    for (fold_num, (models, _)) in folds_to_predictors.items():
        work_items.append({
            'fold_num': fold_num,
            'models': models,
            'min_models': args.min_models_per_fold,
            'max_models': args.max_models_per_fold,
        })

    GLOBAL_DATA["data"] = df
    GLOBAL_DATA["input_predictor"] = input_predictor

    if not os.path.exists(args.out_models_dir):
        print("Attempting to create directory: %s" % args.out_models_dir)
        os.mkdir(args.out_models_dir)
        print("Done.")

    result_predictor = Class1ProcessingPredictor(
        models=[],
        metadata_dataframes=metadata_dfs)

    serial_run = not args.cluster_parallelism and args.num_jobs == 0
    worker_pool = None
    start = time.time()
    if serial_run:
        # Serial run
        print("Running in serial.")
        results = (model_select(**item) for item in work_items)
    elif args.cluster_parallelism:
        # Run using separate processes HPC cluster.
        print("Running on cluster.")
        results = cluster_results_from_args(
            args,
            work_function=model_select,
            work_items=work_items,
            constant_data=GLOBAL_DATA,
            result_serialization_method="pickle")
    else:
        worker_pool = worker_pool_with_gpu_assignments_from_args(args)
        print("Worker pool", worker_pool)
        assert worker_pool is not None

        print("Processing %d work items in parallel." % len(work_items))
        assert not serial_run

        # Parallel run
        results = worker_pool.imap_unordered(
            do_model_select_task,
            work_items,
            chunksize=1)

    models_by_fold = {}
    summary_dfs = []
    for result in tqdm.tqdm(results, total=len(work_items)):
        pprint(result)
        fold_num = result['fold_num']
        (all_models_for_fold, _) = folds_to_predictors[fold_num]
        models = [
            all_models_for_fold[i]
            for i in result['selected_indices']
        ]
        summary_df = result['summary'].copy()
        summary_df.index = summary_df.index.map(
            lambda idx: all_models_for_fold[idx])
        summary_dfs.append(summary_df)

        print("Selected %d models for fold %d: %s" % (
            len(models), fold_num, result['selected_indices']))
        models_by_fold[fold_num] = models
        result_predictor.add_models(models)

    summary_df = pandas.concat(summary_dfs, ignore_index=False)
    summary_df["model_config"] = summary_df.index.map(lambda m: m.get_config())
    result_predictor.metadata_dataframes["model_selection_summary"] = (
        summary_df.reset_index(drop=True))

    result_predictor.save(args.out_models_dir)

    model_selection_time = time.time() - start

    if worker_pool:
        worker_pool.close()
        worker_pool.join()

    print("Model selection time %0.2f min." % (model_selection_time / 60.0))
    print("Predictor [%d models] written to: %s" % (
        len(result_predictor.models), args.out_models_dir))

def do_model_select_task(item, constant_data=GLOBAL_DATA):
    return model_select(constant_data=constant_data, **item)

def model_select(
        fold_num, models, min_models, max_models, constant_data=GLOBAL_DATA):
    """
    Model select for a fold.

    Parameters
    ----------
    fold_num : int
    models : list of Class1NeuralNetwork
    min_models : int
    max_models : int
    constant_data : dict

    Returns
    -------
    dict with keys 'fold_num', 'selected_indices', 'summary'
    """
    from .flanking_encoding import FlankingEncoding

    full_data = constant_data["data"]
    df = full_data.loc[
        full_data["fold_%d" % fold_num] == 0
    ]

    sequences = FlankingEncoding(
        peptides=df.peptide.values,
        n_flanks=df.n_flank.values,
        c_flanks=df.c_flank.values)

    predictions_df = df.copy()
    for (i, model) in enumerate(models):
        predictions_df[i] = model.predict_encoded(sequences)

    selected = []
    selected_score = 0
    remaining_models = set(numpy.arange(len(models)))
    individual_model_scores = {}
    selected_in_round = {}
    ensemble_score_when_selected = {}
    while remaining_models and len(selected) < max_models:
        best_model = None
        best_model_score = 0
        for i in remaining_models:
            possible_ensemble = list(selected) + [i]
            predictions = predictions_df[possible_ensemble].mean(1)
            auc_score = roc_auc_score(df.hit.values, predictions.values)
            if auc_score > best_model_score:
                best_model = i
                best_model_score = auc_score
            if not selected:
                # First iteration. Store individual model scores.
                individual_model_scores[i] = auc_score
        if len(selected) < min_models or best_model_score > selected_score:
            selected_score = best_model_score
            remaining_models.remove(best_model)
            selected.append(best_model)
            selected_in_round[best_model] = len(selected)
            ensemble_score_when_selected[best_model] = selected_score
        else:
            break

    assert selected

    summary_df = pandas.Series(individual_model_scores)[
        numpy.arange(len(models))
    ].to_frame()
    summary_df.columns = ['auc_score']
    summary_df["selected_in_round"] = pandas.Series(selected_in_round)
    summary_df["ensemble_score_when_selected"] = pandas.Series(
        ensemble_score_when_selected)

    print(summary_df)

    return {
        'fold_num': fold_num,
        'selected_indices': selected,
        'summary': summary_df,  # indexed by model index
    }

if __name__ == '__main__':
    run()


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

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

import java.util.List;

import org.camunda.bpm.engine.delegate.BaseDelegateExecution;
import org.camunda.bpm.engine.delegate.DelegateListener;
import org.camunda.bpm.engine.impl.bpmn.parser.FieldDeclaration;
import org.camunda.bpm.engine.impl.cmmn.listener.ClassDelegateCaseExecutionListener;
import org.camunda.bpm.model.cmmn.CmmnModelInstance;
import org.camunda.bpm.model.cmmn.instance.camunda.CamundaCaseExecutionListener;

public class ClassExecutionListenerSpec extends AbstractExecutionListenerSpec {

  // could be configurable
  protected static final String CLASS_NAME = "org.camunda.bpm.test.caseexecutionlistener.ABC";

  public ClassExecutionListenerSpec(String eventName) {
    super(eventName);
  }

  protected void configureCaseExecutionListener(CmmnModelInstance modelInstance, CamundaCaseExecutionListener listener) {
    listener.setCamundaClass(CLASS_NAME);
  }

  public void verifyListener(DelegateListener<? extends BaseDelegateExecution> listener) {
    assertTrue(listener instanceof ClassDelegateCaseExecutionListener);
    ClassDelegateCaseExecutionListener classDelegateListener = (ClassDelegateCaseExecutionListener) listener;
    assertEquals(CLASS_NAME, classDelegateListener.getClassName());

    List<FieldDeclaration> fieldDeclarations = classDelegateListener.getFieldDeclarations();
    assertEquals(fieldSpecs.size(), fieldDeclarations.size());

    for (int i = 0; i < fieldDeclarations.size(); i++) {
      FieldDeclaration declaration = fieldDeclarations.get(i);
      FieldSpec matchingFieldSpec = fieldSpecs.get(i);
      matchingFieldSpec.verify(declaration);
    }
  }

}


text:
package org.robolectric.shadows;

import android.view.ContextThemeWrapper;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;

/**
 * Shadow for {@link android.view.ContextThemeWrapper}.
 */
@SuppressWarnings({"UnusedDeclaration"})
@Implements(ContextThemeWrapper.class)
public class ShadowContextThemeWrapper extends ShadowContextWrapper {
  @RealObject private ContextThemeWrapper realContextThemeWrapper;

  public Integer callGetThemeResId() {
    return ReflectionHelpers.callInstanceMethod(realContextThemeWrapper, "getThemeResId");
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.bingoohuang</groupId>
    <artifactId>blackcat-mall</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>

    <name>blackcat-yoga-consumer</name>
    <description>consumer that monitor a machine's memory, cpu, processes and etc.</description>

    <dependencies>
        <dependency>
            <groupId>com.github.bingoohuang</groupId>
            <artifactId>guava-compatible</artifactId>
            <version>0.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.bingoohuang</groupId>
            <artifactId>blackcat-sdk</artifactId>
            <version>0.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.github.bingoohuang</groupId>
            <artifactId>blackcat-instrument</artifactId>
            <version>0.0.10</version>
        </dependency>
        <dependency>
            <groupId>com.github.bingoohuang</groupId>
            <artifactId>blackcat-server</artifactId>
            <version>0.0.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>com.cronutils</groupId>
            <artifactId>cron-utils</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.bingoohuang</groupId>
            <artifactId>diamond-client</artifactId>
            <version>0.0.20</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>com.github.bingoohuang</groupId>
            <artifactId>java-utils</artifactId>
            <version>0.0.10</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.github.bingoohuang.blackcat.consumer.Main</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.4.3</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>

    </build>

</project>


text:
package org.elasticsearch.gateway.none;

import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.StartedRerouteAllocation;
import org.elasticsearch.cluster.routing.allocation.allocator.GatewayAllocator;

/**
 */
public class NoneGatewayAllocator implements GatewayAllocator {

    @Override
    public void applyStartedShards(StartedRerouteAllocation allocation) {
    }

    @Override
    public void applyFailedShards(FailedRerouteAllocation allocation) {
    }

    @Override
    public boolean allocateUnassigned(RoutingAllocation allocation) {
        return false;
    }
}


text:
/* @flow */
import React from 'react';
import PropTypes from 'prop-types';
import StyleSheet from '../stylesheet';
import TextStylePropTypes from './TextStylePropTypes';
import ViewStylePropTypes from './ViewStylePropTypes';
import ResizingConstraintPropTypes from './ResizingConstraintPropTypes';

const propTypes = {
  // TODO(lmr): do some nice warning stuff like RN does
  style: PropTypes.shape({
    ...ViewStylePropTypes,
    ...TextStylePropTypes,
  }),
  name: PropTypes.string,
  resizingConstraint: PropTypes.shape({
    ...ResizingConstraintPropTypes,
  }),
  children: PropTypes.node,
};

/**
 * @example
 * <Text name='Foo' style={style}>
 *   Hello World!
 * </Text>
 */
class Text extends React.Component {
  static defaultProps = {
    name: 'Text',
  };

  render() {
    return (
      <text
        name={this.props.name}
        style={StyleSheet.flatten(this.props.style)}
        resizingConstraint={this.props.resizingConstraint}
      >
        {this.props.children}
      </text>
    );
  }
}

Text.propTypes = propTypes;

module.exports = Text;


text:
class Admin::SettingsController < AdminController
end


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\Shared;

use Oro\Bundle\ApiBundle\Model\Error;
use Oro\Bundle\ApiBundle\Processor\Shared\NormalizeEntityClass;
use Oro\Bundle\ApiBundle\Request\DataType;
use Oro\Bundle\ApiBundle\Tests\Unit\Processor\GetList\GetListProcessorTestCase;

class NormalizeEntityClassTest extends GetListProcessorTestCase
{
    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $valueNormalizer;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $resourcesProvider;

    /** @var NormalizeEntityClass */
    protected $processor;

    protected function setUp()
    {
        parent::setUp();

        $this->valueNormalizer = $this->getMockBuilder('Oro\Bundle\ApiBundle\Request\ValueNormalizer')
            ->disableOriginalConstructor()
            ->getMock();
        $this->resourcesProvider = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\ResourcesProvider')
            ->disableOriginalConstructor()
            ->getMock();

        $this->processor = new NormalizeEntityClass(
            $this->valueNormalizer,
            $this->resourcesProvider
        );
    }

    public function testProcessWhenClassIsNotSet()
    {
        $this->processor->process($this->context);

        $this->assertEquals(
            [
                Error::createValidationError(
                    'entity type constraint',
                    'The entity class must be set in the context.'
                )
            ],
            $this->context->getErrors()
        );
    }

    public function testProcessWhenClassAlreadyNormalized()
    {
        $this->context->setClassName('Test\Class');

        $this->valueNormalizer->expects($this->never())
            ->method('normalizeValue');

        $this->processor->process($this->context);
    }

    public function testProcess()
    {
        $this->context->setClassName('test');

        $this->valueNormalizer->expects($this->once())
            ->method('normalizeValue')
            ->with($this->context->getClassName(), DataType::ENTITY_CLASS, $this->context->getRequestType())
            ->willReturn('Test\Class');
        $this->resourcesProvider->expects($this->once())
            ->method('isResourceAccessible')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn(true);

        $this->processor->process($this->context);

        $this->assertSame('Test\Class', $this->context->getClassName());
    }

    public function testProcessForNotAccessibleEntityType()
    {
        $this->context->setClassName('test');

        $this->valueNormalizer->expects($this->once())
            ->method('normalizeValue')
            ->with($this->context->getClassName(), DataType::ENTITY_CLASS, $this->context->getRequestType())
            ->willReturn('Test\Class');
        $this->resourcesProvider->expects($this->once())
            ->method('isResourceAccessible')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn(false);

        $this->processor->process($this->context);

        $this->assertNull($this->context->getClassName());
        $this->assertEquals(
            [
                Error::createValidationError('entity type constraint', 'Unknown entity type: test.')
            ],
            $this->context->getErrors()
        );
    }

    public function testProcessForInvalidEntityType()
    {
        $this->context->setClassName('test');

        $this->valueNormalizer->expects($this->once())
            ->method('normalizeValue')
            ->with($this->context->getClassName(), DataType::ENTITY_CLASS, $this->context->getRequestType())
            ->willThrowException(new \Exception('some error'));

        $this->processor->process($this->context);

        $this->assertNull($this->context->getClassName());
        $this->assertEquals(
            [
                Error::createValidationError('entity type constraint', 'Unknown entity type: test.')
            ],
            $this->context->getErrors()
        );
    }
}


text:
package unittesting;

import static org.junit.Assert.*;

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

public class UnittestingUnitTest2 extends AbstractUnitTest
{

	@Before
	public void setup() throws InterruptedException {
		Thread.sleep(500);
	}

	@After
	public void tearDown() throws InterruptedException {
		Thread.sleep(500);
	}

	@Test
	public void evenMoreUnitTests() throws InterruptedException {
		this.startTimeMeasure();

		this.reportStep("By inheriting from AbstractUnitTest some utility methods are provided and time can be tracted in a more reliable way (without counting setup and teardown)");
		Thread.sleep(1000);

		assertTrue(true);

		this.endTimeMeasure();
	}

}


text:
package org.apache.spark.graphx.impl

import scala.reflect.{classTag, ClassTag}

import org.apache.spark.graphx._
import org.apache.spark.graphx.util.collection.GraphXPrimitiveKeyOpenHashMap
import org.apache.spark.util.collection.BitSet

/**
 * A collection of edges, along with referenced vertex attributes and an optional active vertex set
 * for filtering computation on the edges.
  *
  * 边集合,以及引用的顶点属性和可选的活动顶点集,用于过滤边缘上的计算
 *
 * The edges are stored in columnar format in `localSrcIds`, `localDstIds`, and `data`. All
 * referenced global vertex ids are mapped to a compact set of local vertex ids according to the
 * `global2local` map. Each local vertex id is a valid index into `vertexAttrs`, which stores the
 * corresponding vertex attribute, and `local2global`, which stores the reverse mapping to global
 * vertex id. The global vertex ids that are active are optionally stored in `activeSet`.
 *
 * The edges are clustered by source vertex id, and the mapping from global vertex id to the index
 * of the corresponding edge cluster is stored in `index`.
 *
 * @tparam ED the edge attribute type
 * @tparam VD the vertex attribute type
 *
 * @param localSrcIds the local source vertex id of each edge as an index into `local2global` and
 *   `vertexAttrs`
 * @param localDstIds the local destination vertex id of each edge as an index into `local2global`
 *   and `vertexAttrs`
 * @param data the attribute associated with each edge
 * @param index a clustered index on source vertex id as a map from each global source vertex id to
 *   the offset in the edge arrays where the cluster for that vertex id begins
 * @param global2local a map from referenced vertex ids to local ids which index into vertexAttrs
 * @param local2global an array of global vertex ids where the offsets are local vertex ids
 * @param vertexAttrs an array of vertex attributes where the offsets are local vertex ids
 * @param activeSet an optional active vertex set for filtering computation on the edges
 */
private[graphx]
class EdgePartition[
    @specialized(Char, Int, Boolean, Byte, Long, Float, Double) ED: ClassTag, VD: ClassTag](
    localSrcIds: Array[Int],
    localDstIds: Array[Int],
    data: Array[ED],
    index: GraphXPrimitiveKeyOpenHashMap[VertexId, Int],
    global2local: GraphXPrimitiveKeyOpenHashMap[VertexId, Int],
    local2global: Array[VertexId],
    vertexAttrs: Array[VD],
    activeSet: Option[VertexSet])
  extends Serializable {

  /** No-arg constructor for serialization. 用于序列化的无参数构造函数*/
  private def this() = this(null, null, null, null, null, null, null, null)

  /** Return a new `EdgePartition` with the specified edge data. 返回带有指定边数据的新`EdgePartition`*/
  def withData[ED2: ClassTag](data: Array[ED2]): EdgePartition[ED2, VD] = {
    new EdgePartition(
      localSrcIds, localDstIds, data, index, global2local, local2global, vertexAttrs, activeSet)
  }

  /** Return a new `EdgePartition` with the specified active set, provided as an iterator.
    * 返回一个带有指定活动集的新`EdgePartition`,作为迭代器提供*/
  def withActiveSet(iter: Iterator[VertexId]): EdgePartition[ED, VD] = {
    val activeSet = new VertexSet
    while (iter.hasNext) { activeSet.add(iter.next()) }
    new EdgePartition(
      localSrcIds, localDstIds, data, index, global2local, local2global, vertexAttrs,
      Some(activeSet))
  }

  /** Return a new `EdgePartition` with updates to vertex attributes specified in `iter`.
    * 返回一个新的`EdgePartition`,其中包含对`iter`中指定的顶点属性的更新*/
  def updateVertices(iter: Iterator[(VertexId, VD)]): EdgePartition[ED, VD] = {
    val newVertexAttrs = new Array[VD](vertexAttrs.length)
    System.arraycopy(vertexAttrs, 0, newVertexAttrs, 0, vertexAttrs.length)
    while (iter.hasNext) {
      val kv = iter.next()
      newVertexAttrs(global2local(kv._1)) = kv._2
    }
    new EdgePartition(
      localSrcIds, localDstIds, data, index, global2local, local2global, newVertexAttrs,
      activeSet)
  }

  /** Return a new `EdgePartition` without any locally cached vertex attributes.
    * 返回一个没有任何本地缓存顶点属性的新`EdgePartition` */
  def withoutVertexAttributes[VD2: ClassTag](): EdgePartition[ED, VD2] = {
    val newVertexAttrs = new Array[VD2](vertexAttrs.length)
    new EdgePartition(
      localSrcIds, localDstIds, data, index, global2local, local2global, newVertexAttrs,
      activeSet)
  }

  @inline private def srcIds(pos: Int): VertexId = local2global(localSrcIds(pos))

  @inline private def dstIds(pos: Int): VertexId = local2global(localDstIds(pos))

  @inline private def attrs(pos: Int): ED = data(pos)

  /** Look up vid in activeSet, throwing an exception if it is None.
    * 在activeSet中查找vid,如果为None则抛出异常*/
  def isActive(vid: VertexId): Boolean = {
    activeSet.get.contains(vid)
  }

  /** The number of active vertices, if any exist.
    * 活动顶点的数量(如果存在)*/
  def numActives: Option[Int] = activeSet.map(_.size)

  /**
   * Reverse all the edges in this partition.
    * 反转此分区中的所有边
   *
   * @return a new edge partition with all edges reversed.
   */
  def reverse: EdgePartition[ED, VD] = {
    val builder = new ExistingEdgePartitionBuilder[ED, VD](
      global2local, local2global, vertexAttrs, activeSet, size)
    var i = 0
    while (i < size) {
      val localSrcId = localSrcIds(i)
      val localDstId = localDstIds(i)
      val srcId = local2global(localSrcId)
      val dstId = local2global(localDstId)
      val attr = data(i)
      builder.add(dstId, srcId, localDstId, localSrcId, attr)
      i += 1
    }
    builder.toEdgePartition
  }

  /**
   * Construct a new edge partition by applying the function f to all
   * edges in this partition.
    * 通过将函数f应用于此分区中的所有边来构造新的边分区
   *
   * Be careful not to keep references to the objects passed to `f`.
   * To improve GC performance the same object is re-used for each call.
    *
    * 注意不要保留对传递给`f`的对象的引用,
    * 为了提高GC性能,每次调用都会重复使用相同的对象
   *
   * @param f a function from an edge to a new attribute
   * @tparam ED2 the type of the new attribute
   * @return a new edge partition with the result of the function `f`
   *         applied to each edge
   */
  def map[ED2: ClassTag](f: Edge[ED] => ED2): EdgePartition[ED2, VD] = {
    val newData = new Array[ED2](data.size)
    val edge = new Edge[ED]()
    val size = data.size
    var i = 0
    while (i < size) {
      edge.srcId = srcIds(i)
      edge.dstId = dstIds(i)
      edge.attr = data(i)
      newData(i) = f(edge)
      i += 1
    }
    this.withData(newData)
  }

  /**
   * Construct a new edge partition by using the edge attributes
   * contained in the iterator.
   * 使用迭代器中包含的边缘属性构造新的边缘分区
   * @note The input iterator should return edge attributes in the
   * order of the edges returned by `EdgePartition.iterator` and
   * should return attributes equal to the number of edges.
   *
   * @param iter an iterator for the new attribute values
   * @tparam ED2 the type of the new attribute
   * @return a new edge partition with the attribute values replaced
   */
  def map[ED2: ClassTag](iter: Iterator[ED2]): EdgePartition[ED2, VD] = {
    // Faster than iter.toArray, because the expected size is known.
    val newData = new Array[ED2](data.size)
    var i = 0
    while (iter.hasNext) {
      newData(i) = iter.next()
      i += 1
    }
    assert(newData.size == i)
    this.withData(newData)
  }

  /**
   * Construct a new edge partition containing only the edges matching `epred` and where both
   * vertices match `vpred`.
    *
    * 构造一个新的边分区,其中只包含与`epred`匹配的边,并且两个顶点都匹配`vpred`
   */
  def filter(
      epred: EdgeTriplet[VD, ED] => Boolean,
      vpred: (VertexId, VD) => Boolean): EdgePartition[ED, VD] = {
    val builder = new ExistingEdgePartitionBuilder[ED, VD](
      global2local, local2global, vertexAttrs, activeSet)
    var i = 0
    while (i < size) {
      // The user sees the EdgeTriplet, so we can't reuse it and must create one per edge.
      //用户看到EdgeTriplet,因此我们无法重复使用它,并且必须为每个边创建一个
      val localSrcId = localSrcIds(i)
      val localDstId = localDstIds(i)
      val et = new EdgeTriplet[VD, ED]
      et.srcId = local2global(localSrcId)
      et.dstId = local2global(localDstId)
      et.srcAttr = vertexAttrs(localSrcId)
      et.dstAttr = vertexAttrs(localDstId)
      et.attr = data(i)
      if (vpred(et.srcId, et.srcAttr) && vpred(et.dstId, et.dstAttr) && epred(et)) {
        builder.add(et.srcId, et.dstId, localSrcId, localDstId, et.attr)
      }
      i += 1
    }
    builder.toEdgePartition
  }

  /**
   * Apply the function f to all edges in this partition.
    * 将函数f应用于此分区中的所有边
   *
   * @param f an external state mutating user defined function.
   */
  def foreach(f: Edge[ED] => Unit) {
    iterator.foreach(f)
  }

  /**
   * Merge all the edges with the same src and dest id into a single
   * edge using the `merge` function
    * 使用`merge`函数将具有相同src和dest id的所有边合并为单个边
   *
   * @param merge a commutative associative merge operation
   * @return a new edge partition without duplicate edges
   */
  def groupEdges(merge: (ED, ED) => ED): EdgePartition[ED, VD] = {
    val builder = new ExistingEdgePartitionBuilder[ED, VD](
      global2local, local2global, vertexAttrs, activeSet)
    var currSrcId: VertexId = null.asInstanceOf[VertexId]
    var currDstId: VertexId = null.asInstanceOf[VertexId]
    var currLocalSrcId = -1
    var currLocalDstId = -1
    var currAttr: ED = null.asInstanceOf[ED]
    // Iterate through the edges, accumulating runs of identical edges using the curr* variables and
    // releasing them to the builder when we see the beginning of the next run
    //通过边缘迭代,使用curr *变量累积相同边的运行,并在我们看到下一次运行的开始时将它们释放到构建器
    var i = 0
    while (i < size) {
      if (i > 0 && currSrcId == srcIds(i) && currDstId == dstIds(i)) {
        // This edge should be accumulated into the existing run
        //此边缘应累积到现有运行中
        currAttr = merge(currAttr, data(i))
      } else {
        // This edge starts a new run of edges
        //此边缘开始新的边缘运行
        if (i > 0) {
          // First release the existing run to the builder
          //首先将现有运行发布到构建器
          builder.add(currSrcId, currDstId, currLocalSrcId, currLocalDstId, currAttr)
        }
        // Then start accumulating for a new run
        //然后开始累积新的运行
        currSrcId = srcIds(i)
        currDstId = dstIds(i)
        currLocalSrcId = localSrcIds(i)
        currLocalDstId = localDstIds(i)
        currAttr = data(i)
      }
      i += 1
    }
    // Finally, release the last accumulated run
    //最后,释放最后累积的运行
    if (size > 0) {
      builder.add(currSrcId, currDstId, currLocalSrcId, currLocalDstId, currAttr)
    }
    builder.toEdgePartition
  }

  /**
   * Apply `f` to all edges present in both `this` and `other` and return a new `EdgePartition`
   * containing the resulting edges.
    * 将`f`应用于'this`和`other`中的所有边,并返回一个包含结果边的新`EdgePartition`
   *
   * If there are multiple edges with the same src and dst in `this`, `f` will be invoked once for
   * each edge, but each time it may be invoked on any corresponding edge in `other`.
    *
    * 如果在`this`中有多个具有相同src和dst的边,则每个边将调用一次`f`,但每次可以在`other`中的任何相应边上调用它
   *
   * If there are multiple edges with the same src and dst in `other`, `f` will only be invoked
   * once.
   */
  def innerJoin[ED2: ClassTag, ED3: ClassTag]
      (other: EdgePartition[ED2, _])
      (f: (VertexId, VertexId, ED, ED2) => ED3): EdgePartition[ED3, VD] = {
    val builder = new ExistingEdgePartitionBuilder[ED3, VD](
      global2local, local2global, vertexAttrs, activeSet)
    var i = 0
    var j = 0
    // For i = index of each edge in `this`...
    while (i < size && j < other.size) {
      val srcId = this.srcIds(i)
      val dstId = this.dstIds(i)
      // ... forward j to the index of the corresponding edge in `other`, and...
      while (j < other.size && other.srcIds(j) < srcId) { j += 1 }
      if (j < other.size && other.srcIds(j) == srcId) {
        while (j < other.size && other.srcIds(j) == srcId && other.dstIds(j) < dstId) { j += 1 }
        if (j < other.size && other.srcIds(j) == srcId && other.dstIds(j) == dstId) {
          // ... run `f` on the matching edge
          builder.add(srcId, dstId, localSrcIds(i), localDstIds(i),
            f(srcId, dstId, this.data(i), other.attrs(j)))
        }
      }
      i += 1
    }
    builder.toEdgePartition
  }

  /**
   * The number of edges in this partition
   * 此分区中的边数
   * @return size of the partition
   */
  val size: Int = localSrcIds.size

  /** The number of unique source vertices in the partition.
    * 分区中唯一源顶点的数量*/
  def indexSize: Int = index.size

  /**
   * Get an iterator over the edges in this partition.
   * 获取此分区边缘的迭代器
   * Be careful not to keep references to the objects from this iterator.
    * 注意不要在此迭代器中保留对象的引用
   * To improve GC performance the same object is re-used in `next()`.
   *
   * @return an iterator over edges in the partition
   */
  def iterator: Iterator[Edge[ED]] = new Iterator[Edge[ED]] {
    private[this] val edge = new Edge[ED]
    private[this] var pos = 0

    override def hasNext: Boolean = pos < EdgePartition.this.size

    override def next(): Edge[ED] = {
      edge.srcId = srcIds(pos)
      edge.dstId = dstIds(pos)
      edge.attr = data(pos)
      pos += 1
      edge
    }
  }

  /**
   * Get an iterator over the edge triplets in this partition.
    * 获取此分区中边缘三元组的迭代器
   *
   * It is safe to keep references to the objects from this iterator.
    * 从这个迭代器继续引用对象是安全的
   */
  def tripletIterator(
      includeSrc: Boolean = true, includeDst: Boolean = true)
      : Iterator[EdgeTriplet[VD, ED]] = new Iterator[EdgeTriplet[VD, ED]] {
    private[this] var pos = 0

    override def hasNext: Boolean = pos < EdgePartition.this.size

    override def next(): EdgeTriplet[VD, ED] = {
      val triplet = new EdgeTriplet[VD, ED]
      val localSrcId = localSrcIds(pos)
      val localDstId = localDstIds(pos)
      triplet.srcId = local2global(localSrcId)
      triplet.dstId = local2global(localDstId)
      if (includeSrc) {
        triplet.srcAttr = vertexAttrs(localSrcId)
      }
      if (includeDst) {
        triplet.dstAttr = vertexAttrs(localDstId)
      }
      triplet.attr = data(pos)
      pos += 1
      triplet
    }
  }

  /**
   * Send messages along edges and aggregate them at the receiving vertices. Implemented by scanning
   * all edges sequentially.
    *
    * 沿边发送消息并在接收顶点聚合它们,通过顺序扫描所有边缘来实现
   *
   * @param sendMsg generates messages to neighboring vertices of an edge
   * @param mergeMsg the combiner applied to messages destined to the same vertex
   * @param tripletFields which triplet fields `sendMsg` uses
   * @param activeness criteria for filtering edges based on activeness
   *
   * @return iterator aggregated messages keyed by the receiving vertex id
   */
  def aggregateMessagesEdgeScan[A: ClassTag](
      sendMsg: EdgeContext[VD, ED, A] => Unit,
      mergeMsg: (A, A) => A,
      tripletFields: TripletFields,
      activeness: EdgeActiveness): Iterator[(VertexId, A)] = {
    val aggregates = new Array[A](vertexAttrs.length)
    val bitset = new BitSet(vertexAttrs.length)

    var ctx = new AggregatingEdgeContext[VD, ED, A](mergeMsg, aggregates, bitset)
    var i = 0
    while (i < size) {
      val localSrcId = localSrcIds(i)
      val srcId = local2global(localSrcId)
      val localDstId = localDstIds(i)
      val dstId = local2global(localDstId)
      val edgeIsActive =
        if (activeness == EdgeActiveness.Neither) true
        else if (activeness == EdgeActiveness.SrcOnly) isActive(srcId)
        else if (activeness == EdgeActiveness.DstOnly) isActive(dstId)
        else if (activeness == EdgeActiveness.Both) isActive(srcId) && isActive(dstId)
        else if (activeness == EdgeActiveness.Either) isActive(srcId) || isActive(dstId)
        else throw new Exception("unreachable")
      if (edgeIsActive) {
        val srcAttr = if (tripletFields.useSrc) vertexAttrs(localSrcId) else null.asInstanceOf[VD]
        val dstAttr = if (tripletFields.useDst) vertexAttrs(localDstId) else null.asInstanceOf[VD]
        ctx.set(srcId, dstId, localSrcId, localDstId, srcAttr, dstAttr, data(i))
        sendMsg(ctx)
      }
      i += 1
    }

    bitset.iterator.map { localId => (local2global(localId), aggregates(localId)) }
  }

  /**
   * Send messages along edges and aggregate them at the receiving vertices. Implemented by
   * filtering the source vertex index, then scanning each edge cluster.
    * 沿边发送消息并在接收顶点聚合它们,通过过滤源顶点索引实现,然后扫描每个边缘集群
   *
   * @param sendMsg generates messages to neighboring vertices of an edge
   * @param mergeMsg the combiner applied to messages destined to the same vertex
   * @param tripletFields which triplet fields `sendMsg` uses
   * @param activeness criteria for filtering edges based on activeness
   *
   * @return iterator aggregated messages keyed by the receiving vertex id
   */
  def aggregateMessagesIndexScan[A: ClassTag](
      sendMsg: EdgeContext[VD, ED, A] => Unit,
      mergeMsg: (A, A) => A,
      tripletFields: TripletFields,
      activeness: EdgeActiveness): Iterator[(VertexId, A)] = {
    val aggregates = new Array[A](vertexAttrs.length)
    val bitset = new BitSet(vertexAttrs.length)

    var ctx = new AggregatingEdgeContext[VD, ED, A](mergeMsg, aggregates, bitset)
    index.iterator.foreach { cluster =>
      val clusterSrcId = cluster._1
      val clusterPos = cluster._2
      val clusterLocalSrcId = localSrcIds(clusterPos)

      val scanCluster =
        if (activeness == EdgeActiveness.Neither) true
        else if (activeness == EdgeActiveness.SrcOnly) isActive(clusterSrcId)
        else if (activeness == EdgeActiveness.DstOnly) true
        else if (activeness == EdgeActiveness.Both) isActive(clusterSrcId)
        else if (activeness == EdgeActiveness.Either) true
        else throw new Exception("unreachable")

      if (scanCluster) {
        var pos = clusterPos
        val srcAttr =
          if (tripletFields.useSrc) vertexAttrs(clusterLocalSrcId) else null.asInstanceOf[VD]
        ctx.setSrcOnly(clusterSrcId, clusterLocalSrcId, srcAttr)
        while (pos < size && localSrcIds(pos) == clusterLocalSrcId) {
          val localDstId = localDstIds(pos)
          val dstId = local2global(localDstId)
          val edgeIsActive =
            if (activeness == EdgeActiveness.Neither) true
            else if (activeness == EdgeActiveness.SrcOnly) true
            else if (activeness == EdgeActiveness.DstOnly) isActive(dstId)
            else if (activeness == EdgeActiveness.Both) isActive(dstId)
            else if (activeness == EdgeActiveness.Either) isActive(clusterSrcId) || isActive(dstId)
            else throw new Exception("unreachable")
          if (edgeIsActive) {
            val dstAttr =
              if (tripletFields.useDst) vertexAttrs(localDstId) else null.asInstanceOf[VD]
            ctx.setRest(dstId, localDstId, dstAttr, data(pos))
            sendMsg(ctx)
          }
          pos += 1
        }
      }
    }

    bitset.iterator.map { localId => (local2global(localId), aggregates(localId)) }
  }
}

private class AggregatingEdgeContext[VD, ED, A](
    mergeMsg: (A, A) => A,
    aggregates: Array[A],
    bitset: BitSet)
  extends EdgeContext[VD, ED, A] {

  private[this] var _srcId: VertexId = _
  private[this] var _dstId: VertexId = _
  private[this] var _localSrcId: Int = _
  private[this] var _localDstId: Int = _
  private[this] var _srcAttr: VD = _
  private[this] var _dstAttr: VD = _
  private[this] var _attr: ED = _

  def set(
      srcId: VertexId, dstId: VertexId,
      localSrcId: Int, localDstId: Int,
      srcAttr: VD, dstAttr: VD,
      attr: ED) {
    _srcId = srcId
    _dstId = dstId
    _localSrcId = localSrcId
    _localDstId = localDstId
    _srcAttr = srcAttr
    _dstAttr = dstAttr
    _attr = attr
  }

  def setSrcOnly(srcId: VertexId, localSrcId: Int, srcAttr: VD) {
    _srcId = srcId
    _localSrcId = localSrcId
    _srcAttr = srcAttr
  }

  def setRest(dstId: VertexId, localDstId: Int, dstAttr: VD, attr: ED) {
    _dstId = dstId
    _localDstId = localDstId
    _dstAttr = dstAttr
    _attr = attr
  }

  override def srcId: VertexId = _srcId
  override def dstId: VertexId = _dstId
  override def srcAttr: VD = _srcAttr
  override def dstAttr: VD = _dstAttr
  override def attr: ED = _attr

  override def sendToSrc(msg: A) {
    send(_localSrcId, msg)
  }
  override def sendToDst(msg: A) {
    send(_localDstId, msg)
  }

  @inline private def send(localId: Int, msg: A) {
    if (bitset.get(localId)) {
      aggregates(localId) = mergeMsg(aggregates(localId), msg)
    } else {
      aggregates(localId) = msg
      bitset.set(localId)
    }
  }
}


text:
#include "gtypes.h"
/*****************************************************/
/*  This file was automatically generated by Ocarina */
/*  Do NOT hand-modify this file, as your            */
/*  changes will be lost when you re-run Ocarina     */
/*****************************************************/
void user_receive
    (pingpong__integer input);

/****************************/
/* pingpong__hello_part2   */
/***************************/

void pingpong__hello_part2
    (pingpong__integer input)
{

  user_receive (input);
}


text:
"""
Django settings for project project.

Generated by 'django-admin startproject' using Django 1.11.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'yqhd3g#pokbw0mn0dtjgk2v6^yk1n%)osv@qnvtxit!(u3oyg!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'api',
    'tools',

    'rest_framework',
    'rest_framework_swagger',
    'gunicorn',
    'corsheaders',
    'rest_framework.authtoken',
    'django_filters',
    'rest_auth',
    'django_crontab',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    #'default': {
    #    'ENGINE': 'django.db.backends.sqlite3',
    #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #},
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'hotfix',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    },
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 100,
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
}

LOGIN_URL = '/api-auth/login/'
LOGOUT_URL = '/api-auth/logout/'

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)
CORS_ALLOW_CREDENTIALS = True
APPEND_SLASH = False

CRONJOBS = (
    ('*/1 * * * *', 'api.cron.store_from_redis'),
)


text:
package com.xeiam.xchange.kraken.dto.trade;

import java.math.BigDecimal;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class KrakenTrade {

  private final String orderTxId;
  private final String assetPair;
  private final double unixTimestamp;
  private final KrakenType type;
  private final KrakenOrderType orderType;
  private final BigDecimal price;
  private final BigDecimal cost;
  private final BigDecimal fee;
  private final BigDecimal volume;
  private final BigDecimal margin;
  private final String miscellaneous;
  private final String closing;
  private final String positionStatus;
  private final BigDecimal averageClosePrice;
  private final BigDecimal closeCost;
  private final BigDecimal closeFee;
  private final BigDecimal closeVolume;
  private final BigDecimal closeMargin;
  private final BigDecimal netDifference;
  private final List<String> tradeIds;

  /**
   * Constructor
   *
   * @param orderTxId
   * @param assetPair
   * @param unixTimestamp
   * @param type
   * @param orderType
   * @param price
   * @param cost
   * @param fee
   * @param volume
   * @param margin
   * @param miscellaneous
   * @param closing
   * @param positionStatus
   * @param averageClosePrice
   * @param closeCost
   * @param closeFee
   * @param closeVolume
   * @param closeMargin
   * @param netDifference
   * @param tradeIds
   */
  public KrakenTrade(@JsonProperty("ordertxid") String orderTxId, @JsonProperty("pair") String assetPair, @JsonProperty("time") double unixTimestamp, @JsonProperty("type") KrakenType type,
      @JsonProperty("ordertype") KrakenOrderType orderType, @JsonProperty("price") BigDecimal price, @JsonProperty("cost") BigDecimal cost, @JsonProperty("fee") BigDecimal fee,
      @JsonProperty("vol") BigDecimal volume, @JsonProperty("margin") BigDecimal margin, @JsonProperty("misc") String miscellaneous, @JsonProperty("closing") String closing,
      @JsonProperty("posstatus") String positionStatus, @JsonProperty("cprice") BigDecimal averageClosePrice, @JsonProperty("ccost") BigDecimal closeCost, @JsonProperty("cfee") BigDecimal closeFee,
      @JsonProperty("cvol") BigDecimal closeVolume, @JsonProperty("cmargin") BigDecimal closeMargin, @JsonProperty("net") BigDecimal netDifference, @JsonProperty("trades") List<String> tradeIds) {

    this.orderTxId = orderTxId;
    this.assetPair = assetPair;
    this.unixTimestamp = unixTimestamp;
    this.type = type;
    this.orderType = orderType;
    this.price = price;
    this.cost = cost;
    this.fee = fee;
    this.volume = volume;
    this.margin = margin;
    this.miscellaneous = miscellaneous;
    this.closing = closing;
    this.positionStatus = positionStatus;
    this.averageClosePrice = averageClosePrice;
    this.closeCost = closeCost;
    this.closeFee = closeFee;
    this.closeVolume = closeVolume;
    this.closeMargin = closeMargin;
    this.netDifference = netDifference;
    this.tradeIds = tradeIds;
  }

  public String getOrderTxId() {

    return orderTxId;
  }

  public String getAssetPair() {

    return assetPair;
  }

  public double getUnixTimestamp() {

    return unixTimestamp;
  }

  public KrakenType getType() {

    return type;
  }

  public KrakenOrderType getOrderType() {

    return orderType;
  }

  public BigDecimal getPrice() {

    return price;
  }

  public BigDecimal getCost() {

    return cost;
  }

  public BigDecimal getFee() {

    return fee;
  }

  public BigDecimal getVolume() {

    return volume;
  }

  public BigDecimal getMargin() {

    return margin;
  }

  public String getMiscellaneous() {

    return miscellaneous;
  }

  public String getClosing() {

    return closing;
  }

  public String getPositionStatus() {

    return positionStatus;
  }

  public BigDecimal getAverageClosePrice() {

    return averageClosePrice;
  }

  public BigDecimal getCloseCost() {

    return closeCost;
  }

  public BigDecimal getCloseFee() {

    return closeFee;
  }

  public BigDecimal getCloseVolume() {

    return closeVolume;
  }

  public BigDecimal getCloseMargin() {

    return closeMargin;
  }

  public BigDecimal getNetDifference() {

    return netDifference;
  }

  public List<String> getTradeIds() {

    return tradeIds;
  }

  @Override
  public String toString() {

    return "KrakenTrade [orderTxId=" + orderTxId + ", assetPair=" + assetPair + ", unixTimestamp=" + unixTimestamp + ", type=" + type + ", orderType=" + orderType + ", price=" + price + ", cost="
        + cost + ", fee=" + fee + ", volume=" + volume + ", margin=" + margin + ", miscellaneous=" + miscellaneous + ", closing=" + closing + ", positionStatus=" + positionStatus
        + ", averageClosePrice=" + averageClosePrice + ", closeCost=" + closeCost + ", closeFee=" + closeFee + ", closeVolume=" + closeVolume + ", closeMargin=" + closeMargin + ", netDifference="
        + netDifference + ", tradeIds=" + tradeIds + "]";
  }

}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.plugins.groovy.settings;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.SettingsCategory;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;

/**
 * @author ilyas
 */

@State(name = "GroovyApplicationSettings", storages = @Storage("groovy_config.xml"), category = SettingsCategory.CODE)
public class GroovyApplicationSettings implements PersistentStateComponent<GroovyApplicationSettings> {

  public boolean INTRODUCE_LOCAL_CREATE_FINALS = false;
  public boolean INTRODUCE_LOCAL_SELECT_DEF = true;
  public boolean FORCE_RETURN = false;
  public Boolean EXTRACT_METHOD_SPECIFY_TYPE = null;
  public String EXTRACT_METHOD_VISIBILITY = null;
  public Boolean CONVERT_PARAM_SPECIFY_MAP_TYPE = null;
  public Boolean CONVERT_PARAM_CREATE_NEW_PARAM = null;

  @Override
  public GroovyApplicationSettings getState() {
    return this;
  }

  @Override
  public void loadState(@NotNull GroovyApplicationSettings groovyApplicationSettings) {
    XmlSerializerUtil.copyBean(groovyApplicationSettings, this);
  }

  public static GroovyApplicationSettings getInstance() {
    return ApplicationManager.getApplication().getService(GroovyApplicationSettings.class);
  }

}


text:
TARGET=parse-capDL

.PHONY: all
all: $(TARGET)

.PHONY: tests
tests: example-arm.parse example-ia32.parse hello-dump.parse

# The size of the IRQ array we emit (if using --code) needs to match the size
# expected by the initialiser. If we're building within a project, try to
# retrieve this from the current configuration.
-include .config
ifndef CONFIG_CAPDL_LOADER_MAX_IRQS
    CONFIG_CAPDL_LOADER_MAX_IRQS = 256
endif

%.parse: %.cdl %.right $(TARGET)
	./$(TARGET) -t $*.parse -x $*.xml -d $*.dot $< || rm -f $*.parse $*.dot $*.xml
	dot -Tpng $*.dot -o $*.png
	@diff $*.parse $*.right
	@./$(TARGET) -t $*.parse.x $*.parse > /dev/null
	@diff $*.parse $*.parse.x  || (echo "Self parse failed"; exit 1)
	which xmllint && xmllint --noout --dtdvalid ./capdl.dtd $*.xml

.PHONY: sandbox
sandbox:
	cabal sandbox init
	cabal install --dependencies-only

.PHONY: userdeps
userdeps:
	cabal install --user --dependencies-only

$(TARGET): capDL-tool.cabal Setup.hs Main.hs CapDL/*.hs
	export CONFIG_CAPDL_LOADER_MAX_IRQS=$(CONFIG_CAPDL_LOADER_MAX_IRQS) && cabal configure && cabal build && \
	cp dist/build/parse-capDL/parse-capDL .

.PHONY: clean
clean:
	cabal clean
	rm -f $(TARGET)

.PHONY: testclean
testclean:
	rm -f *.parse *.parse.x *.dot *.xml *.thy *.png *.out


text:
const path = require('path');
const storage = require('../../adapters/storage');

module.exports = {
    docName: 'media',
    upload: {
        statusCode: 201,
        permissions: false,
        async query(frame) {
            let thumbnailPath = null;
            if (frame.files.thumbnail && frame.files.thumbnail[0]) {
                thumbnailPath = await storage.getStorage('media').save(frame.files.thumbnail[0]);
            }

            const filePath = await storage.getStorage('media').save(frame.files.file[0]);

            return {
                filePath,
                thumbnailPath
            };
        }
    },

    uploadThumbnail: {
        permissions: false,
        data: [
            'url',
            'ref'
        ],
        async query(frame) {
            const mediaStorage = storage.getStorage('media');
            const targetDir = path.dirname(mediaStorage.urlToPath(frame.data.url));

            // NOTE: need to cleanup otherwise the parent media name won't match thumb name
            //       due to "unique name" generation during save
            if (mediaStorage.exists(frame.file.name, targetDir)) {
                await mediaStorage.delete(frame.file.name, targetDir);
            }

            return await mediaStorage.save(frame.file, targetDir);
        }
    }
};


text:
package org.knowm.xchange.bitstamp.service.streaming;

import java.util.HashSet;
import java.util.Set;

import com.pusher.client.PusherOptions;
import org.knowm.xchange.service.streaming.ExchangeStreamingConfiguration;

/**
 *

 * Value object to provide the following
 *

 *

 *
Access to streaming data configuration specific to Bitstamp exchange streaming API

 *

 */
public class BitstampStreamingConfiguration implements ExchangeStreamingConfiguration {

  private final int maxReconnectAttempts;
  private final int reconnectWaitTimeInMs;
  private final int timeoutInMs;
  private final boolean isEncryptedChannel;
  private final String pusherKey;
  private final Set<String> channels;
  private PusherOptions pusherOpts;

  /**
   * Constructor
   *
   * @param maxReconnectAttempts
   * @param reconnectWaitTimeInMs
   * @param timeoutInMs
   * @param isEncryptedChannel - should it use an encrypted channel or not? (ws vs. wss protocol)
   * @param channel - the specific data channel you want to tap into (https://mtgox.com/api/2/stream/list_public), null if none
   */
  public BitstampStreamingConfiguration(PusherOptions pusherOptions, int maxReconnectAttempts, int reconnectWaitTimeInMs, int timeoutInMs,
      boolean isEncryptedChannel, String pusherKey, Set<String> channels) {

    this.maxReconnectAttempts = maxReconnectAttempts;
    this.reconnectWaitTimeInMs = reconnectWaitTimeInMs;
    this.timeoutInMs = timeoutInMs;
    this.isEncryptedChannel = isEncryptedChannel;
    this.pusherKey = pusherKey;
    this.channels = channels;
    pusherOpts = pusherOptions;
  }

  public BitstampStreamingConfiguration() {

    maxReconnectAttempts = 30; // 67 min
    reconnectWaitTimeInMs = 135000; // 2:15
    timeoutInMs = 120000; // 2:00
    isEncryptedChannel = false; // data stream is public
    pusherKey = "de504dc5763aeef9ff52"; // https://www.bitstamp.net/websocket/
    channels = new HashSet<String>();
    channels.add("live_trades");
    channels.add("order_book");
    channels.add("diff_order_book");
    pusherOpts = new PusherOptions();
    pusherOpts.setEncrypted(isEncryptedChannel);
    pusherOpts.setActivityTimeout(4 * timeoutInMs); // Keep-alive interval
    pusherOpts.setPongTimeout(timeoutInMs); // Response timeout
  }

  public final PusherOptions pusherOptions() {

    return pusherOpts;
  }

  @Override
  public int getMaxReconnectAttempts() {

    return maxReconnectAttempts;
  }

  @Override
  public int getReconnectWaitTimeInMs() {

    return reconnectWaitTimeInMs;
  }

  @Override
  public int getTimeoutInMs() {

    return timeoutInMs;
  }

  @Override
  public boolean isEncryptedChannel() {

    return isEncryptedChannel;
  }

  @Override
  public boolean keepAlive() {

    return true; // pusher client always keeps alive
  }

  public String getPusherKey() {

    return pusherKey;
  }

  public Set<String> getChannels() {

    return channels;
  }

}


text:
var changeFrog = function(){
  document.getElementById("animatedfrog");
  document.getElementById("animatedfrog").className = "animated bounce";
}


text:
module Logic (
	-- | types
	User,
	Conversation,
	-- | data
	Message (Message),
	-- | construction
	boot,
	insert,
	construct,
	deconstruct
	)
	where

import Data.Maybe (catMaybes)

-- repeat a list forever
cycled [] = []
cycled xs = xs ++ cycled xs

type User = String

data Message = Message User String deriving Show

-- | a conversation builded right accepting new messages only if they are correct.
-- Correctness is 2 users only and alternated messages
data Conversation = Conversation {
		-- accept a new message fail when not correct
	 	accept' :: Message -> Maybe Conversation,
		-- | spits out messages
		deconstruct :: [Message]
		}
-- | insert a new message, failing on unacceptable user sequence
insert :: Message -> Conversation -> Maybe Conversation
insert = flip accept'

-- | an helper for multi message construction
construct :: [Message] -> Maybe Conversation
construct = foldl (\f x -> f >>= insert x) (Just boot)

make :: Maybe User -> Maybe User -> [String] -> Conversation
make u1 u2  xs = Conversation (accept u1 u2 xs) (ser u1 u2 xs)

-- | an empty Conversation
boot :: Conversation
boot = make Nothing Nothing []

accept :: Maybe User -> Maybe User -> [String] -> Message -> Maybe Conversation
-- primo messaggio
accept Nothing Nothing [] (Message u x) = Just $ make Nothing (Just u) [x]
-- secondo messaggio
accept Nothing (Just u2) xs (Message u x)
	| u == u2 = Nothing
	| True =  Just (make (Just u2) (Just u) $ x:xs)
-- ennesimo messaggio
accept (Just u1) u2 xs (Message u x)
	| u == u1 = Just (make u2 (Just u1) $ x:xs)
	| otherwise = Nothing

-- ricostruzione
ser :: Maybe User -> Maybe User -> [String] -> [Message]
ser u1 u2 xs = zipWith Message (cycled $ catMaybes [u1,u2]) $ reverse xs


text:
'use strict';

const fs = require('fs');
const redux = require('redux');

class ActionStore {
    constructor(reducer, history) {
        this.history = history || [];
        this.reducer = reducer;
        this._store = redux.createStore(reducer);

        this.createStore = this.createStore.bind(this);
    }

    static fromJson(path, reducer) {
        try {
            return new ActionStore(reducer, JSON.parse(fs.readFileSync(path, {encoding: 'utf8'})).history);
        } catch (err) {
            return new ActionStore(reducer);
        }
    }

    get storeActions() {
        return store => next => action => {
            this.record(action);
            return next(action);
        }
    }

    record(action) {
        this.history.push(action);
    }

    createStore(reducer) {
        this.history.forEach(this._store.dispatch.bind(this._store));
        return redux.createStore(reducer || this.reducer, this._store.getState());
    }

    toJson(path) {
        fs.writeFileSync(path, JSON.stringify({
            history: this.history
        }));
    }

    setPersistence(path) {
        process.on('beforeExit', () => this.toJson(path));
        process.on('SIGINT', () => {
            this.toJson(path);
        });
        return this;
    }
}

module.exports = ActionStore;


text:
package com.intellij.openapi.components;

import com.intellij.openapi.util.Pair;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @deprecated Use {@link StateSplitterEx}
 */
public interface StateSplitter {
  List<Pair<Element, String>> splitState(@NotNull  Element e);

  void mergeStatesInto(Element target, Element[] elements);
}