text:
'use strict';

const Hapi = require('@hapi/hapi');
const Code = require('@hapi/code');
const Lab = require('@hapi/lab');
const Boom = require('@hapi/boom');

const lab = exports.lab = Lab.script();

const expect = Code.expect;

const describe = lab.describe;
const it = lab.it;
const beforeEach = lab.beforeEach;
let server;

beforeEach(async () => {

    try {
        server = new Hapi.Server();
        await server.start();
    }
    catch (err) {
        console.error(err);
        process.exit(1);
    }
});

describe('Plugin registration', () => {

    it('should throw error if no options are specified', (done) => {

        try {
            server.register({
                plugin: require('../'),
                options: {}
            }).then(() => {
            }).catch((e) => expect(e).to.be.an.instanceof(Error));
        }
        catch (e) {
            done();
        }
    });

    it('should fail if no options are specified', async () => {

        await expect(server.register({
            register: require('../'),
            options: {}
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if no validVersions are specified', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if validVersions is not an array', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: 1,
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);

    });

    it('should fail if validVersions is an empty array', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [],
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if validVersions contains non integer values', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: ['1', 2.2],
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if no defaultVersion is specified', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if defaultVersion is not an integer', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: '1',
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if defaultVersion is not an element of validVersions', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 3,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if defaultVersion is not an element of validVersions', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 3,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if no vendorName is specified', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 1
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if vendorName is not a string', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 1,
                vendorName: 33
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should fail if passiveMode is not a boolean', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 1,
                vendorName: 33,
                passiveMode: []
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should succeed if all required options are provided correctly', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        })).to.reject(Error, /Invalid plugin options/);
    });

    it('should succeed if all options are provided correctly', async () => {

        await expect(server.register({
            register: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 1,
                vendorName: 'mysuperapi',
                versionHeader: 'myversion',
                passiveMode: true
            }
        })).to.reject(Error, /Invalid plugin options/);
    });
});

describe('Versioning', () => {

    beforeEach(async () => {

        await server.register({
            plugin: require('../'),
            options: {
                validVersions: [0, 1, 2],
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        });
    });

    describe(' -> basic versioning', () => {

        beforeEach(() => {

            server.route({
                method: 'GET',
                path: '/unversioned',
                handler: function (request, h) {

                    const response = {
                        version: request.pre.apiVersion,
                        data: 'unversioned'
                    };

                    return response;
                }
            });

            server.route({
                method: 'GET',
                path: '/v0/versioned',
                handler: function (request, h) {

                    const response = {
                        version: 0,
                        data: 'versioned'
                    };

                    return response;
                }
            });

            server.route({
                method: 'GET',
                path: '/v1/versioned',
                handler: function (request, h) {

                    const response = {
                        version: request.pre.apiVersion,
                        data: 'versioned'
                    };

                    return response;
                }
            });

            server.route({
                method: 'GET',
                path: '/v2/versioned',
                handler: function (request, h) {

                    const response = {
                        version: request.pre.apiVersion,
                        data: 'versioned'
                    };

                    return response;
                }
            });
        });

        it('returns version 2 if custom header is valid', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'api-version': '2'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(2);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns version 0 if custom header is valid', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'api-version': '0'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(0);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns version 2 if accept header is valid', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'Accept': 'application/vnd.mysuperapi.v2+json'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(2);
            expect(response.result.data).to.equal('versioned');
        });

        it('sets pre.apiVersion properly', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/v2/versioned'
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(2);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns default version if no header is sent', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned'
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns default version response header if no request header is sent', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned'
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('versioned');
            expect(response.headers['api-version']).to.equal(1);
        });

        it('returns version response header if response header is present', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'api-version': '2'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(2);
            expect(response.result.data).to.equal('versioned');
            expect(response.headers['api-version']).to.equal(2);
        });

        it('returns default version if custom header is invalid', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'api-version': 'asdf'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns default version if custom header is null', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'api-version': null
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns default version if accept header is invalid', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'Accept': 'application/someinvalidapi.vasf+json'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns default version if accept header has an invalid vendor-name', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'Accept': 'application/vnd.someinvalidapi.v2+json'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('versioned');
        });

        it('returns a 400 if invalid api version is requested (not included in validVersions)', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/versioned',
                headers: {
                    'api-version': '3'
                }
            });
            expect(response.statusCode).to.equal(400);
        });

        it('returns the same response for an unversioned route no matter what version is requested - version 1', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/unversioned',
                headers: {
                    'api-version': '1'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('unversioned');
        });

        it('returns the same response for an unversioned route no matter what version is requested - version 2', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/unversioned',
                headers: {
                    'api-version': '2'
                }
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(2);
            expect(response.result.data).to.equal('unversioned');
        });

        it('returns the same response for an unversioned route no matter what version is requested - no version (=default)', async () => {

            const response = await server.inject({
                method: 'GET',
                url: '/unversioned'
            });
            expect(response.statusCode).to.equal(200);
            expect(response.result.version).to.equal(1);
            expect(response.result.data).to.equal('unversioned');
        });
    });

    it('preserves query parameters after url-rewrite', async () => {

        server.route({
            method: 'GET',
            path: '/v1/versionedWithParams',
            handler: function (request, h) {

                const response = {
                    params: request.query
                };

                return response;
            }
        });

        const response = await server.inject({
            method: 'GET',
            url: '/versionedWithParams?test=1'
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.params).to.equal({
            test: '1'
        });
    });

    it('should work with CORS enabled', async () => {

        server.route({
            method: 'GET',
            path: '/corstest',
            handler: function (request, h) {

                return 'Testing CORS!';
            },
            config: {
                cors: {
                    origin: ['*'],
                    headers: ['Accept', 'Authorization']
                }
            }
        });

        const response = await server.inject({
            method: 'OPTIONS',
            url: '/corstest',
            headers: {
                'Origin': 'http://www.example.com',
                'Access-Control-Request-Method': 'GET',
                'Access-Control-Request-Headers': 'accept, authorization'
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.headers).to.include({
            'access-control-allow-origin': 'http://www.example.com'
        });

        expect(response.headers).to.include('access-control-allow-methods');
        expect(response.headers['access-control-allow-methods'].split(',')).to.include('GET');

        expect(response.headers).to.include('access-control-allow-headers');
        expect(response.headers['access-control-allow-headers'].split(',')).to.include(['Accept', 'Authorization']);
    });

    it('should 400 when an OPTIONS request has a malformed access-control-request-method header', async () => {

        server.route({
            method: 'GET',
            path: '/corstest',
            handler: function (request, h) {

                return 'Testing CORS!';
            },
            config: {
                cors: {
                    origin: ['*'],
                    headers: ['Accept', 'Authorization']
                }
            }
        });

        const response = await server.inject({
            method: 'OPTIONS',
            url: '/corstest',
            headers: {
                'Origin': 'http://www.example.com',
                'Access-Control-Request-Method': ''
            }
        });
        expect(response.statusCode).to.equal(400);
    });

    it('handles invalid request methods properly', async () => {

        const response = await server.inject({
            method: 'FAKE',
            url: '/route'
        });
        expect(response.statusCode).to.equal(404);
    });
});

describe(' -> vendor name ', () => {

    it('should accept non-alphanumeric characters', async () => {

        await server.register({
            plugin: require('../'),
            options: {
                validVersions: [0, 1, 2],
                defaultVersion: 1,
                vendorName: 'my.super-Api!'
            }
        });

        server.route({
            method: 'GET',
            path: '/v2/versioned',
            handler: function (request, h) {

                const response = {
                    version: 2,
                    data: 'versioned'
                };

                return response;
            }
        });

        const response = await server.inject({
            method: 'GET',
            url: '/versioned',
            headers: {
                'Accept': 'application/vnd.my.super-Api!.v2+json'
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(2);
        expect(response.result.data).to.equal('versioned');
    });

    it('should accept several period characters', async () => {

        await server.register({
            plugin: require('../'),
            options: {
                validVersions: [0, 1, 10],
                defaultVersion: 1,
                vendorName: 'company.departmanet.project.api'
            }
        });

        server.route({
            method: 'GET',
            path: '/v10/versioned',
            handler: function (request, h) {

                const response = {
                    version: 10,
                    data: 'versioned'
                };

                return response;
            }
        });

        const response = await server.inject({
            method: 'GET',
            url: '/versioned',
            headers: {
                'Accept': 'application/vnd.company.departmanet.project.api.v10+json'
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(10);
        expect(response.result.data).to.equal('versioned');
    });
});

describe(' -> path parameters', () => {

    beforeEach(async () => {

        await server.register({
            plugin: require('../'),
            options: {
                validVersions: [0, 1, 2],
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        });
        server.route({
            method: 'GET',
            path: '/unversioned/{catchAll*}',
            handler: function (request, h) {

                const response = {
                    version: request.pre.apiVersion,
                    data: 'unversionedCatchAll'
                };

                return response;
            }
        });

        server.route({
            method: 'GET',
            path: '/v2/versioned/{catchAll*3}',
            handler: function (request, h) {

                const response = {
                    version: request.pre.apiVersion,
                    data: 'versionedCatchAll'
                };

                return response;
            }
        });

        server.route({
            method: 'GET',
            path: '/unversioned/withPathParam/{unversionedPathParam}',
            handler: function (request, h) {

                const response = {
                    version: request.pre.apiVersion,
                    data: request.params.unversionedPathParam
                };

                return response;
            }
        });

        server.route({
            method: 'GET',
            path: '/v1/versioned/withPathParam/{versionedPathParam}',
            handler: function (request, h) {

                const response = {
                    version: request.pre.apiVersion,
                    data: request.params.versionedPathParam
                };

                return response;
            }
        });

        server.route({
            method: 'GET',
            path: '/v2/versioned/multiSegment/{segment*2}',
            handler: function (request, h) {

                const response = {
                    version: request.pre.apiVersion,
                    data: request.params.segment
                };

                return response;
            }
        });

        server.route({
            method: 'GET',
            path: '/v2/versioned/optionalPathParam/{optional?}',
            handler: function (request, h) {

                const response = {
                    version: request.pre.apiVersion,
                    data: request.params.optional
                };

                return response;
            }
        });
    });

    it('resolves unversioned catch all routes', async () => {

        const response = await server.inject({
            method: 'GET',
            url: '/unversioned/catch/all/route'
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(1);
        expect(response.result.data).to.equal('unversionedCatchAll');
    });

    it('resolves versioned catch all routes', async () => {

        const apiVersion = 2;

        const response = await server.inject({
            method: 'GET',
            url: '/versioned/catch/all/route',
            headers: {
                'api-version': apiVersion
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(apiVersion);
        expect(response.result.data).to.equal('versionedCatchAll');
    });

    it('resolves unversioned routes with path parameters', async () => {

        const pathParam = '123456789';

        const response = await server.inject({
            method: 'GET',
            url: '/unversioned/withPathParam/' + pathParam
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(1);
        expect(response.result.data).to.equal(pathParam);
    });

    it('resolves versioned routes with path parameters', async () => {

        const pathParam = '123456789';
        const apiVersion = 1;

        const response = await server.inject({
            method: 'GET',
            url: '/versioned/withPathParam/' + pathParam,
            headers: {
                'api-version': apiVersion
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(apiVersion);
        expect(response.result.data).to.equal(pathParam);
    });

    it('resolves multi segment path parameters', async () => {

        const apiVersion = 2;
        const pathParam = 'multi/segment';

        const response = await server.inject({
            method: 'GET',
            url: '/versioned/multiSegment/' + pathParam,
            headers: {
                'api-version': apiVersion
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(apiVersion);
        expect(response.result.data).to.equal(pathParam);
    });

    it('resolves optional path parameters - without optional value', async () => {

        const apiVersion = 2;
        const pathParam = (parseInt(server.version.match(/^(\d+)/)[1]) >= 17 ? '' : undefined);

        const response = await server.inject({
            method: 'GET',
            url: '/versioned/optionalPathParam/',
            headers: {
                'api-version': apiVersion
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(apiVersion);
        expect(response.result.data).to.equal(pathParam);
    });

    it('resolves optional path parameters - with optional value', async () => {

        const apiVersion = 2;
        const pathParam = 'test';

        const response = await server.inject({
            method: 'GET',
            url: '/versioned/optionalPathParam/' + pathParam,
            headers: {
                'api-version': apiVersion
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(apiVersion);
        expect(response.result.data).to.equal(pathParam);
    });
});

describe('Versioning with passive mode', () => {

    beforeEach(async () => {

        await server.register({
            plugin: require('../'),
            options: {
                validVersions: [1, 2],
                defaultVersion: 1,
                vendorName: 'mysuperapi',
                passiveMode: true
            }
        });

        server.route({
            method: 'GET',
            path: '/unversioned',
            handler: function (request, h) {

                const response = {
                    data: 'unversioned'
                };

                return response;
            }
        });

        server.route({
            method: 'GET',
            path: '/v1/versioned',
            handler: function (request, h) {

                const response = {
                    data: 'versioned',
                    version: request.pre.apiVersion
                };

                return response;
            }
        });
    });

    it('returns no version if no header is supplied', async () => {

        const response = await server.inject({
            method: 'GET',
            url: '/unversioned'
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(undefined);
        expect(response.result.data).to.equal('unversioned');
    });

    it('returns version if header is supplied with passive mode on', async () => {

        const response = await server.inject({
            method: 'GET',
            url: '/versioned',
            headers: {
                'Accept': 'application/vnd.mysuperapi.v1+json'
            }
        });
        expect(response.statusCode).to.equal(200);
        expect(response.result.version).to.equal(1);
        expect(response.result.data).to.equal('versioned');
    });
});

describe('Malformed URLs with a catchall route', () => {

    beforeEach(async () => {

        await server.register({
            plugin: require('../'),
            options: {
                validVersions: [0, 1, 2],
                defaultVersion: 1,
                vendorName: 'mysuperapi'
            }
        });
        server.route({
            method: 'GET',
            path: '/{path*}',
            handler: function (request, h) {

                throw Boom.notFound('Not found');
            }
        });
    });

    it('returns 400 for an invalid path', async () => {

        const response = await server.inject({
            method: 'GET',
            url: '/%C0%AE%C0%AE'
        });
        expect(response.statusCode).to.equal(400);
    });

    it('returns 404 for a missing patch', async () => {

        const response = await server.inject({
            method: 'GET',
            url: '/validencoding'
        });
        expect(response.statusCode).to.equal(404);
    });
});


text:
{-# LANGUAGE
    OverloadedStrings
  , ScopedTypeVariables
  , TemplateHaskell
  , TypeFamilies
  #-}
module Test.Util where

import Prelude.Compat

import Data.Aeson hiding (Result)
import Data.Aeson.Parser ()
import Data.Attoparsec.Lazy
import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Lazy.Char8 (unpack)
import Data.List.Compat (intersperse)
import Data.Proxy.Compat
import Test.Tasty.HUnit
import qualified Data.Aeson.Parser as A
import qualified Data.Aeson.Types  as A
import qualified Data.Vector       as V

import Data.JSON.Schema
import Data.JSON.Schema.Validate

-- | Serializes a value to an aeson Value and validates that against the type's schema
valid :: forall a . (Show a, ToJSON a, FromJSON a, JSONSchema a) => a -> Assertion
valid v = do
  case eitherDecode (encode v) of
    Left err -> error err
    Right r  -> case V.toList $ validate sch r of
      []   -> assertBool "x" True
      errs -> assertFailure ("schema validation for " ++ show v ++ " value: " ++ show r ++ " schema: " ++ show sch ++ " errors: " ++ show errs)
  where
    sch = schema (Proxy :: Proxy a)

encDec :: (FromJSON a, ToJSON a) => a -> Either String a
encDec a = case (parse A.value . encode) a of
  Done _ r -> case fromJSON r of A.Success v -> Right v; Error s -> Left $ "fromJSON r=" ++ show r ++ ", s=" ++ s
  Fail _ ss e -> Left . concat $ intersperse "," (ss ++ [e])

unsafeParse :: ByteString -> Value
unsafeParse b = fromResult . parse A.value $ b
  where
    fromResult (Done _ r) = r
    fromResult _ = error $ "unsafeParse failed on: " ++ unpack b

eq :: (Show a, Eq a) => a -> a -> Assertion
eq = (@=?)

bidir ::  (FromJSON a, ToJSON a, Show a, Eq a) => ByteString -> a -> IO ()
bidir s d = do
  eq (unsafeParse s)
     (toJSON d)
  eq (Right d)
     (encDec d)

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
import { IDevice, DeviceOrientation, DeviceType } from '../mobilePreview/MobilePreview';
export interface IMobilePreviewDeviceViewProps {
    currentDevice: IDevice;
    currentOrientation: DeviceOrientation;
    deviceType: DeviceType;
    url: string;
}
export default class MobilePreviewDeviceView extends React.Component<IMobilePreviewDeviceViewProps, {}> {
    constructor(props: IMobilePreviewDeviceViewProps);
    render(): React.ReactElement<IMobilePreviewDeviceViewProps>;
}
//# sourceMappingURL=MobilePreviewDeviceView.d.ts.map


text:
import sys
sys.path.append('/notebooks')

import wave
import re
import struct
import glob
import params as par
from scipy import fromstring, int16
import numpy as np
import os.path
from keras.models import Sequential, load_model
from keras.layers import Dense, LSTM, Dropout
from keras.callbacks import Callback
from keras import backend as K

test_files = glob.glob(par.base_data + 'input/*.wav')
print(test_files)
#test_files = test_files[5]

def get_dataset(filename):
    wavfile = filename
    wr = wave.open(wavfile, "rb")
    origin = wr.readframes(wr.getnframes())
    data = origin[:par.fr * 4 * 60]
    wr.close()
    X = np.frombuffer(data, dtype="int16")/ (par.bit_depth * 1.0)
    X = np.reshape(X, (-1, par.l1_input_length, par.l1_channel_size))
    #print(X.shape)
    #print(len(X))
    return X

import l3_model as level3

for test_file in test_files:
    data = get_dataset(test_file)
    temp = level3.encoder([data])
    res = level3.decoder([temp[0]])
    row_data = np.array(res)
    mdata = np.reshape(res, (-1)) * par.bit_depth
    mdata = mdata.astype('int16')
    savename = re.sub('.*\/', '', test_file)
    savename = re.sub('.*\\\\', '', savename)
    outf = par.base_data + 'output/' + savename
    outd = struct.pack("h" * len(mdata), *mdata)
    ww = wave.open(outf, 'w')
    ww.setnchannels(2)
    ww.setsampwidth(2)
    ww.setframerate(par.fr)
    ww.writeframes(outd)
    ww.close()


text:
\hypertarget{group__group_interpolation}{}\section{Interpolation Functions}
\label{group__group_interpolation}\index{Interpolation Functions@{Interpolation Functions}}
\subsection*{Modules}
\begin{DoxyCompactItemize}
\item
\hyperlink{group___linear_interpolate}{Linear Interpolation}
\item
\hyperlink{group___bilinear_interpolate}{Bilinear Interpolation}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
These functions perform 1-\/ and 2-\/dimensional interpolation of data. Linear interpolation is used for 1-\/dimensional data and bilinear interpolation is used for 2-\/dimensional data.


text:
![nmesimpledrawing](https://cloud.githubusercontent.com/assets/489459/8213460/e0bb6944-1519-11e5-9070-d00f1c173c37.png)
# hxDaedalus-simpledrawing

Simple drawing with hxDaedalus allows you to use simple draw commands the same way across a range of target structures. ( NME/Openfl, Flambe, Luxe, JS, SVG, Java Swing ).

Requires:

[hxDaedalus](https://github.com/Justinfront/hxDaedalus)

On windows you can just run

<code>
haxe compileAll.hxml
</code>

and it will create a range of targets.


text:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
           android:fromXDelta="0"
           android:toXDelta="8"
           android:duration="50"
           android:repeatCount="1" />


text:
<?php

namespace Doctrine\DBAL\Tests;

use Doctrine\DBAL\Exception;
use PHPUnit\Framework\TestCase;
use stdClass;

use function sprintf;

class ExceptionTest extends TestCase
{
    public function testDriverRequiredWithUrl(): void
    {
        $url       = 'mysql://localhost';
        $exception = Exception::driverRequired($url);

        self::assertSame(
            sprintf(
                "The options 'driver' or 'driverClass' are mandatory if a connection URL without scheme " .
                'is given to DriverManager::getConnection(). Given URL: %s',
                $url,
            ),
            $exception->getMessage(),
        );
    }

    public function testInvalidPlatformTypeObject(): void
    {
        $exception = Exception::invalidPlatformType(new stdClass());

        self::assertSame(
            "Option 'platform' must be a subtype of 'Doctrine\DBAL\Platforms\AbstractPlatform', "
                . "instance of 'stdClass' given",
            $exception->getMessage(),
        );
    }

    public function testInvalidPlatformTypeScalar(): void
    {
        $exception = Exception::invalidPlatformType('some string');

        self::assertSame(
            "Option 'platform' must be an object and subtype of 'Doctrine\DBAL\Platforms\AbstractPlatform'. "
                . "Got 'string'",
            $exception->getMessage(),
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="io.grpc.auth.ClientAuthInterceptorTests" tests="3" skipped="0" failures="0" errors="0" timestamp="2015-03-23T00:36:37" hostname="ip-172-31-8-225" time="0.428">
  <properties/>
  <testcase name="testWithOAuth2Credential" classname="io.grpc.auth.ClientAuthInterceptorTests" time="0.376"/>
  <testcase name="testCopyCredentialToHeaders" classname="io.grpc.auth.ClientAuthInterceptorTests" time="0.025"/>
  <testcase name="testCredentialsThrows" classname="io.grpc.auth.ClientAuthInterceptorTests" time="0.016"/>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>


text:
<?php

if(!isset($_REQUEST['cid']) || !isset($_REQUEST['key'])) die('Invalid usage - missing param');
$cid = $_REQUEST['cid'];
$key = $_REQUEST['key'];

define('CID', $cid);
define('READ_ONLY_SESSION',true);
require_once('../../../include.php');

if (!isset($_SESSION['client']['utils_recordbrowser'][$key])) {
    die('Invalid request');
}

$crits = $_SESSION['client']['utils_recordbrowser'][$key]['crits'];
$cols = $_SESSION['client']['utils_recordbrowser'][$key]['cols'];
$order = $_SESSION['client']['utils_recordbrowser'][$key]['order'];
$admin = $_SESSION['client']['utils_recordbrowser'][$key]['admin'];
$tab = $_SESSION['client']['utils_recordbrowser'][$key]['tab'];
$more_table_properties = $_SESSION['client']['utils_recordbrowser'][$key]['more_table_properties'];
$limit = $_SESSION['client']['utils_recordbrowser'][$key]['limit'];

ModuleManager::load_modules();
if (!Utils_RecordBrowserCommon::get_access($tab, 'print') && !Base_AclCommon::i_am_admin())
	die('Access denied');

set_time_limit(0);

$rb = ModuleManager::new_instance('Utils_RecordBrowser', null, 'print_rb');
$rb->construct($tab);
$rb->set_inline_display();
$rb->set_header_properties($more_table_properties);
$rb->disable_pagination();

ob_start();
$rb->show_data($crits, $cols, $order, $admin, false, true, $limit);
$html = ob_get_clean();

$limit_info = '';
if (is_array($limit)) {
    $offset = $limit['offset'];
    $per_page = $limit['numrows'];
    $start = $offset + 1;
    $end = $offset + $per_page;
    $total = Utils_RecordBrowserCommon::get_records_count($tab, $crits, $admin, $order);
    if ($end > $total)
        $end = $total;
    $limit_info = __('Records %s to %s of %s', array($start, $end, $total)) . "\n";
}

$tcpdf = Libs_TCPDFCommon::new_pdf();

$filters = Utils_RecordBrowserCommon::crits_to_words($tab, $crits, false);
$filters = str_replace(' and ', "\n", $filters);
$filters = str_replace(' is equal to', ':', $filters);

$subject = $limit_info . $filters;
Libs_TCPDFCommon::prepare_header($tcpdf, _V(DB::GetOne('SELECT caption FROM recordbrowser_table_properties WHERE tab=%s', array($tab))), $subject, false);
Libs_TCPDFCommon::add_page($tcpdf);

Libs_TCPDFCommon::SetFont($tcpdf, Libs_TCPDFCommon::$default_font, '', 6);

$html = Libs_TCPDFCommon::stripHTML(str_replace(array('
',' '),array('
',' '),$html));
Libs_TCPDFCommon::writeHTML($tcpdf, $html, false);

$buffer = Libs_TCPDFCommon::output($tcpdf);

header('Content-Type: application/pdf');
header('Content-Length: '.strlen($buffer));
header('Content-disposition: inline; filename="recordset_'.$tab.'.pdf"');

print($buffer);

?>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Anise Cookie Cordials</title>
      <categories>
        <cat>Cookie</cat></categories>
      <yield>50</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>2 3/4</qty>
          <unit>cups</unit></amt>
        <item>All-purpose flour</item></ing>
      <ing>
        <amt>
          <qty>1 1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Baking powder</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Butter; softened</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit/></amt>
        <item>Eggs</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Anise flavored liqueur</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Water</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Anise seed</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>packages</unit></amt>
        <item>(12-oz) Nestle Toll House little bits semi-sweet chocolate</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Coarsely chopped toasted almonds</item></ing></ingredients>
    <directions>
      <step>  In medium bowl, combine flour and baking powder; set aside. In large bowl,
  combine sugar and butter; beat until creamy. Add eggs, anise flavored
  liqueur, water and anise seed; beat until well blended. Gradually beat in
  flour mixture. Stir in Nestle Toll House Little Bits semi-sweet chocolate
  and almonds. Cover; chill several hours. Preheat oven to 375 degrees.
  Divide dough into 4 pieces. With floured hands, shape each piece into
  15-1/2x2x1/2-inch loaf. Place loaves 4 inches apart on greased cookie
  sheets. Bake at 375 degrees for 15 minutes. Remove from oven. Cut into
  1-inch slices. Place slices back on cookie sheets. Bake at 375 degrees for
  7 minutes. Turn cookies over. Bake at 375 degrees for 7 minutes. Cool
  completely on wire racks. Makes about
    4-1/4    dozen 1-inch cookies.

  From <Favorite Recipes: Nestle Sweet Treats>.  Downloaded from Glen's MM
  Recipe Archive, http://www.erols.com/hosey.

</step></directions></recipe></recipeml>


text:
package org.zaproxy.zap.extension.saml;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import org.apache.log4j.Logger;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.ExtensionPopupMenuItem;
import org.zaproxy.zap.extension.ExtensionPopupMenu;
import org.zaproxy.zap.extension.saml.ui.SamlExtentionSettingsUI;
import org.zaproxy.zap.view.popup.ExtensionPopupMenuMessageContainer;

public class SAMLExtension extends ExtensionAdaptor {

    protected static final Logger log = Logger.getLogger(SAMLExtension.class);

    @SuppressWarnings("deprecation")
    @Override
    public void hook(ExtensionHook extensionHook) {
        super.hook(extensionHook);

        try {
            SAMLConfiguration conf = SAMLConfiguration.getInstance();
            SamlI18n.init();
            if (conf != null) {
                conf.initialize();
            } else {
                log.error("SAML Configuration can't be loaded. Extention will not be loaded...");
            }
            if (getView() != null && conf != null) {
                final SAMLProxyListener proxyListener = new SAMLProxyListener();
                extensionHook.addProxyListener(proxyListener);

                ExtensionPopupMenu samlMenu =
                        new ExtensionPopupMenuMessageContainer(
                                SamlI18n.getMessage("saml.popup.mainmenu"));
                ExtensionPopupMenuItem samlResendMenuItem =
                        new SAMLResendMenuItem(SamlI18n.getMessage("saml.popup.view_resend"));

                samlMenu.add(samlResendMenuItem);
                extensionHook.getHookMenu().addPopupMenuItem(samlMenu);

                JMenuItem samlActiveEditorMenu =
                        new JMenuItem(SamlI18n.getMessage("saml.toolmenu.settings"));
                samlActiveEditorMenu.addActionListener(
                        new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                SamlExtentionSettingsUI settingUI = new SamlExtentionSettingsUI();
                                settingUI.setVisible(true);
                            }
                        });
                extensionHook.getHookMenu().addToolsMenuItem(samlActiveEditorMenu);
            }
        } catch (SAMLException e) {
            log.error("SAML Extension can't be loaded. Configuration not found or invalid", e);
        }
    }

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


text:
package com.felix.zhiban.bean.filmdetail;

import com.felix.zhiban.bean.top250.Avatars;

/**
 * Created by XiaGF on 2017/4/28.
 */

public class FilmPeople {

    private String alt;

    private Avatars avatars;

    private String name;

    private String id;

    private int type;

    public String getAlt() {
        return alt;
    }

    public void setAlt(String alt) {
        this.alt = alt;
    }

    public Avatars getAvatars() {
        return avatars;
    }

    public void setAvatars(Avatars avatars) {
        this.avatars = avatars;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}


text:
*
*  PROJECT:     VehicleBlips
*  LICENSE:     GNU GPLv3
*  FILE:        :VehicleBlips/cVehicleBlips.lua
*  PURPOSE:     Vehicle blips.
*  DEVELOPERS:  John_Michael <JohnMichaelFFS@gmail.com>
*
********************************************************************************]]
local vehicleBlipRoot = createElement("vehicleBlipRoot", "vehicleBlipRoot")

--This function creates a blip for all currently streamed-in vehicles when the resource starts.
local function resourceStart()
	for _, vehicle in ipairs(getElementsByType("vehicle"), root, true) do
		if vehicle ~= getPedOccupiedVehicle(localPlayer) then
			local blip = createBlipAttachedTo(vehicle, 0, 1, 150, 150, 150, 255, -10, 75)
			setElementParent(blip, vehicleBlipRoot)
		end
	end
end
addEventHandler("onClientResourceStart", root, resourceStart)

--This function destroys a vehicle's blip when it streams out.
local function streamOut()
	for _, blip in ipairs(getElementChildren(vehicleBlipRoot)) do
		if getElementAttachedTo(blip) == source then
			destroyElement(blip)
		end
	end
	removeEventHandler("onClientElementStreamOut", source, streamOut)
	removeEventHandler("onClientElementDestroy", source, streamOut)
end

--This function creates a blip when a vehicle streams in.
local function streamIn()
	if getElementType(source) ~= "vehicle" then
		return
	end

	--Check if the vehicle already has a blip.
	for _, blip in ipairs(getElementChildren(vehicleBlipRoot)) do
		if getElementAttachedTo(blip) == source then
			return
		end
	end

	local blip = createBlipAttachedTo(source, 0, 1, 150, 150, 150, 255, -10, 75)
	setElementParent(blip, vehicleBlipRoot)
	addEventHandler("onClientElementStreamOut", source, streamOut)
	addEventHandler("onClientElementDestroy", source, streamOut)
end
addEventHandler("onClientElementStreamIn", root, streamIn)


text:
package test;

import java.util.Iterator;

import nodes.NodeSpecialist;

public class Map implements NodeSpecialist<ConcreteNode> {

	@Override
	public int getHeuristicDist(ConcreteNode start, ConcreteNode goal) {
		return 0;
	}

	@Override
	public Iterator<ConcreteNode> getAdjacents(ConcreteNode node) {
		return node.getAdjacents();
	}

	@Override
	public int getDistBetween(ConcreteNode node, ConcreteNode neighbour) {
		return node.getDistTo(neighbour);
	}

}


text:
import sys
import unittest
import zlib
import gzip

from mock import Mock

from libcloud.utils.py3 import httplib, b, StringIO, PY3
from libcloud.common.base import Response, XmlResponse, JsonResponse
from libcloud.common.types import MalformedResponseError

class ResponseClassesTests(unittest.TestCase):
    def setUp(self):
        self._mock_response = Mock()
        self._mock_response.getheaders.return_value = []
        self._mock_response.status = httplib.OK
        self._mock_response._original_data = None
        self._mock_connection = Mock()

    def test_XmlResponse_class(self):
        self._mock_response.read.return_value = '<foo>bar</foo>'
        response = XmlResponse(response=self._mock_response,
                               connection=self._mock_connection)

        parsed = response.parse_body()
        self.assertEqual(parsed.tag, 'foo')
        self.assertEqual(parsed.text, 'bar')

    def test_XmlResponse_class_malformed_response(self):
        self._mock_response.read.return_value = '<foo>'

        try:
            XmlResponse(response=self._mock_response,
                        connection=self._mock_connection)
        except MalformedResponseError:
            pass
        else:
            self.fail('Exception was not thrown')

    def test_XmlResponse_class_zero_length_body_strip(self):
        self._mock_response.read.return_value = ' '

        response = XmlResponse(response=self._mock_response,
                               connection=self._mock_connection)

        parsed = response.parse_body()
        self.assertEqual(parsed, '')

    def test_JsonResponse_class_success(self):
        self._mock_response.read.return_value = '{"foo": "bar"}'
        response = JsonResponse(response=self._mock_response,
                                connection=self._mock_connection)

        parsed = response.parse_body()
        self.assertEqual(parsed, {'foo': 'bar'})

    def test_JsonResponse_class_malformed_response(self):
        self._mock_response.read.return_value = '{"foo": "bar'

        try:
            JsonResponse(response=self._mock_response,
                         connection=self._mock_connection)
        except MalformedResponseError:
            pass
        else:
            self.fail('Exception was not thrown')

    def test_JsonResponse_class_zero_length_body_strip(self):
        self._mock_response.read.return_value = ' '

        response = JsonResponse(response=self._mock_response,
                                connection=self._mock_connection)

        parsed = response.parse_body()
        self.assertEqual(parsed, '')

    def test_deflate_encoding(self):
        original_data = 'foo bar ponies, wooo zlib'
        compressed_data = zlib.compress(b(original_data))

        self._mock_response.read.return_value = compressed_data
        self._mock_response.getheaders.return_value = \
            {'Content-Encoding': 'deflate'}

        response = Response(response=self._mock_response,
                            connection=self._mock_connection)

        body = response.parse_body()
        self.assertEqual(body, original_data)

        self._mock_response.getheaders.return_value = \
            {'Content-Encoding': 'zlib'}

        response = Response(response=self._mock_response,
                            connection=self._mock_connection)

        body = response.parse_body()
        self.assertEqual(body, original_data)

    def test_gzip_encoding(self):
        original_data = 'foo bar ponies, wooo gzip'

        if PY3:
            from io import BytesIO
            string_io = BytesIO()
        else:
            string_io = StringIO()

        stream = gzip.GzipFile(fileobj=string_io, mode='w')
        stream.write(b(original_data))
        stream.close()
        compressed_data = string_io.getvalue()

        self._mock_response.read.return_value = compressed_data
        self._mock_response.getheaders.return_value = \
            {'Content-Encoding': 'gzip'}

        response = Response(response=self._mock_response,
                            connection=self._mock_connection)

        body = response.parse_body()
        self.assertEqual(body, original_data)

        self._mock_response.getheaders.return_value = \
            {'Content-Encoding': 'x-gzip'}

        response = Response(response=self._mock_response,
                            connection=self._mock_connection)

        body = response.parse_body()
        self.assertEqual(body, original_data)

if __name__ == '__main__':
    sys.exit(unittest.main())


text:
import re

from taggit_suggest.models import TagKeyword, TagRegex
from taggit.models import Tag

def _suggest_keywords(content):
    """
    Suggest by keywords
    """
    suggested_keywords = set()
    keywords = TagKeyword.objects.all()

    for k in keywords:
        # Use the stem if available, otherwise use the whole keyword
        if k.stem:
            if k.stem in content:
                suggested_keywords.add(k.tag_id)
        elif k.keyword in content:
            suggested_keywords.add(k.tag_id)

    return suggested_keywords

def _suggest_regexes(content):
    """
    Suggest by regular expressions
    """
    # Grab all regular expressions and compile them
    suggested_regexes = set()
    regex_keywords = TagRegex.objects.all()

    # Look for our regular expressions in the content
    for r in regex_keywords:
        if re.search(r.regex, content):
            suggested_regexes.add(r.tag_id)

    return suggested_regexes

def suggest_tags(content):
    """
    Suggest tags based on text content
    """
    suggested_keywords = _suggest_keywords(content)
    suggested_regexes  = _suggest_regexes(content)
    suggested_tag_ids  = suggested_keywords | suggested_regexes

    return Tag.objects.filter(id__in=suggested_tag_ids)


text:
#include "aco.h"
#include <math.h>

int main()
{
    printLogo();
    printf("MODALITA' DI TEST\n");

    // CONFIGURAZIONE PARAMETRI DI ESECUZIONE
    ACOVARS.verbose = 0;
    ACOVARS.sizeMetaPopolazione = 5;
    ACOVARS.qzero = 75;
    ACOVARS.useLocalSearch = 0;
    ACOVARS.showTours = 0;

    bool faiTest = 1;
    // AGGIORNA L'INDIVIDUO I NELLA POPOLAZIONE DI SOLUZIONI SE E SOLO SE L'ANT I HA FORNITO UN PERCORSO MENO COSTOSO
    bool aggiornaSoloSeNuovoCostoInferioreAlVecchio = 1;
    uint16_t nGenerazioni = 0, costoMiglioreSolPrecedente = 0;
    uint16_t nTentativiMiglioramento = ACOVARS.tentativiMiglioramento;
    uint16_t nVertici, nAnt, capacita, solPeggioreInit, solMiglioreInit, runSolMigliore = 0, solMiglioreAssoluto = numeric_limits<uint16_t>::max(), runSolMiglioreAssoluto = 0;
    ACOVARS.grafoFile = readIntFromConsole(string("[0] Crea grafo casuale\n[1] Leggi grafo da file\n>> "));
    string filenameLeggi = "";
    if(ACOVARS.grafoFile)
        filenameLeggi = readStringFromConsole(string("Nome del file: "));

    // input della capacità
    ostringstream vertRequest, antRequest, capRequest;
    vertRequest << "Numero vertici [DEFAULT " << ACOVARS.nVertici << "]: ";
    antRequest << "Numero ant [DEFAULT " << ACOVARS.nAnt << "]: ";
    nVertici = getNumberFromConsole(vertRequest.str(),'u');
    nAnt = getNumberFromConsole(antRequest.str(),'u');
    if(nVertici > 0) ACOVARS.nVertici = nVertici;
    if(nAnt > 0) ACOVARS.nAnt = nAnt;

    // ALLOCAZIONE STRUTTURE DATI
    vectorUint richieste(ACOVARS.nVertici); // ARRAY RICHIESTE CLIENTI
    matrixUint pesoArchi(ACOVARS.nVertici, vectorUint(ACOVARS.nVertici));  // MATRICE PESI
    matrixDouble feromoneArchi(ACOVARS.nVertici, vector<double>(ACOVARS.nVertici)); // MATRICE FEROMONE
    matrixUint popolazioneSoluzioni(ACOVARS.nAnt); // POPOLAZIONE SOLUZIONI
    matrixUint popolazioneSoluzioniInit(ACOVARS.nAnt);  // PER RESET
    vectorUint costoSoluzioni(ACOVARS.nAnt); // CACHE COSTO SOLUZIONI
    vectorUint costoSoluzioniInit(ACOVARS.nAnt);    // PER RESET
    AntType coloniaAnt[ACOVARS.nAnt]; // COLONIA ANT

    // MATRICE DELLE DESIDERABILITÀ DEI VERTICI
    for(uint16_t i=0; i<ACOVARS.nAnt; i++)
    {
        for(uint16_t j=0; j<ACOVARS.nVertici; j++)
        {
            desiderabilitaType tmp;
            tmp.vertice = i;
            tmp.value = 0;
            coloniaAnt[i].desiderabilitaVertici.push_back(tmp);
            coloniaAnt[i].flagVerticiVisitati.push_back(0);
        }
    }

    // Inizializzazione strutture dati --------------------------------------
    if(ACOVARS.grafoFile)
    {
        leggiGrafo(filenameLeggi,richieste, pesoArchi, feromoneArchi);
    }
    else
    {
        creaGrafoCasuale(richieste, pesoArchi, feromoneArchi);
        if(readIntFromConsole(string("[0] Non salvare il grafo\n[1] Salva il grafo con nome\n>> ")))
        {
            string filename = readStringFromConsole(string("Nome del file: "));
            salva(filename,richieste,pesoArchi);
        }
    }

    uint16_t tspCapacita = accumulate(richieste.begin(),richieste.end(),0);
    // input della capacità
    capRequest << "Capacita' [DEFAULT " << ACOVARS.maxRichiesta << "][TSP: >=" << tspCapacita << "]: ";
    capacita = getNumberFromConsole(capRequest.str(),'u');

    if (capacita >= ACOVARS.maxRichiesta)
        ACOVARS.capacita = capacita;
    else
        ACOVARS.capacita = ACOVARS.maxRichiesta;

    // INIZIALIZZAZIONE PROPOSTE DI SOLUZIONI

    printf("Inizializzazione popolazione proposte di soluzione (%u candidati)\n",ACOVARS.nAnt);

    if(ACOVARS.useMultiThread)
        initPopolazioneSoluzioniMT(popolazioneSoluzioni, richieste,pesoArchi);
    else
        initPopolazioneSoluzioni(popolazioneSoluzioni, richieste,pesoArchi);

    uint16_t indextmp;
    updateCacheCostiSoluzioni(popolazioneSoluzioni,pesoArchi,costoSoluzioni,indextmp);
    solMiglioreInit = costoSoluzioni[indextmp];
    /* Aggiorno i valori da dare in report */
    indextmp = distance(costoSoluzioni.begin(),max_element(costoSoluzioni.begin(),costoSoluzioni.end()));
    solPeggioreInit = costoSoluzioni[indextmp];

    // Global update al passo 0 --------------------------------------
    printProposteSoluzioni(popolazioneSoluzioni, costoSoluzioni);
    uint16_t migliorSoluzione = distance(costoSoluzioni.begin(),min_element(costoSoluzioni.begin(),costoSoluzioni.end()));
    costoMiglioreSolPrecedente = costoSoluzioni[migliorSoluzione];
    globalUpdate(migliorSoluzione, costoSoluzioni, popolazioneSoluzioni, feromoneArchi);
    printf("\nIntervallo costo soluzioni in fase di init: (%u - %u), media: %f\n",solMiglioreInit,solPeggioreInit,mediaCosti(costoSoluzioni));

    // BACKUP ELEMENTI PER IL RESET
    {
        copiaVettore(costoSoluzioni,costoSoluzioniInit);
        for(uint16_t i=0; i<ACOVARS.nAnt; i++)
        {
            copiaVettore(popolazioneSoluzioni[i],popolazioneSoluzioniInit[i]);
        }
    }

    while(faiTest)
    {
        vectorUint minimiLocali;
        // INPUT DIMENSIONE DELLA METAPOPOLAZIONE, SCEGLI SE FARE RICERCA LOCALE O MENO
        {
            ACOVARS.sizeMetaPopolazione = readIntFromConsole(string("Dimensione della metapopolazione (0 per annullare la ricerca locale):  "));
            ACOVARS.useLocalSearch = (ACOVARS.sizeMetaPopolazione>0);

            if(ACOVARS.useLocalSearch)
                printf("TEST (Metapopolazione di %u soluzioni, %u ant) ----------\n",ACOVARS.sizeMetaPopolazione,ACOVARS.nAnt);
            else
                printf("TEST (No ricerca locale, %u ant) ----------\n",ACOVARS.nAnt);
        }

        time_t start = time(nullptr);
        while(nGenerazioni<ACOVARS.maxGenerazioni)
        {
            for(uint16_t i=0; i<ACOVARS.nAnt; i++)
            {
                if(ACOVARS.verbose) printf("ANT WALK PER ANT %u ******************\n",i);
                antWalk(coloniaAnt[i],pesoArchi, feromoneArchi, richieste);

                if(aggiornaSoloSeNuovoCostoInferioreAlVecchio)
                {
                    // IL TOUR DELL'ANT DIVENTA UNA PROPOSTA DI SOLUZIONE SOLO SE HA DIMINUITO IL COSTO
                    if(costoTour(coloniaAnt[i].tour,pesoArchi)<costoSoluzioni[i])
                        copiaVettore(coloniaAnt[i].tour,popolazioneSoluzioni[i]);
                }
                else
                {
                    //  AGGIORNA A PRESCINDERE
                    copiaVettore(coloniaAnt[i].tour,popolazioneSoluzioni[i]);
                }
            }
            // AGGIORNO I COSTI
            updateCacheCostiSoluzioni(popolazioneSoluzioni,pesoArchi,costoSoluzioni,migliorSoluzione);
            // RICERCA LOCALE
            if(ACOVARS.useLocalSearch)
            {
                localSearch(popolazioneSoluzioni,migliorSoluzione,pesoArchi,richieste,costoSoluzioni);
                updateCacheCostiSoluzioni(popolazioneSoluzioni,pesoArchi,costoSoluzioni,migliorSoluzione);
            }
            // GLOBAL UPDATE
            globalUpdate(migliorSoluzione,costoSoluzioni, popolazioneSoluzioni, feromoneArchi);

            if(costoSoluzioni[migliorSoluzione]<solMiglioreAssoluto)
            {
                solMiglioreAssoluto = costoSoluzioni[migliorSoluzione];
                runSolMiglioreAssoluto = nGenerazioni;
            }

            printf("GENERAZIONE %u: La migliore soluzione corrente ora ha costo %u, media %f\n",nGenerazioni,costoSoluzioni[migliorSoluzione],mediaCosti(costoSoluzioni));

            if(costoSoluzioni[migliorSoluzione] < costoMiglioreSolPrecedente) // HO MIGLIORATO, NO STAGNATION
            {
                printf("Costo migliore ora %u, Costo migliore precedente %u (ho migliorato)\n",costoSoluzioni[migliorSoluzione],costoMiglioreSolPrecedente);
                nTentativiMiglioramento = ACOVARS.tentativiMiglioramento;
                costoMiglioreSolPrecedente = costoSoluzioni[migliorSoluzione];
                runSolMigliore = nGenerazioni;
            }
            else if(costoSoluzioni[migliorSoluzione] > costoMiglioreSolPrecedente) // NON HO MIGLIORATO, NO STAGNATION
            {
                printf("Costo migliore ora %u, Costo migliore precedente %u (non ho migliorato)\n",costoSoluzioni[migliorSoluzione],costoMiglioreSolPrecedente);
                nTentativiMiglioramento = ACOVARS.tentativiMiglioramento;
            }
            else if(costoSoluzioni[migliorSoluzione] == costoMiglioreSolPrecedente && nTentativiMiglioramento == 0) // NON HO MIGLIORATO E HO ESAURITO I TENTATIVI
            {
                printf("Rischio di stagnation! ");
                if(minimiLocali.empty())
                    minimiLocali.push_back(costoSoluzioni[migliorSoluzione]);
                else if(minimiLocali.back()!=costoSoluzioni[migliorSoluzione])
                    minimiLocali.push_back(costoSoluzioni[migliorSoluzione]);

                {
                    nTentativiMiglioramento = ACOVARS.tentativiMiglioramento;
                    bool condizione = uint16_t(mediaCosti(costoSoluzioni)) == costoSoluzioni[migliorSoluzione];
                    if(condizione) // TUTTE LE SOLUZIONI SONO UGUALI COME COSTO AL MINIMO
                    {
                        initPopolazioneSoluzioni(popolazioneSoluzioni,richieste,pesoArchi);
                    }

                    else
                    {
                        printf("Reinizializzo gli individui: ");
                        for(uint16_t i=0;i<ACOVARS.nAnt;i++)
                        {
                            if(costoSoluzioni[i]==costoSoluzioni[migliorSoluzione])
                            {
                                printf("%u-",i);
                                resetFeromoneSoluzione(feromoneArchi,popolazioneSoluzioni[i]);
                                initIndividuo(i,popolazioneSoluzioni,richieste,pesoArchi); // LAVORIAMO SU ALTRI INDIVIDUI DELLA POP.
                                // local update come se fosse stato inserito da un'ant
                                for(uint16_t j=1;j<popolazioneSoluzioni[i].size();j++)
                                {
                                    uint16_t origine = popolazioneSoluzioni[i][j-1];
                                    uint16_t destinazione = popolazioneSoluzioni[i][j];
                                    feromoneArchi[origine][destinazione] = (1-ACOVARS.theta) * feromoneArchi[origine][destinazione] + ACOVARS.theta * ACOVARS.feromoneIniziale;
                                }
                            }
                        }
                        printf(" il cui costo e' pari al minimo locale\n");
                    }

                    updateCacheCostiSoluzioni(popolazioneSoluzioni,pesoArchi,costoSoluzioni,migliorSoluzione);
                    globalUpdate(migliorSoluzione, costoSoluzioni, popolazioneSoluzioni, feromoneArchi);
                    costoMiglioreSolPrecedente = costoSoluzioni[migliorSoluzione];
                }
            }
            else if(costoSoluzioni[migliorSoluzione] == costoMiglioreSolPrecedente && nTentativiMiglioramento > 0) // NON HO MIGLIORATO E HO ESAURITO I TENTATIVI// NON HO MIGLIORATO, MA HO ANCORA TENTATIVI
            {
                --nTentativiMiglioramento; // la soluzione non è migliorata
            }
            ++nGenerazioni;

            if(nGenerazioni==ACOVARS.maxGenerazioni)
            {
                printf("Hai esaurito le generazioni! Se vuoi puoi continuare con le iterazioni.\n");
                uint16_t nGenAggiuntive = readIntFromConsole(string("Continua per altre N generazioni [0 per concludere]: "));
                nGenerazioni += nGenAggiuntive;
            }
        }

        double tasktime = difftime( time(nullptr), start);

        // STAMPA INFORMAZIONI A SCHERMO
        {
            printf("Tempo di esecuzione: %f\n",tasktime);
            printf("Soluzione migliore in assoluto (costo %u):\n",solMiglioreAssoluto);
            if(ACOVARS.showTours) printTour(popolazioneSoluzioni[migliorSoluzione]);
            printf(" (run %u)\n",runSolMiglioreAssoluto);
            printf("Minimi locali:");
            printTour(minimiLocali);
            printf("\n");
        }

        // reset per un nuovo test ----------------------------------------------------
        {
            copiaVettore(costoSoluzioniInit,costoSoluzioni);
            for(uint16_t i=0; i<ACOVARS.nAnt; i++)
            {
                copiaVettore(popolazioneSoluzioniInit[i],popolazioneSoluzioni[i]);
            }

            resetFeromoneGrafo(feromoneArchi);
            migliorSoluzione = distance(costoSoluzioni.begin(),min_element(costoSoluzioni.begin(),costoSoluzioni.end()));
            costoMiglioreSolPrecedente = costoSoluzioni[migliorSoluzione];
            globalUpdate(migliorSoluzione, costoSoluzioni, popolazioneSoluzioni, feromoneArchi);
            nGenerazioni = runSolMigliore = 0;
            nTentativiMiglioramento = 20;
            solMiglioreAssoluto = numeric_limits<uint16_t>::max();
            runSolMiglioreAssoluto = 0;
        }

        faiTest = readIntFromConsole(string("[0] ESCI\n[1] CONTINUA \n>> "));
    }
}


text:
int main(int argc, char* argv[]) {
    testing::InitGoogleTest(&argc, argv);
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
    return RUN_ALL_TESTS();
}

namespace {

static const std::string EXP_REQUEST = "hello";
static const std::string EXP_RESPONSE = "world";

static const std::string MOCK_CREDENTIAL = "mock credential";
static const std::string MOCK_USER = "mock user";

class MyAuthenticator : public brpc::Authenticator {
public:
    MyAuthenticator() {}

    int GenerateCredential(std::string* auth_str) const {
        *auth_str = MOCK_CREDENTIAL;
        return 0;
    }

    int VerifyCredential(const std::string& auth_str,
                         const butil::EndPoint&,
                         brpc::AuthContext* ctx) const {
        EXPECT_EQ(MOCK_CREDENTIAL, auth_str);
        ctx->set_user(MOCK_USER);
        return 0;
    }
};

class MyEchoService : public ::test::EchoService {
    void Echo(::google::protobuf::RpcController* cntl_base,
              const ::test::EchoRequest* req,
              ::test::EchoResponse* res,
              ::google::protobuf::Closure* done) {
        brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);
        brpc::ClosureGuard done_guard(done);

        if (req->close_fd()) {
            cntl->CloseConnection("Close connection according to request");
            return;
        }
        EXPECT_EQ(EXP_REQUEST, req->message());
        res->set_message(EXP_RESPONSE);
    }
};

class SofaTest : public ::testing::Test{
protected:
    SofaTest() {
        EXPECT_EQ(0, _server.AddService(
            &_svc, brpc::SERVER_DOESNT_OWN_SERVICE));
        // Hack: Regard `_server' as running
        _server._status = brpc::Server::RUNNING;
        // Sofa doesn't support authentication
        // _server._options.auth = &_auth;

        EXPECT_EQ(0, pipe(_pipe_fds));

        brpc::SocketId id;
        brpc::SocketOptions options;
        options.fd = _pipe_fds[1];
        EXPECT_EQ(0, brpc::Socket::Create(options, &id));
        EXPECT_EQ(0, brpc::Socket::Address(id, &_socket));
    };

    virtual ~SofaTest() {};
    virtual void SetUp() {};
    virtual void TearDown() {};

    void VerifyMessage(brpc::InputMessageBase* msg) {
        if (msg->_socket == NULL) {
            _socket->ReAddress(&msg->_socket);
        }
        msg->_arg = &_server;
        EXPECT_TRUE(brpc::policy::VerifySofaRequest(msg));
    }

    void ProcessMessage(void (*process)(brpc::InputMessageBase*),
                        brpc::InputMessageBase* msg, bool set_eof) {
        if (msg->_socket == NULL) {
            _socket->ReAddress(&msg->_socket);
        }
        msg->_arg = &_server;
        _socket->PostponeEOF();
        if (set_eof) {
            _socket->SetEOF();
        }
        (*process)(msg);
    }

    brpc::policy::MostCommonMessage* MakeRequestMessage(
        const brpc::policy::SofaRpcMeta& meta) {
        brpc::policy::MostCommonMessage* msg =
                brpc::policy::MostCommonMessage::Get();
        butil::IOBufAsZeroCopyOutputStream meta_stream(&msg->meta);
        EXPECT_TRUE(meta.SerializeToZeroCopyStream(&meta_stream));

        test::EchoRequest req;
        req.set_message(EXP_REQUEST);
        butil::IOBufAsZeroCopyOutputStream req_stream(&msg->payload);
        EXPECT_TRUE(req.SerializeToZeroCopyStream(&req_stream));
        return msg;
    }

    brpc::policy::MostCommonMessage* MakeResponseMessage(
        const brpc::policy::SofaRpcMeta& meta) {
        brpc::policy::MostCommonMessage* msg =
                brpc::policy::MostCommonMessage::Get();
        butil::IOBufAsZeroCopyOutputStream meta_stream(&msg->meta);
        EXPECT_TRUE(meta.SerializeToZeroCopyStream(&meta_stream));

        test::EchoResponse res;
        res.set_message(EXP_RESPONSE);
        butil::IOBufAsZeroCopyOutputStream res_stream(&msg->payload);
        EXPECT_TRUE(res.SerializeToZeroCopyStream(&res_stream));
        return msg;
    }

    void CheckResponseCode(bool expect_empty, int expect_code) {
        int bytes_in_pipe = 0;
        ioctl(_pipe_fds[0], FIONREAD, &bytes_in_pipe);
        if (expect_empty) {
            EXPECT_EQ(0, bytes_in_pipe);
            return;
        }

        EXPECT_GT(bytes_in_pipe, 0);
        butil::IOPortal buf;
        EXPECT_EQ((ssize_t)bytes_in_pipe,
                  buf.append_from_file_descriptor(_pipe_fds[0], 1024));
        brpc::ParseResult pr = brpc::policy::ParseSofaMessage(&buf, NULL, false, NULL);
        EXPECT_EQ(brpc::PARSE_OK, pr.error());
        brpc::policy::MostCommonMessage* msg =
            static_cast<brpc::policy::MostCommonMessage*>(pr.message());

        brpc::policy::SofaRpcMeta meta;
        butil::IOBufAsZeroCopyInputStream meta_stream(msg->meta);
        EXPECT_TRUE(meta.ParseFromZeroCopyStream(&meta_stream));
        EXPECT_EQ(expect_code, meta.error_code());
    }

    void TestSofaCompress(brpc::CompressType type) {
        butil::IOBuf request_buf;
        butil::IOBuf total_buf;
        brpc::Controller cntl;
        test::EchoRequest req;
        test::EchoResponse res;
        cntl._response = &res;

        req.set_message(EXP_REQUEST);
        cntl.set_request_compress_type(type);
        brpc::SerializeRequestDefault(&request_buf, &cntl, &req);
        ASSERT_FALSE(cntl.Failed());
        brpc::policy::PackSofaRequest(
            &total_buf, NULL, cntl.call_id().value,
            test::EchoService::descriptor()->method(0),
            &cntl, request_buf, &_auth);
        ASSERT_FALSE(cntl.Failed());

        brpc::ParseResult req_pr =
                brpc::policy::ParseSofaMessage(&total_buf, NULL, false, NULL);
        ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
        brpc::InputMessageBase* req_msg = req_pr.message();
        ProcessMessage(brpc::policy::ProcessSofaRequest, req_msg, false);
        CheckResponseCode(false, 0);
    }

    int _pipe_fds[2];
    brpc::SocketUniquePtr _socket;
    brpc::Server _server;

    MyEchoService _svc;
    MyAuthenticator _auth;
};

TEST_F(SofaTest, process_request_failed_socket) {
    brpc::policy::SofaRpcMeta meta;
    meta.set_type(brpc::policy::SofaRpcMeta::REQUEST);
    meta.set_sequence_id(0);
    meta.set_method("EchoService.Echo");
    brpc::policy::MostCommonMessage* msg = MakeRequestMessage(meta);
    _socket->SetFailed();
    ProcessMessage(brpc::policy::ProcessSofaRequest, msg, false);
    ASSERT_EQ(0ll, _server._nerror_bvar.get_value());
    CheckResponseCode(true, 0);
}

TEST_F(SofaTest, process_request_logoff) {
    brpc::policy::SofaRpcMeta meta;
    meta.set_type(brpc::policy::SofaRpcMeta::REQUEST);
    meta.set_sequence_id(0);
    meta.set_method("EchoService.Echo");
    brpc::policy::MostCommonMessage* msg = MakeRequestMessage(meta);
    _server._status = brpc::Server::READY;
    ProcessMessage(brpc::policy::ProcessSofaRequest, msg, false);
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
    CheckResponseCode(false, brpc::ELOGOFF);
}

TEST_F(SofaTest, process_request_wrong_method) {
    brpc::policy::SofaRpcMeta meta;
    meta.set_type(brpc::policy::SofaRpcMeta::REQUEST);
    meta.set_sequence_id(0);
    meta.set_method("EchoService.NO_SUCH_METHOD");
    brpc::policy::MostCommonMessage* msg = MakeRequestMessage(meta);
    ProcessMessage(brpc::policy::ProcessSofaRequest, msg, false);
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
    CheckResponseCode(false, brpc::ENOMETHOD);
}

TEST_F(SofaTest, process_response_after_eof) {
    brpc::policy::SofaRpcMeta meta;
    test::EchoResponse res;
    brpc::Controller cntl;
    meta.set_type(brpc::policy::SofaRpcMeta::RESPONSE);
    meta.set_sequence_id(cntl.call_id().value);
    cntl._response = &res;
    brpc::policy::MostCommonMessage* msg = MakeResponseMessage(meta);
    ProcessMessage(brpc::policy::ProcessSofaResponse, msg, true);
    ASSERT_EQ(EXP_RESPONSE, res.message());
    ASSERT_TRUE(_socket->Failed());
}

TEST_F(SofaTest, process_response_error_code) {
    const int ERROR_CODE = 12345;
    brpc::policy::SofaRpcMeta meta;
    brpc::Controller cntl;
    meta.set_type(brpc::policy::SofaRpcMeta::RESPONSE);
    meta.set_sequence_id(cntl.call_id().value);
    meta.set_error_code(ERROR_CODE);
    brpc::policy::MostCommonMessage* msg = MakeResponseMessage(meta);
    ProcessMessage(brpc::policy::ProcessSofaResponse, msg, false);
    ASSERT_EQ(ERROR_CODE, cntl.ErrorCode());
}

TEST_F(SofaTest, complete_flow) {
    butil::IOBuf request_buf;
    butil::IOBuf total_buf;
    brpc::Controller cntl;
    test::EchoRequest req;
    test::EchoResponse res;
    cntl._response = &res;

    // Send request
    req.set_message(EXP_REQUEST);
    brpc::SerializeRequestDefault(&request_buf, &cntl, &req);
    ASSERT_FALSE(cntl.Failed());
    brpc::policy::PackSofaRequest(
        &total_buf, NULL, cntl.call_id().value,
        test::EchoService::descriptor()->method(0), &cntl, request_buf, &_auth);
    ASSERT_FALSE(cntl.Failed());

    // Verify and handle request
    brpc::ParseResult req_pr =
            brpc::policy::ParseSofaMessage(&total_buf, NULL, false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
    brpc::InputMessageBase* req_msg = req_pr.message();
    VerifyMessage(req_msg);
    ProcessMessage(brpc::policy::ProcessSofaRequest, req_msg, false);

    // Read response from pipe
    butil::IOPortal response_buf;
    response_buf.append_from_file_descriptor(_pipe_fds[0], 1024);
    brpc::ParseResult res_pr =
            brpc::policy::ParseSofaMessage(&response_buf, NULL, false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, res_pr.error());
    brpc::InputMessageBase* res_msg = res_pr.message();
    ProcessMessage(brpc::policy::ProcessSofaResponse, res_msg, false);

    ASSERT_FALSE(cntl.Failed());
    ASSERT_EQ(EXP_RESPONSE, res.message());
}

TEST_F(SofaTest, close_in_callback) {
    butil::IOBuf request_buf;
    butil::IOBuf total_buf;
    brpc::Controller cntl;
    test::EchoRequest req;

    // Send request
    req.set_message(EXP_REQUEST);
    req.set_close_fd(true);
    brpc::SerializeRequestDefault(&request_buf, &cntl, &req);
    ASSERT_FALSE(cntl.Failed());
    brpc::policy::PackSofaRequest(
        &total_buf, NULL, cntl.call_id().value,
        test::EchoService::descriptor()->method(0), &cntl, request_buf, &_auth);
    ASSERT_FALSE(cntl.Failed());

    // Handle request
    brpc::ParseResult req_pr =
            brpc::policy::ParseSofaMessage(&total_buf, NULL, false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
    brpc::InputMessageBase* req_msg = req_pr.message();
    ProcessMessage(brpc::policy::ProcessSofaRequest, req_msg, false);

    // Socket should be closed
    ASSERT_TRUE(_socket->Failed());
}

TEST_F(SofaTest, sofa_compress) {
    TestSofaCompress(brpc::COMPRESS_TYPE_SNAPPY);
    TestSofaCompress(brpc::COMPRESS_TYPE_GZIP);
    TestSofaCompress(brpc::COMPRESS_TYPE_ZLIB);
}
} //namespace


text:
<?xml version="1.0" encoding="utf-8" ?>

<storyPoints>
	<storyPoint name = "toolkitsession">
		<SaliencyMapInit>

		</SaliencyMapInit>
		<keywordToObjectMap>
			<keyword name = "I">

				</keyword>
		</keywordToObjectMap>
		<emotionInit name = "normal"/>
	</storyPoint>
</storyPoints>


text:
package org.apache.hadoop.yarn.server.resourcemanager.reservation;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anySetOf;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ReservationDefinition;
import org.apache.hadoop.yarn.api.records.ReservationId;
import org.apache.hadoop.yarn.api.records.ReservationRequest;
import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter;
import org.apache.hadoop.yarn.api.records.ReservationRequests;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.impl.pb.ReservationDefinitionPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ReservationRequestsPBImpl;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.MockNodes;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.AlignedPlannerWithGreedy;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager;
import org.junit.Assert;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class ReservationSystemTestUtil {

  private static Random rand = new Random();

  public final static String reservationQ = "dedicated";

  public static ReservationId getNewReservationId() {
    return ReservationId.newInstance(rand.nextLong(), rand.nextLong());
  }

  public static ReservationSchedulerConfiguration createConf(
      String reservationQ, long timeWindow, float instConstraint,
      float avgConstraint) {
    ReservationSchedulerConfiguration conf = mock
        (ReservationSchedulerConfiguration.class);
    when(conf.getReservationWindow(reservationQ)).thenReturn(timeWindow);
    when(conf.getInstantaneousMaxCapacity(reservationQ)).thenReturn
        (instConstraint);
    when(conf.getAverageCapacity(reservationQ)).thenReturn(avgConstraint);
    return conf;
  }

  public static void validateReservationQueue(
      AbstractReservationSystem reservationSystem, String planQName) {
    Plan plan = reservationSystem.getPlan(planQName);
    Assert.assertNotNull(plan);
    Assert.assertTrue(plan instanceof InMemoryPlan);
    Assert.assertEquals(planQName, plan.getQueueName());
    Assert.assertEquals(8192, plan.getTotalCapacity().getMemory());
    Assert.assertTrue(
        plan.getReservationAgent() instanceof AlignedPlannerWithGreedy);
    Assert.assertTrue(
        plan.getSharingPolicy() instanceof CapacityOverTimePolicy);
  }

  public static void validateNewReservationQueue(
      AbstractReservationSystem reservationSystem, String newQ) {
    Plan newPlan = reservationSystem.getPlan(newQ);
    Assert.assertNotNull(newPlan);
    Assert.assertTrue(newPlan instanceof InMemoryPlan);
    Assert.assertEquals(newQ, newPlan.getQueueName());
    Assert.assertEquals(1024, newPlan.getTotalCapacity().getMemory());
    Assert
        .assertTrue(newPlan.getReservationAgent() instanceof AlignedPlannerWithGreedy);
    Assert
        .assertTrue(newPlan.getSharingPolicy() instanceof CapacityOverTimePolicy);
  }

  public static void setupFSAllocationFile(String allocationFile)
      throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter(allocationFile));
    out.println("<?xml version=\"1.0\"?>");
    out.println("<allocations>");
    out.println("<queue name=\"default\">");
    out.println("<weight>1</weight>");
    out.println("</queue>");
    out.println("<queue name=\"a\">");
    out.println("<weight>1</weight>");
    out.println("<queue name=\"a1\">");
    out.println("<weight>3</weight>");
    out.println("</queue>");
    out.println("<queue name=\"a2\">");
    out.println("<weight>7</weight>");
    out.println("</queue>");
    out.println("</queue>");
    out.println("<queue name=\"dedicated\">");
    out.println("<reservation></reservation>");
    out.println("<weight>8</weight>");
    out.println("</queue>");
    out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>");
    out.println("</allocations>");
    out.close();
  }

  public static void updateFSAllocationFile(String allocationFile)
      throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter(allocationFile));
    out.println("<?xml version=\"1.0\"?>");
    out.println("<allocations>");
    out.println("<queue name=\"default\">");
    out.println("<weight>5</weight>");
    out.println("</queue>");
    out.println("<queue name=\"a\">");
    out.println("<weight>5</weight>");
    out.println("<queue name=\"a1\">");
    out.println("<weight>3</weight>");
    out.println("</queue>");
    out.println("<queue name=\"a2\">");
    out.println("<weight>7</weight>");
    out.println("</queue>");
    out.println("</queue>");
    out.println("<queue name=\"dedicated\">");
    out.println("<reservation></reservation>");
    out.println("<weight>80</weight>");
    out.println("</queue>");
    out.println("<queue name=\"reservation\">");
    out.println("<reservation></reservation>");
    out.println("<weight>10</weight>");
    out.println("</queue>");
    out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>");
    out.println("</allocations>");
    out.close();
  }

  public static FairScheduler setupFairScheduler(
      ReservationSystemTestUtil testUtil,
      RMContext rmContext, Configuration conf, int numContainers) throws
      IOException {
    FairScheduler scheduler = new FairScheduler();
    scheduler.setRMContext(rmContext);

    when(rmContext.getScheduler()).thenReturn(scheduler);

    scheduler.init(conf);
    scheduler.start();
    scheduler.reinitialize(conf, rmContext);

    Resource resource = testUtil.calculateClusterResource(numContainers);
    RMNode node1 = MockNodes.newNodeInfo(1, resource, 1, "127.0.0.1");
    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
    scheduler.handle(nodeEvent1);
    return scheduler;
  }

  @SuppressWarnings("unchecked")
  public CapacityScheduler mockCapacityScheduler(int numContainers)
      throws IOException {
    // stolen from TestCapacityScheduler
    CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration();
    setupQueueConfiguration(conf);

    CapacityScheduler cs = Mockito.spy(new CapacityScheduler());
    cs.setConf(new YarnConfiguration());

    RMContext mockRmContext = createRMContext(conf);

    cs.setRMContext(mockRmContext);
    try {
      cs.serviceInit(conf);
    } catch (Exception e) {
      Assert.fail(e.getMessage());
    }

    initializeRMContext(numContainers, cs, mockRmContext);
    return cs;
  }

  public static void initializeRMContext(int numContainers,
      AbstractYarnScheduler scheduler, RMContext mockRMContext) {

    when(mockRMContext.getScheduler()).thenReturn(scheduler);
    Resource r = calculateClusterResource(numContainers);
    doReturn(r).when(scheduler).getClusterResource();
  }

  public static RMContext createRMContext(Configuration conf) {
    RMContext mockRmContext =
        Mockito.spy(new RMContextImpl(null, null, null, null, null, null,
            new RMContainerTokenSecretManager(conf),
            new NMTokenSecretManagerInRM(conf),
            new ClientToAMTokenSecretManagerInRM(), null));

    RMNodeLabelsManager nlm = mock(RMNodeLabelsManager.class);
    when(
        nlm.getQueueResource(any(String.class), anySetOf(String.class),
            any(Resource.class))).thenAnswer(new Answer<Resource>() {
      @Override
      public Resource answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        return (Resource) args[2];
      }
    });

    when(nlm.getResourceByLabel(any(String.class), any(Resource.class)))
        .thenAnswer(new Answer<Resource>() {
          @Override
          public Resource answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return (Resource) args[1];
          }
        });

    mockRmContext.setNodeLabelManager(nlm);
    return mockRmContext;
  }

  public static void setupQueueConfiguration(CapacitySchedulerConfiguration conf) {
    // Define default queue
    final String defQ = CapacitySchedulerConfiguration.ROOT + ".default";
    conf.setCapacity(defQ, 10);

    // Define top-level queues
    conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {
        "default", "a", reservationQ });

    final String A = CapacitySchedulerConfiguration.ROOT + ".a";
    conf.setCapacity(A, 10);

    final String dedicated =
        CapacitySchedulerConfiguration.ROOT
            + CapacitySchedulerConfiguration.DOT + reservationQ;
    conf.setCapacity(dedicated, 80);
    // Set as reservation queue
    conf.setReservable(dedicated, true);

    // Define 2nd-level queues
    final String A1 = A + ".a1";
    final String A2 = A + ".a2";
    conf.setQueues(A, new String[] { "a1", "a2" });
    conf.setCapacity(A1, 30);
    conf.setCapacity(A2, 70);
  }

  public String getFullReservationQueueName() {
    return CapacitySchedulerConfiguration.ROOT
        + CapacitySchedulerConfiguration.DOT + reservationQ;
  }

  public String getreservationQueueName() {
    return reservationQ;
  }

  public void updateQueueConfiguration(CapacitySchedulerConfiguration conf,
      String newQ) {
    // Define default queue
    final String prefix =
        CapacitySchedulerConfiguration.ROOT
            + CapacitySchedulerConfiguration.DOT;
    final String defQ = prefix + "default";
    conf.setCapacity(defQ, 5);

    // Define top-level queues
    conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {
        "default", "a", reservationQ, newQ });

    final String A = prefix + "a";
    conf.setCapacity(A, 5);

    final String dedicated = prefix + reservationQ;
    conf.setCapacity(dedicated, 80);
    // Set as reservation queue
    conf.setReservable(dedicated, true);

    conf.setCapacity(prefix + newQ, 10);
    // Set as reservation queue
    conf.setReservable(prefix + newQ, true);

    // Define 2nd-level queues
    final String A1 = A + ".a1";
    final String A2 = A + ".a2";
    conf.setQueues(A, new String[]{"a1", "a2"});
    conf.setCapacity(A1, 30);
    conf.setCapacity(A2, 70);
  }

  public static ReservationDefinition generateRandomRR(Random rand, long i) {
    rand.setSeed(i);
    long now = System.currentTimeMillis();

    // start time at random in the next 12 hours
    long arrival = rand.nextInt(12 * 3600 * 1000);
    // deadline at random in the next day
    long deadline = arrival + rand.nextInt(24 * 3600 * 1000);

    // create a request with a single atomic ask
    ReservationDefinition rr = new ReservationDefinitionPBImpl();
    rr.setArrival(now + arrival);
    rr.setDeadline(now + deadline);

    int gang = 1 + rand.nextInt(9);
    int par = (rand.nextInt(1000) + 1) * gang;
    long dur = rand.nextInt(2 * 3600 * 1000); // random duration within 2h
    ReservationRequest r =
        ReservationRequest.newInstance(Resource.newInstance(1024, 1), par,
            gang, dur);
    ReservationRequests reqs = new ReservationRequestsPBImpl();
    reqs.setReservationResources(Collections.singletonList(r));
    rand.nextInt(3);
    ReservationRequestInterpreter[] type =
        ReservationRequestInterpreter.values();
    reqs.setInterpreter(type[rand.nextInt(type.length)]);
    rr.setReservationRequests(reqs);

    return rr;

  }

  public static ReservationDefinition generateBigRR(Random rand, long i) {
    rand.setSeed(i);
    long now = System.currentTimeMillis();

    // start time at random in the next 2 hours
    long arrival = rand.nextInt(2 * 3600 * 1000);
    // deadline at random in the next day
    long deadline = rand.nextInt(24 * 3600 * 1000);

    // create a request with a single atomic ask
    ReservationDefinition rr = new ReservationDefinitionPBImpl();
    rr.setArrival(now + arrival);
    rr.setDeadline(now + deadline);

    int gang = 1;
    int par = 100000; // 100k tasks
    long dur = rand.nextInt(60 * 1000); // 1min tasks
    ReservationRequest r =
        ReservationRequest.newInstance(Resource.newInstance(1024, 1), par,
            gang, dur);
    ReservationRequests reqs = new ReservationRequestsPBImpl();
    reqs.setReservationResources(Collections.singletonList(r));
    rand.nextInt(3);
    ReservationRequestInterpreter[] type =
        ReservationRequestInterpreter.values();
    reqs.setInterpreter(type[rand.nextInt(type.length)]);
    rr.setReservationRequests(reqs);

    return rr;
  }

  public static Map<ReservationInterval, Resource> generateAllocation(
      long startTime, long step, int[] alloc) {
    Map<ReservationInterval, Resource> req =
        new TreeMap<ReservationInterval, Resource>();
    for (int i = 0; i < alloc.length; i++) {
      req.put(new ReservationInterval(startTime + i * step, startTime + (i + 1)
          * step), ReservationSystemUtil.toResource(ReservationRequest
          .newInstance(
          Resource.newInstance(1024, 1), alloc[i])));
    }
    return req;
  }

  public static Resource calculateClusterResource(int numContainers) {
    Resource clusterResource = Resource.newInstance(numContainers * 1024,
        numContainers);
    return clusterResource;
  }
}


text:
package it0009.test;

import it0009.HelloWorldSharedLibJNI;
import org.junit.Assert;
import org.junit.Test;

public class HelloWorldSharedLibJNITest
{
    @Test public final void testNativeHelloWorldSharedLibJNI()
        throws Exception
    {
        HelloWorldSharedLibJNI app = new HelloWorldSharedLibJNI();

        Assert.assertEquals( "Hello NAR LIB World!", app.sayHello() );
    }
}


text:
using System;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class InspectStringOmitOverlap
{
    public static InspectContentResponse Inspect(string projectId, string textToInspect)
    {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the "close" method on the client to safely clean up any remaining background resources.
        var dlp = DlpServiceClient.Create();

        // Specify the type and content to be inspected.
        var byteItem = new ByteContentItem
        {
            Type = ByteContentItem.Types.BytesType.TextUtf8,
            Data = Google.Protobuf.ByteString.CopyFromUtf8(textToInspect)
        };
        var contentItem = new ContentItem { ByteItem = byteItem };

        // Specify the type of info the inspection will look for.
        // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types.
        var infoTypes = new string[] { "PERSON_NAME", "EMAIL_ADDRESS" }.Select(it => new InfoType { Name = it });

        // Exclude EMAIL_ADDRESS matches
        var exclusionRule = new ExclusionRule
        {
            ExcludeInfoTypes = new ExcludeInfoTypes { InfoTypes = { new InfoType { Name = "EMAIL_ADDRESS" } } },
            MatchingType = MatchingType.PartialMatch
        };

        // Construct a ruleset that applies the exclusion rule to the PERSON_NAME infotype.
        // If a PERSON_NAME match overlaps with an EMAIL_ADDRESS match, the PERSON_NAME match will
        // be excluded.
        var ruleSet = new InspectionRuleSet
        {
            InfoTypes = { new InfoType { Name = "PERSON_NAME" } },
            Rules = { new InspectionRule { ExclusionRule = exclusionRule } }
        };

        // Construct the configuration for the Inspect request, including the ruleset.
        var config = new InspectConfig
        {
            InfoTypes = { infoTypes },
            IncludeQuote = true,
            RuleSet = { ruleSet }
        };

        // Construct the Inspect request to be sent by the client.
        var request = new InspectContentRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            Item = contentItem,
            InspectConfig = config
        };

        // Use the client to send the API request.
        var response = dlp.InspectContent(request);

        // Parse the response and process results
        Console.WriteLine($"Findings: {response.Result.Findings.Count}");
        foreach (var f in response.Result.Findings)
        {
            Console.WriteLine("\tQuote: " + f.Quote);
            Console.WriteLine("\tInfo type: " + f.InfoType.Name);
            Console.WriteLine("\tLikelihood: " + f.Likelihood);
        }

        return response;
    }
}

// [END dlp_inspect_string_omit_overlap]


text:
package com.microsoft.bingads.v12.api.test.entities.label_association.write;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.v12.api.test.entities.label_association.BulkLabelAssociationTest;
import com.microsoft.bingads.v12.bulk.entities.BulkCampaignLabel;

@RunWith(Parameterized.class)
public class BulkLabelAssociationWriteToRowValueIdTest extends BulkLabelAssociationTest {

    @Parameter(value = 1)
    public Long expectedResult;

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {"123", 123L},
                {"9223372036854775807", 9223372036854775807L},
        });
    }

    @Test
    public void testRead() {
        this.<Long>testWriteProperty("Id", this.datum, this.expectedResult, new BiConsumer<BulkCampaignLabel, Long>() {
            @Override
            public void accept(BulkCampaignLabel c, Long v) {
                c.getLabelAssociation().setLabelId(v);
            }
        });
    }
}


text:
set -e

oldrev="origin/main"
newrev="HEAD"

# Disallow merge commits
for rev in $(git rev-list --merges $oldrev..$newrev); do
	echo "Merge commit $rev found"
	echo "Please fix your branch/PR to not include merges"
	exit 1
done

# Disallow submodules
for rev in $(git rev-list $oldrev..$newrev); do
	comparison=$(git rev-parse --quiet --verify $rev^ || true)

	# Submodules are indicated by files with mode 160000
	submodules=$(git diff-tree -r $comparison $rev | awk '$2 ~ /160000/ {print substr($0, index($0,$6))}' || true)
	if [[ $submodules ]] ; then
		echo "Git submodules are not allowed."
		echo "Commit $rev introduces a submodule at path: $submodules"
		exit 1
	fi
done

# Disallow checking in multiple files with the same name on case-insensitive
# filesystems on OSes like macOS or Windows. These files work fine in linux,
# but break git checkouts on case-insensitive filesystems.
export LC_ALL=C
for rev in $(git rev-list $oldrev..$newrev); do
	test -z "$(git diff-tree $rev -r --root --no-commit-id --name-only \
		--diff-filter=ACR)" && continue

	names=$(git ls-tree -r --name-only $rev | \
		awk '{fn=tolower($0); files[fn]++; if (files[fn] > 1) {print fn}}')

	if [[ -n $names ]]; then
		echo "Commit $rev would introduce files with the same name on"
		echo "case-insensitive filesystems (common on macOS and Windows)."
		echo "Bad filenames: $names"
		exit 1
	fi
done

# Disallow checking in insane filenames that are not broadly
# compatible across source control systems and plaforms.
#
# For example, no carriage returns or line feeds should be allowed in filenames.
export LC_ALL=C
for rev in $(git rev-list $oldrev..$newrev); do
	names=$(git diff-tree $rev -r --root --no-commit-id --name-only \
		--diff-filter=AR)

	# Block commits with filenames outside normal ASCII
	badnames=$(grep '\\\|[`{}|~:]' <<< "$names") || true
	#                ^^ find anything with a backslash in the name
	#                  ^^ or...
	#                    ^^^^^^^ any of these funky chars

if [[ -n $badnames ]]; then
	echo "Bad filenames in commits are blocked to protect the codebase"
	echo "from side-effects on different platforms."
	echo "Bad filenames: $badnames"
	exit 1
fi
done

# If there are whitespace errors, print the offending file names and fail.
for rev in $(git rev-list $oldrev..$newrev); do
	comparison=$(git rev-parse --quiet --verify $rev^ || true)

	whitespace=$(git diff --check $comparison $rev || true)
	if [[ $whitespace ]] ; then
		echo "Found whitespace errors in commit $rev:"
		echo
		git diff --check $comparison $rev
		exit 1
	fi
done