text:
'use strict';

const assert = require('chai').assert;
const sinon = require('sinon');
const hapi = require('hapi');
const mockery = require('mockery');
const urlLib = require('url');
const hoek = require('hoek');
const testPipeline = require('./data/pipeline.json');
const testSecret = require('./data/secret.json');

sinon.assert.expose(assert, { prefix: '' });

const getPipelineMock = (pipeline) => {
    const mock = hoek.clone(pipeline);

    mock.sync = sinon.stub();
    mock.update = sinon.stub();
    mock.toJson = sinon.stub().returns(pipeline);
    mock.jobs = sinon.stub();

    return mock;
};

const getUserMock = (user) => {
    const mock = hoek.clone(user);

    mock.getPermissions = sinon.stub();

    return mock;
};

const getSecretMock = (secret) => {
    const mock = hoek.clone(secret);

    mock.toJson = sinon.stub().returns(secret);
    mock.remove = sinon.stub();
    mock.update = sinon.stub();

    return mock;
};

describe('secret plugin test', () => {
    let secretFactoryMock;
    let userFactoryMock;
    let pipelineFactoryMock;
    let plugin;
    let server;
    const password = 'this_is_a_password_that_needs_to_be_atleast_32_characters';

    before(() => {
        mockery.enable({
            useCleanCache: true,
            warnOnUnregistered: false
        });
    });

    beforeEach((done) => {
        secretFactoryMock = {
            create: sinon.stub(),
            get: sinon.stub(),
            remove: sinon.stub()
        };
        pipelineFactoryMock = {
            get: sinon.stub()
        };
        userFactoryMock = {
            get: sinon.stub()
        };

        /* eslint-disable global-require */
        plugin = require('../../plugins/secrets');
        /* eslint-enable global-require */
        server = new hapi.Server();
        server.app = {
            secretFactory: secretFactoryMock,
            userFactory: userFactoryMock,
            pipelineFactory: pipelineFactoryMock
        };
        server.connection({
            port: 1234
        });

        server.auth.scheme('custom', () => ({
            authenticate: (request, reply) => reply.continue({
                credentials: {
                    scope: ['user']
                }
            })
        }));
        server.auth.strategy('token', 'custom');

        server.register([{
            register: plugin,
            options: {
                password
            }
        }], done);
    });

    afterEach(() => {
        server = null;
        mockery.deregisterAll();
        mockery.resetCache();
    });

    after(() => {
        mockery.disable();
    });

    it('registers the plugin', () => {
        assert.equal(server.registrations.secrets.options.password, password);
        assert.isOk(server.registrations.secrets);
    });

    describe('POST /secrets', () => {
        let options;
        const scmUri = 'github.com:12345:branchName';
        const secretId = 1234;
        const pipelineId = 123;
        const name = 'NPM_TOKEN';
        const value = 'batman';
        const allowInPR = true;
        const username = 'd2lam';
        const scmContext = 'github:github.com';
        let secretMock;
        let userMock;
        let pipelineMock;

        beforeEach(() => {
            options = {
                method: 'POST',
                url: '/secrets',
                payload: {
                    pipelineId,
                    name,
                    value,
                    allowInPR
                },
                credentials: {
                    username,
                    scmContext,
                    scope: ['user']
                }
            };

            userMock = getUserMock({ username });
            userMock.getPermissions.withArgs(scmUri).resolves({ admin: true });
            userFactoryMock.get.withArgs({ username, scmContext }).resolves(userMock);

            pipelineMock = getPipelineMock(testPipeline);
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(pipelineMock);

            secretMock = getSecretMock(testSecret);
            secretFactoryMock.create.resolves(secretMock);
        });

        it('returns 201 and correct secret data', () => {
            let expectedLocation;

            return server.inject(options).then((reply) => {
                expectedLocation = {
                    host: reply.request.headers.host,
                    port: reply.request.headers.port,
                    protocol: reply.request.server.info.protocol,
                    pathname: `${options.url}/${secretId}`
                };
                const expected = {
                    id: 1234,
                    pipelineId: 123,
                    name: 'NPM_TOKEN',
                    allowInPR: false
                };

                assert.equal(reply.statusCode, 201);
                assert.deepEqual(reply.result, expected);
                assert.strictEqual(reply.headers.location, urlLib.format(expectedLocation));
                assert.calledWith(secretFactoryMock.create, options.payload);
            });
        });

        it('returns 409 when the secret already exists', () => {
            secretFactoryMock.get.resolves(secretMock);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 409);
                assert.strictEqual(reply.result.message,
                    `Secret already exists with the ID: ${secretMock.id}`);
            });
        });

        it('returns 404 when the user does not exist', () => {
            userFactoryMock.get.withArgs({ username, scmContext }).resolves(null);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 404);
            });
        });

        it('returns 404 when the pipeline does not exist', () => {
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(null);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 404);
            });
        });

        it('returns 403 when the user does not have admin permissions', () => {
            userMock.getPermissions.withArgs(scmUri).resolves({ admin: false });

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 403);
            });
        });

        it('returns 500 when the secret model fails to create', () => {
            const testError = new Error('secretModelCreateError');

            secretFactoryMock.create.rejects(testError);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 500);
            });
        });
    });

    describe('DELETE /secrets/{id}', () => {
        let options;
        const pipelineId = 123;
        const secretId = 1234;
        const scmUri = 'github.com:12345:branchName';
        const username = 'myself';
        const scmContext = 'github:github.com';
        let secretMock;
        let userMock;
        let pipelineMock;

        beforeEach(() => {
            options = {
                method: 'DELETE',
                url: `/secrets/${secretId}`,
                credentials: {
                    username,
                    scmContext,
                    scope: ['user']
                }
            };

            userMock = getUserMock({ username });
            userMock.getPermissions.withArgs(scmUri).resolves({ admin: true });
            userFactoryMock.get.withArgs({ username, scmContext }).resolves(userMock);

            pipelineMock = getPipelineMock(testPipeline);
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(pipelineMock);

            secretMock = getSecretMock(testSecret);
            secretFactoryMock.get.resolves(secretMock);
            secretMock.remove.resolves(null);
        });

        it('returns 404 when the pipeline does not exist', () => {
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(null);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 404);
            });
        });

        it('returns 404 when the secret does not exist', () => {
            secretFactoryMock.get.resolves(null);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 404);
            });
        });

        it('returns 204 if remove successfully', () =>
            server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 204);
                assert.calledOnce(secretMock.remove);
            })
        );

        it('returns 403 when the user does not have admin permissions', () => {
            userMock.getPermissions.withArgs(scmUri).resolves({ admin: false });

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 403);
            });
        });

        it('returns 500 when the secret model fails to remove', () => {
            const testError = new Error('secretModelRemoveError');

            secretMock.remove.rejects(testError);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 500);
            });
        });
    });

    describe('PUT /secrets/{id}', () => {
        let options;
        const pipelineId = 123;
        const secretId = 1234;
        const scmUri = 'github.com:12345:branchName';
        const username = 'myself';
        const scmContext = 'github:github.com';
        let secretMock;
        let userMock;
        let pipelineMock;

        beforeEach(() => {
            options = {
                method: 'PUT',
                url: `/secrets/${secretId}`,
                credentials: {
                    username,
                    scmContext,
                    scope: ['user']
                },
                payload: {
                    value: 'newValue',
                    allowInPR: true
                }
            };

            userMock = getUserMock({ username });
            userMock.getPermissions.withArgs(scmUri).resolves({ admin: true });
            userFactoryMock.get.withArgs({ username, scmContext }).resolves(userMock);

            pipelineMock = getPipelineMock(testPipeline);
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(pipelineMock);

            secretMock = getSecretMock(testSecret);
            secretFactoryMock.get.resolves(secretMock);
            secretMock.update.resolves(secretMock);
        });

        it('returns 404 when the pipeline does not exist', () => {
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(null);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 404);
            });
        });

        it('returns 404 when the secret does not exist', () => {
            secretFactoryMock.get.resolves(null);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 404);
            });
        });

        it('returns 200 if update successfully', () => {
            const expected = {
                id: 1234,
                pipelineId: 123,
                name: 'NPM_TOKEN',
                allowInPR: true
            };

            secretMock.toJson.returns(hoek.applyToDefaults(expected, { value: 'encrypted' }));

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 200);
                assert.calledOnce(secretMock.update);
                assert.deepEqual(reply.result, expected);
            });
        });

        it('returns 403 when the user does not have admin permissions', () => {
            userMock.getPermissions.withArgs(scmUri).resolves({ admin: false });

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 403);
            });
        });

        it('returns 500 when the secret model fails to update', () => {
            const testError = new Error('secretModelUpdateError');

            secretMock.update.rejects(testError);

            return server.inject(options).then((reply) => {
                assert.equal(reply.statusCode, 500);
            });
        });
    });

    describe('GET /secrets/{id}', () => {
        let options;
        const pipelineId = 123;
        const secretId = 1234;
        const scmUri = 'github.com:12345:branchName';
        const username = 'minz';
        const scmContext = 'github:github.com';
        let secretMock;
        let userMock;
        let pipelineMock;

        beforeEach(() => {
            userMock = getUserMock({ username });
            userMock.getPermissions.withArgs(scmUri).resolves({ push: true });
            userFactoryMock.get.withArgs({ username, scmContext }).resolves(userMock);

            pipelineMock = getPipelineMock(testPipeline);
            pipelineFactoryMock.get.withArgs(pipelineId).resolves(pipelineMock);

            secretMock = getSecretMock(testSecret);
            secretFactoryMock.get.resolves(secretMock);
        });

        describe('User scope', () => {
            beforeEach(() => {
                options = {
                    method: 'GET',
                    url: `/secrets/${secretId}`,
                    credentials: {
                        username,
                        scmContext,
                        scope: ['user']
                    }
                };
            });

            it('returns 404 when the pipeline does not exist', () => {
                pipelineFactoryMock.get.withArgs(pipelineId).resolves(null);

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 404);
                });
            });

            it('returns 404 when the secret does not exist', () => {
                secretFactoryMock.get.resolves(null);

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 404);
                });
            });

            it('returns 404 when the user does not exist', () => {
                userFactoryMock.get.withArgs({ username, scmContext }).resolves(null);

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 404);
                });
            });

            it('returns 403 when the user does not have push permissions', () => {
                userMock.getPermissions.withArgs(scmUri).resolves({ push: false });

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 403);
                });
            });

            it('does not show secret value if scope is user', () => {
                const expected = {
                    id: 1234,
                    pipelineId: 123,
                    name: 'NPM_TOKEN',
                    allowInPR: false
                };

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 200);
                    assert.deepEqual(reply.result, expected);
                    assert.calledWith(secretFactoryMock.get, secretId);
                });
            });
        });

        describe('Build scope', () => {
            beforeEach(() => {
                options = {
                    method: 'GET',
                    url: `/secrets/${secretId}`,
                    credentials: {
                        username,
                        scmContext,
                        pipelineId: 123,
                        scope: ['build']
                    }
                };
            });

            it('shows secret value if scope is build', () =>
                server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 200);
                    assert.deepEqual(reply.result, testSecret);
                    assert.calledWith(secretFactoryMock.get, secretId);
                })
            );

            it('returns 403 if build is not allowed to access secret', () => {
                options.credentials.pipelineId = 124;

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 403);
                });
            });

            it('returns 403 if not allowed in PR and build is running a PR job', () => {
                options.credentials.isPR = true;

                return server.inject(options).then((reply) => {
                    assert.equal(reply.statusCode, 403);
                });
            });
        });
    });
});


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>cocos.actions.move_actions.WrappedMove</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

      Trees

      Indices

          cocos . actions . move_actions . WrappedMove

        Toggle frames

Class cocos.actions.move_actions.WrappedMove

base_actions.Action --+
                      |
                   Move --+
                          |
                         WrappedMove

Move the target but wrap position when it hits certain bounds.

Wrap occurs outside of 0 < x < width and 0 < y < height taking into
account the dimenstions of the target.

Methods

        init(self,
        width,
        height)

Init method.

        step(self,
        dt)

Gets called every frame.

        __add__(self,
        action)

sequence operator - concatenates actions
action1 + action2 -> action_result
where action_result performs as:
first do all that action1 would do; then
perform all that action2 would do

      (Inherited from cocos.actions.base_actions.Action)

        __init__(self,
        *args,
        **kwargs)

dont override - use init

      (Inherited from cocos.actions.base_actions.Action)

        __mul__(self,
        other)

repeats ntimes the action
action * n -> action_result
where action result performs as:
repeat n times the changes that action would do

      (Inherited from cocos.actions.base_actions.Action)

        __or__(self,
        action)

spawn operator -  runs two actions in parallel
action1 | action2 -> action_result

      (Inherited from cocos.actions.base_actions.Action)

        __reversed__(self)
      (Inherited from cocos.actions.base_actions.Action)

        done(self)

False while the step method must be called.

      (Inherited from cocos.actions.base_actions.Action)

        start(self)

External code sets self.target and then calls this method.

      (Inherited from cocos.actions.base_actions.Action)

        stop(self)

When the action must cease to perform this function is called by
external code; after this call no other method should be called.

      (Inherited from cocos.actions.base_actions.Action)

Instance Variables

        target

CocosNode object that is the target of the action

      (Inherited from cocos.actions.base_actions.Action)

Method Details

init

    init(self,
        width,
        height)

  Init method.

Parameters:

width : integer

The width to wrap position at.

height : integer

The height to wrap position at.

Overrides:

      base_actions.Action.init

step

    step(self,
        dt)

  Gets called every frame. dt is the number of seconds that elapsed
since the last call.

Overrides:

      Move.step

      Trees

      Indices

          cocos . actions . move_actions . WrappedMove

        Toggle frames

    Generated by Epydoc 3.0beta1 on Sun Aug 12 20:39:19 2012

      http://epydoc.sourceforge.net

redpajama_set_name: RedPajamaGithub


text:
package com.symbolplay.tria.game.rise.generators;

import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.symbolplay.tria.game.platforms.Platform;

public final class RiseGeneratorToggleSpikes {

    private static final float STEP_Y_2 = 3.5f;
    private static final float STEP_Y_3 = 5.5f;
    private static final float IN_STEP_OFFSET = 0.5f;

    private final AssetManager assetManager;
    private final RiseGeneratorStandard riseGeneratorStandard;

    public RiseGeneratorToggleSpikes(RiseGeneratorStandard riseGeneratorStandard, AssetManager assetManager) {
        this.riseGeneratorStandard = riseGeneratorStandard;
        this.assetManager = assetManager;
    }

    public void generateHigh(RiseGeneratorData rgd) {
        riseGeneratorStandard.generateHighJumpBoostBufferZone(rgd);

        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float height = getGenerationHeight(absoluteHeight);

        float multiWeight = getMultiWeight(absoluteHeight);
        float adjacentWeight = getAdjacentWeight(absoluteHeight);
        float totalWeight = multiWeight + adjacentWeight;
        float randomValue = MathUtils.random(totalWeight);

        if (randomValue < multiWeight) {
            generateMulti(rgd, MathUtils.randomBoolean(), height);
        } else {
            generate2PerStepY(rgd, false, height);
        }
    }

    private void generateMulti(RiseGeneratorData rgd, boolean isThreePositions, float height) {

        Array<Platform> platforms = rgd.platforms;
        float relativeHeight = rgd.relativeHeight;

        int platformsPerStepY = isThreePositions ? 3 : 2;

        float[] positionsX = new float[platformsPerStepY];

        float y = 0.0f;
        float stepY = isThreePositions ? STEP_Y_3 : STEP_Y_2;

        while (y < height) {
            RiseGeneratorUtils.getPositionsX(positionsX, isThreePositions);

            for (int i = 0; i < platformsPerStepY; i++) {
                float minCurrY = Math.max(y - IN_STEP_OFFSET, 0.0f);
                float maxCurrY = y + IN_STEP_OFFSET;
                float currY = MathUtils.random(minCurrY, maxCurrY);
                Platform platform = new Platform(rgd.nextPlatformId, rgd.nextGroupId, positionsX[i], currY + relativeHeight, assetManager);

                setToggleSpikesPlatformFeatureData(platform, i, isThreePositions);

                platforms.add(platform);

                rgd.nextPlatformId++;
            }

            rgd.nextGroupId++;

            y += stepY;
        }

        rgd.changeGeneratedHeight(y);
        rgd.lastToggleSpikesHeight = rgd.absoluteHeight;
    }

    private void generate2PerStepY(RiseGeneratorData rgd, boolean isThreePositions, float height) {

        Array<Platform> platforms = rgd.platforms;
        float relativeHeight = rgd.relativeHeight;
        float absoluteHeight = rgd.getAbsoluteHeightFloat();

        float maxChange = getAdjacentMaxChange(absoluteHeight);

        int platformsPerStepY = isThreePositions ? 3 : 2;

        float[] positionsX = new float[platformsPerStepY];

        float y = 0.0f;
        float stepY = isThreePositions ? STEP_Y_3 : STEP_Y_2;

        boolean isFirstStep = true;
        float leftSideX = 0.0f;

        while (y < height) {

            if (isFirstStep) {
                float rightOffset = isThreePositions ? Platform.WIDTH * 2.0f : Platform.WIDTH;
                leftSideX = RiseGeneratorUtils.getRandomPlatformX(0.0f, rightOffset);
                RiseGeneratorUtils.getRandomAdjacentPositionsX(leftSideX, positionsX, isThreePositions);
                isFirstStep = false;
            } else {
                RiseGeneratorUtils.getRandomNextAdjacentPositionsX(leftSideX, 0.0f, maxChange, positionsX, isThreePositions);
            }

            for (int i = 0; i < platformsPerStepY; i++) {
                float minCurrY = Math.max(y - IN_STEP_OFFSET, 0.0f);
                float maxCurrY = y + IN_STEP_OFFSET;
                float currY = MathUtils.random(minCurrY, maxCurrY);
                Platform platform = new Platform(rgd.nextPlatformId, rgd.nextGroupId, positionsX[i], currY + relativeHeight, assetManager);

                setToggleSpikesPlatformFeatureData(platform, i, isThreePositions);

                platforms.add(platform);
                rgd.nextPlatformId++;
            }

            rgd.nextGroupId++;

            y += stepY;
        }

        rgd.changeGeneratedHeight(y);
        rgd.lastToggleSpikesHeight = rgd.absoluteHeight;
    }

    private static void setToggleSpikesPlatformFeatureData(Platform platform, int indexInStepY, boolean isThreePositions) {
        int platformsPerStepY = isThreePositions ? 3 : 2;

        int[] states = new int[platformsPerStepY];
        for (int i = 0; i < platformsPerStepY; i++) {
            states[i] = i == indexInStepY ? 0 : 1;
        }

        platform.setToggleSpikesFeature(states);
    }

    private static float getGenerationHeight(float absoluteHeight) {
        float min;
        if (absoluteHeight <= 2000.0f) {
            min = 40.0f + absoluteHeight * 0.005f;
        } else {
            min = 50.0f;
        }

        float max;
        if (absoluteHeight <= 2000.0f) {
            max = 50.0f + absoluteHeight * 0.005f;
        } else {
            max = 60.0f;
        }

        return MathUtils.random(min, max);
    }

    private static float getMultiWeight(float absoluteHeight) {
        if (absoluteHeight <= 500.0f) {
            return 1.0f;
        } else if (absoluteHeight <= 2500.0f) {
            return 1.0f - (absoluteHeight - 500.0f) * 0.0005f;
        } else {
            return 0.0f;
        }
    }

    private static float getAdjacentWeight(float absoluteHeight) {
        if (absoluteHeight <= 500.0f) {
            return 0.0f;
        } else if (absoluteHeight <= 2500.0f) {
            return 0.0f + (absoluteHeight - 500.0f) * 0.0005f;
        } else {
            return 1.0f;
        }
    }

    private static float getAdjacentMaxChange(float absoluteHeight) {
        if (absoluteHeight <= 500.0f) {
            return 4.0f;
        } else if (absoluteHeight <= 2100.0f) {
            return 4.0f - (absoluteHeight - 500.0f) * 0.0025f;
        } else {
            return 0.0f;
        }
    }
}


text:
package fr.pizzeria.ihm.menu.option;

import java.util.Arrays;
import java.util.Scanner;

import fr.pizzeria.dao.IPizzaDao;
import fr.pizzeria.exception.CategoriePizzaException;
import fr.pizzeria.exception.DaoException;
import fr.pizzeria.exception.SavePizzaException;
import fr.pizzeria.model.CategoriePizza;
import fr.pizzeria.model.Pizza;

/**
 * Option pour ajouter une nouvelle pizza.
 */
public class AjouterPizzaOptionMenu extends OptionMenu {

	/**
	 * Constante pour le {@link OptionMenu.libelle libéllé} de
	 * l'{@link OptionMenu}.
	 */
	private static final String AJOUTER_PIZZA_LIBELLE = "Ajouter une pizza";
	private Scanner scan;

	/**
	 * Constructeur.
	 *
	 * @param pizzaDao La DAO pour les pizzas.
	 * @param scan Le {@link Scanner} pour la saisie utilisateur.
	 */
	public AjouterPizzaOptionMenu(IPizzaDao pizzaDao, Scanner scan) {
		super(AJOUTER_PIZZA_LIBELLE, pizzaDao);
		this.scan = scan;
	}

	@Override
	public boolean execute() throws DaoException {
		System.out.println("Ajout d'une nouvelle pizza");
		System.out.println("Veuillez saisir le code");
		String code = scan.next();
		System.out.println("Veuillez saisir le nom (sans espace)");
		String name = scan.next();
		System.out.println("Veuillez saisir le prix");
		double price = scan.nextDouble();
		System.out.println("Veuillez saisir la catégorie : " + Arrays.toString(CategoriePizza.values()));
		String categorieString = scan.next();
		try {
			CategoriePizza categorie = CategoriePizza.valueOf(categorieString.toUpperCase());
			pizzaDao.saveNewPizza(new Pizza(code, name, price, categorie));
		} catch (DaoException e) {
			throw new SavePizzaException("Erreur : La pizza avec le code " + code + " existe déjà.", e);
		} catch (IllegalArgumentException e) {
			throw new CategoriePizzaException(
					"Erreur de saisie : La catégorie \"" + categorieString + "\" n'existe pas.", e);
		}
		System.out.println();
		return false;
	}
}


text:
MathJax.Localization.addTranslation("ce","HTML-CSS",{
        version: "2.7.0-beta",
        isLoaded: true,
        strings: {

        }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/ce/HTML-CSS.js");


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.androidhuman.example.notifications.VoiceInputActivity">

    <Button android:id="@+id/btn_activity_voice_input_basic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Basic voice input"/>

    <Button android:id="@+id/btn_activity_voice_input_pre_defined"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="with pre defined responses"/>

</LinearLayout>


text:
<component name="libraryTable">
  <library name="KotlinPlugin">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/allopen-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-extensions-compiler.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-extensions-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-lint.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/javaslang-2.0.6.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-gradle-tooling.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-reflect.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-script-runtime.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/noarg-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/sam-with-receiver-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/javax.inject-1.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kapt3-idea.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-allopen-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-noarg-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-sam-with-receiver-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/jvm-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/maven-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/jps-common-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-serialization-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-serialization-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-coroutines-core-0.26.1-eap13.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-coroutines-jdk8-0.26.1-eap13.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
    <excluded>
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/allopen-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-extensions-compiler.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-extensions-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-lint.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/javaslang-2.0.6.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-gradle-tooling.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-reflect.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-script-runtime.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/noarg-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/sam-with-receiver-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/javax.inject-1.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kapt3-idea.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-allopen-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-noarg-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlin-sam-with-receiver-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/jvm-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/maven-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/android-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/jps-common-ide.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-serialization-compiler-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-serialization-ide-plugin.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-coroutines-core-0.26.1-eap13.jar!/" />
      <root url="jar://$PROJECT_DIR$/build/dependencies/build/kotlin/Kotlin/lib/kotlinx-coroutines-jdk8-0.26.1-eap13.jar!/" />
    </excluded>
  </library>
</component>


text:
"""
Script to activate LUFA for Arduino.
When LUFA is active, Arduinos USB stack is deactivated and cannot be compiled against.

To deactivate LUFA and activate Arduinos USB stack, use the deactivate.py script.
"""

import textwrap
import fileinput
import re
import os
import shutil

# Get absolute paths
ARDUINO_LUFA_DIR = os.path.dirname(__file__)
ARDUINO_DIR = os.path.abspath(os.path.join(ARDUINO_LUFA_DIR, '../..'))

def absolute_path(path):
    """Converts path relative to ARDUINO_DIR to absolute one"""
    return os.path.abspath(os.path.join(ARDUINO_DIR, path))

#---------------------#
# File path constants #
#---------------------#

ARDUINO_HARDWARE_DIR = 'hardware/arduino'
ARDUINO_LUFA_HARDWARE_DIR = 'hardware/arduino-LUFA'
ARDUINO_CORE_DIR = 'hardware/arduino/avr/cores/arduino/'
ARDUINO_LUFA_CORE_DIR = 'hardware/arduino-LUFA/avr/cores/arduino/'
ARDUINO_LUFA_AVR_DIR = 'hardware/arduino-LUFA/avr'

FILES_TO_BLOCK = [
    'CDC.cpp',
    'PluggableUSB.cpp',
    'PluggableUSB.h',
    'USBAPI.h',
    'USBCore.cpp',
    'USBCore.h',
    'USBDesc.h'
]

SECTIONS_TO_HIDE_IN_FILES = {
    'Arduino.h' :
        textwrap.dedent("""
            #include "USBAPI.h"
            #if defined(HAVE_HWSERIAL0) && defined(HAVE_CDCSERIAL)
            #error "Targets with both UART0 and CDC serial not supported"
            #endif
        """),

    'main.cpp' :
        textwrap.dedent("""
            #if defined(USBCON)
            \tUSBDevice.attach();
            #endif
        """)
}

#Text to be inserted above hidden sections in files
#Because the file might contain multi-line comments, #if 0 ... #endif are used
HIDE_HEADER = textwrap.dedent("""
    //=====================================
    //== This section is hidden by LUFA! ==
    //=====================================
    #if 0
""")

#Text to be inserted below hidden section in files
#This contains additional text to make sure it is easily found when deactivating LUFA
HIDE_FOOTER = textwrap.dedent("""
    END OF HIDDEN SECTION
    #endif
""")

#--------#
# Hiding #
#--------#
def hide_whole_file(path):
    """Hide whole file"""
    hide_section_in_file(path, False)

def unhide_whole_file(path):
    """Make previously hidden file available again"""
    unhide_section_in_file(path)

def hide_section_in_file(path, section):
    """
    Hide section
    If section is a falsey value, the whole file will be hidden
    """

    file_content = ""
    path = absolute_path(path)

    with open(path, 'r') as original:
        file_content = original.read()

    # Check if header or footer are already present
    if file_content.find(HIDE_HEADER) != -1 \
       or file_content.find(HIDE_HEADER) != -1:
        print(("INFO: Hide header and/or footer already present in file `{}'. "
               + 'File was left untouched.').format(path))
        return

    # Prepare insertion indices
    if section:
        section_length = len(section)
        section_start = file_content.find(section)
        if section_start == -1:
            print(("WARNING: Section below not found in file `{}`. "
                   + 'File was left untouched. Section:\n{}\n')
                  .format(path, section))
            return
    else:
        # Comment out whole file if section is falsey
        section_length = len(file_content)
        section_start = 0

    # Insert header before and footer after the section to hide
    modified_content = file_content[0 : section_start]                    \
                       + HIDE_HEADER                                      \
                       + file_content[section_start : section_start + section_length]\
                       + HIDE_FOOTER                                      \
                       + file_content[section_start + section_length : len(file_content)]\

    with open(path, 'w') as modified:
        modified.write(modified_content)

    # Report whether whole file or just a section has been hidden
    if not section:
        print("Successfully hid file `{}'!".format(path))
    else:
        print("Successfully hid section in file `{}'!".format(path))

def unhide_section_in_file(path):
    """Make previously hidden section available again"""

    file_content = ""
    path = absolute_path(path)

    with open(path, 'r') as original:
        file_content = original.read()

    header_start = file_content.find(HIDE_HEADER)
    footer_start = file_content.find(HIDE_FOOTER)

    # Check if header and footer were found
    if header_start == -1 or footer_start == -1:
        print(("WARNING: Hide header and/or footer not found in file `{}'. "
               + 'File was left untouched.').format(path))
        return

    # Check if header appears before footer
    if header_start > footer_start:
        print(("WARNING: Hide footer found before header in file `{}'. "
               + 'File was left untouched, it requires manual attention!')
              .format(path))
        return

    # Remove header and footer
    modified_content = file_content[0 : header_start]                                   \
                       + file_content[header_start + len(HIDE_HEADER) : footer_start]   \
                       + file_content[footer_start + len(HIDE_FOOTER) : len(file_content)]

    with open(path, 'w') as modified:
        modified.write(modified_content)

    print("Successfully unhid section in file `{}'!".format(path))

#--------------------------#
# Arudino version checking #
#--------------------------#
SUPPORTED_ARDUINO_IDE_VERSIONS = ['1.8.2', '1.8.3', '1.8.12', '1.8.13']

def get_arduino_ide_version():
    """Determine Arduino IDE version"""

    version_line = ""

    # Read changelog file. The first line always starts with 'ARDUINO X.Y.Z'
    with open(absolute_path('revisions.txt'), 'r') as revisions:
        version_line = revisions.readline()

    # Extract version number as string
    version_string = re.findall('[0-9].[0-9].[0-9][0-9]?', version_line)[0]

    return version_string

#----------------#
# Main functions #
#----------------#
def main_common(block_and_hide, folder):
    """Common functionality for activate and deactivate scripts"""

    arduino_ide_version = get_arduino_ide_version()

    if not arduino_ide_version in SUPPORTED_ARDUINO_IDE_VERSIONS:
        print(('WARNING: Arduino version {} has not been tested to be compatible.' \
               + "This script might not work properly.").format(arduino_ide_version))
    else:
        print('Compatible Arduino IDE version {} detected!' .format(arduino_ide_version))

    for file_to_block in FILES_TO_BLOCK:
        path = os.path.join(folder, file_to_block)
        if block_and_hide:
            hide_whole_file(path)
        else:
            unhide_whole_file(path)

    for in_file, section in SECTIONS_TO_HIDE_IN_FILES.items():
        path = os.path.join(folder, in_file)
        if block_and_hide:
            hide_section_in_file(path, section)
        else:
            unhide_section_in_file(path)

def copy_hardware_dir():
    shutil.copytree(absolute_path(ARDUINO_HARDWARE_DIR),absolute_path(ARDUINO_LUFA_HARDWARE_DIR))

def update_platform():
    myfile = fileinput.FileInput(absolute_path(os.path.join(ARDUINO_LUFA_AVR_DIR, "platform.txt")), inplace=True)

    for line in myfile:
        line = re.sub(r"name=(.*) AVR", r"name=\1 LUFA AVR", line.rstrip())
        print(line)

def update_boards():
    unsupported = []
    myfile = fileinput.FileInput(absolute_path(os.path.join(ARDUINO_LUFA_AVR_DIR, "boards.txt")), inplace=True)

    #first pass: append (LUFA) to names and check for unsupported boards
    for line in myfile:
        line = re.sub(r"name=(.*)", r"name=\1 (LUFA)", line.rstrip())

        if "build.mcu=" in line and not "atmega32u4" in line:
             unsup = line.split(".",1)[0]
             unsupported.append(unsup)
        print(line)

    #second pass: filter unsupported boards
    myfile = fileinput.FileInput(absolute_path(os.path.join(ARDUINO_LUFA_AVR_DIR, "boards.txt")), inplace=True)
    for line in myfile:
        if line.split(".",1)[0] in unsupported:
            line = "#" + line
            line = re.sub(r"LUFA", r"LUFA not supported", line.rstrip())
        print(line.rstrip())

def activate():
    """Activate function"""
    main_common(True, ARDUINO_CORE_DIR)

def deactivate():
    """Deactivate function"""
    main_common(False, ARDUINO_CORE_DIR)

def install():
    """Install function"""
    copy_hardware_dir()
    main_common(True, ARDUINO_LUFA_CORE_DIR)
    update_platform()
    update_boards()

def uninstall():
    """Uninstall function"""
    shutil.rmtree(absolute_path(ARDUINO_LUFA_HARDWARE_DIR))

if __name__ == '__main__':
    activate()


text:
package com.qualogy.qafe.bind.presentation.layout;

public class VerticalLayout extends Layout {

	/**
	 *
	 */
	private static final long serialVersionUID = 6432891665878790302L;

}


text:
    <button type="button" class="close" data-dismiss="modal" ng-click="close()">×Close</button>

Template Preview

    <button class="btn btn-primary" ng-click="close()">CLOSE</button>


text:
Registers is an [atom-shell] application for taking pupil attendance registers in Primary Schools (or any institution with fixed classes).

Grab a copy of Registers from the [Releases Page](https://github.com/Ed-ITSolutions/Registers/releases)

See the [wiki] for more info on how to use Registers

## Pre-Reqs

 - MySQL

[atom-shell]: https://github.com/atom/atom-shell
[wiki]: https://github.com/Ed-ITSolutions/Registers/wiki


text:
package flex2.tools;

import flex2.compiler.common.CompilerConfiguration;
import flex2.compiler.common.Configuration;
import flex2.compiler.common.ConfigurationPathResolver;
import flex2.compiler.config.ConfigurationBuffer;
import flex2.compiler.config.ConfigurationException;
import flex2.compiler.config.ConfigurationInfo;
import flex2.compiler.config.ConfigurationValue;
import flex2.compiler.config.FileConfigurator;
import flex2.compiler.io.VirtualFile;
import flex2.compiler.util.ThreadLocalToolkit;
import flash.util.FileUtils;

import java.io.File;
import java.io.PrintWriter;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * compc specific configuration.
 */
public class CompcConfiguration extends ToolsConfiguration
{
    // Hack to get around not being able to override the static method
    // getOutputInfo() in subclasses.
    protected static boolean outputRequired = true;

	public static Map<String, String> getAliases()
    {
        // FIXME: would make more sense to have these as part of ConfigurationInfo
        Map<String, String> map = new HashMap<String, String>();
        map.put( "o", "output" );
        map.put( "ic", "include-classes" );
        map.put( "in", "include-namespaces" );
        map.put( "is", "include-sources" );
        map.put( "if", "include-file" );
		map.put( "ir", "include-resource-bundles" );
	    map.putAll(Configuration.getAliases());
		return map;
    }

    public void validate( ConfigurationBuffer cfgbuf ) throws ConfigurationException
    {
    	super.validate( cfgbuf );

        validateSwcInputs();

        // verify that if -include-inheritance-dependencies is set that
        // -include-classes is not null
        if (getIncludeInheritanceDependenciesOnly() && getClasses().size() == 0)
            throw new ConfigurationException.MissingIncludeClasses();
    }

    protected void validateSwcInputs() throws ConfigurationException
    {
        if (getIncludeSources().isEmpty() &&
            getClasses().isEmpty() &&
            getNamespaces().isEmpty() &&
            ((getCompilerConfiguration().getIncludeLibraries() == null) ||
             (getCompilerConfiguration().getIncludeLibraries().length == 0)) &&
            getFiles().isEmpty() &&
            getIncludeResourceBundles().isEmpty())
        {
            throw new ConfigurationException.NoSwcInputs( null, null, -1 );
        }
    }

    //
    // 'directory' option
    //

    private boolean isDirectory;

    public boolean isDirectory()
    {
        return isDirectory;
    }

    public void cfgDirectory(ConfigurationValue val, boolean directory)
    {
        this.isDirectory = directory;
    }

	//
	// 'help' option
	//

    // dummy, just a trigger for help text
    public void cfgHelp(ConfigurationValue cv, String[] keywords)
    {
        // intercepted upstream in order to allow help text to be printed even when args are otherwise bad
    }

    public static ConfigurationInfo getHelpInfo()
    {
        return new ConfigurationInfo( -1, "keyword" )
        {
            public boolean isGreedy()
			{
				return true;
			}

            public boolean isDisplayed()
			{
				return false;
			}
        };
    }

    //
	// 'include-classes' option
	//

    private List<String> classes = new LinkedList<String>();

    public List<String> getClasses()
    {
        return classes;
    }

    public void cfgIncludeClasses(ConfigurationValue cv, List<String> args) throws ConfigurationException
    {
        classes.addAll( toQNameString(args) );
    }

    public static ConfigurationInfo getIncludeClassesInfo()
    {
        return new ConfigurationInfo( -1, new String[] { "class" } )
        {
            public boolean allowMultiple()
            {
                return true;
            }
        };
    }

	//
	// 'include-file' option
	//

    private Map<String, VirtualFile> files = new HashMap<String, VirtualFile>();

    // This method is for ConfigurationBuffer so include files can be included
    // in the checksum. This is considered a getter method (using reflection)
    // for the -include-file option so the method name must be singular even
    // though a list is returned.
    public VirtualFile[] getIncludeFile()
    {
        VirtualFile[] retFiles = new VirtualFile[files.size()];
        int i = 0;

        for (Map.Entry<String, VirtualFile>entry : files.entrySet())
        {
            retFiles[i++] = entry.getValue();
        }

        return retFiles;
    }

    public Map<String, VirtualFile> getFiles()
    {
        return files;
    }

    public void addFiles(Map<String, VirtualFile> f)
    {
        files.putAll(f);
    }

    public void cfgIncludeFile( ConfigurationValue cfgval, String name, String path)
            throws ConfigurationException
    {
        if (files.containsKey(name))
        {
            throw new ConfigurationException.RedundantFile(name, cfgval.getVar(), cfgval.getSource(), cfgval.getLine() );
        }
        VirtualFile f = ConfigurationPathResolver.getVirtualFile( path, configResolver, cfgval );
        files.put(name, f);
    }

    public static ConfigurationInfo getIncludeFileInfo()
    {
        return new ConfigurationInfo( new String[] {"name", "path"} )
        {
            public boolean isPath()
            {
                return true;
            }

            public boolean allowMultiple()
			{
				return true;
			}
        };
    }

	//
	// 'include-stylesheet' option
	//

    private Map<String, VirtualFile> stylesheets = new HashMap<String, VirtualFile>();

    public Map<String, VirtualFile> getStylesheets()
    {
        return stylesheets;
    }

    public void addStylesheets(Map<String, VirtualFile> f)
    {
        stylesheets.putAll(f);
    }

    public void cfgIncludeStylesheet( ConfigurationValue cfgval, String name, String path)
            throws ConfigurationException
    {
        if (stylesheets.containsKey(name))
        {
            throw new ConfigurationException.RedundantFile(name, cfgval.getVar(), cfgval.getSource(), cfgval.getLine() );
        }
        VirtualFile f = ConfigurationPathResolver.getVirtualFile( path, configResolver, cfgval );
        stylesheets.put(name, f);
    }

    public static ConfigurationInfo getIncludeStylesheetInfo()
    {
        return new ConfigurationInfo( new String[] {"name", "path"} )
        {
            public boolean isPath()
            {
                return true;
            }

            public boolean allowMultiple()
			{
				return true;
			}
        };
    }

	//
	// 'include-lookup-only' option
	//

	private boolean includeLookupOnly = false;

	public boolean getIncludeLookupOnly()
	{
		return includeLookupOnly;
	}

	/**
	 * include-lookup-only (hidden)
	 * if true, manifest entries with lookupOnly=true are included in SWC catalog. default is false.
	 * This exists only so that manifests can mention classes that come in from filespec rather than classpath,
	 * e.g. in playerglobal.swc.
	 * TODO could make this a per-namespace setting. Or, if we modify catalog-builder to handle defs from filespecs,
	 * could remove it entirely.
	 */
	public void cfgIncludeLookupOnly(ConfigurationValue val, boolean includeLookupOnly)
	{
		this.includeLookupOnly = includeLookupOnly;
	}

	public static ConfigurationInfo getIncludeLookupOnlyInfo()
	{
		return new ConfigurationInfo()
		{
			public boolean isAdvanced()
			{
				return true;
			}
		};
	}

	//
    // 'include-namespaces' option
    //

    private List<String> namespaces = new LinkedList<String>();

    public List<String> getNamespaces()
    {
        return namespaces;
    }

    public void cfgIncludeNamespaces(ConfigurationValue val, List<String> includeNamespaces)
    {
        namespaces.addAll(includeNamespaces);
    }

    public static ConfigurationInfo getIncludeNamespacesInfo()
    {
        return new ConfigurationInfo( -1, new String[] { "uri" } )
        {
            public boolean allowMultiple()
            {
                return true;
            }
        };
    }

    //
    // 'include-resource-bundles' option
    //

	private List<String> resourceBundles = new LinkedList<String>();

    public List<String> getIncludeResourceBundles()
	{
		return resourceBundles;
	}

	public void cfgIncludeResourceBundles(ConfigurationValue val, List<String> includeResourceBundles)
	{
		resourceBundles.addAll(toQNameString(includeResourceBundles));
	}

	public static ConfigurationInfo getIncludeResourceBundlesInfo()
	{
		return new ConfigurationInfo( -1, new String[] { "bundle" } )
		{
			public boolean allowMultiple()
			{
				return true;
			}
		};
	}

    //
	// 'include-sources' option
	//

    private List<String> sources = new LinkedList<String>();

    public void setIncludeSources(List<String> sources)
    {
        this.sources = sources;
    }

    public List<String> getIncludeSources()
    {
        return sources;
    }

    public void cfgIncludeSources(ConfigurationValue cv, List<String> args) throws ConfigurationException
    {
    	CompilerConfiguration compilerConfiguration = getCompilerConfiguration();
    	String[] paths = new String[args.size()];
    	args.toArray(paths);
    	VirtualFile[] newPathElements = compilerConfiguration.expandTokens(paths, compilerConfiguration.getLocales(), cv);

        for (VirtualFile v  : newPathElements)
           sources.add(v.getName());
    }

    public static ConfigurationInfo getIncludeSourcesInfo()
    {
        return new ConfigurationInfo( -1, new String[] { "path-element" } )
        {
            public boolean allowMultiple()
            {
                return true;
            }

            public boolean isPath()
            {
                return true;
            }
        };
    }

	//
	// 'load-config' option
	//

    // dummy, ignored - pulled out of the buffer
    public void cfgLoadConfig(ConfigurationValue cv, String filename) throws ConfigurationException
    {
    }

    public static ConfigurationInfo getLoadConfigInfo()
    {
        return new ConfigurationInfo( 1, "filename" )
        {
            public boolean allowMultiple()
            {
                return true;
            }
        };
    }

    //
	// 'output' option
	//

    public void cfgOutput(ConfigurationValue val, String output) throws ConfigurationException
    {
		if (output != null && (output.startsWith(File.separator) || output.startsWith("/") || FileUtils.isAbsolute(new File(output))))
		{
			this.output = output;
		}
		else if (val.getContext() != null)
        {
            this.output = FileUtils.addPathComponents( val.getContext(), output, File.separatorChar );
        }
        else
        {
            this.output = output;
        }

        if (isDirectory)
        {
            File d = new File( this.output );

            if (d.exists())
            {
                if (!d.isDirectory())
                    throw new ConfigurationException.NotADirectory( this.output, val.getVar(), val.getSource(), val.getLine() );
                else
                {
                    File[] fl = d.listFiles();
                    if ((fl != null) && (fl.length > 0))
                    {
                        throw new ConfigurationException.DirectoryNotEmpty(this.output, val.getVar(), val.getSource(), val.getLine() );
                    }
                }
            }
        }
    }

    public static ConfigurationInfo getOutputInfo()
    {
        return new ConfigurationInfo(1, "filename")
        {
            public String[] getPrerequisites()
            {
                return new String[] {"directory"} ;
            }

            public boolean isRequired()
            {
                return outputRequired;
            }
        };
    }

    public String getTargetFile()
    {
        return null;
    }

    //
    // 'root' option
    //

	public void cfgRoot(ConfigurationValue val, String rootStr)
            throws ConfigurationException
    {
        throw new ConfigurationException.ObsoleteVariable( "source-path", val.getVar(),
                                                            val.getSource(), val.getLine() );
    }

    public static ConfigurationInfo getRootInfo()
    {
        return new ConfigurationInfo()
        {
            public boolean isAdvanced()
            {
                return true;
            }

            public boolean isHidden()
            {
                return true;
            }
        };
    }

	//
	// 'version' option
	//

    // dummy, just a trigger for version info
    public void cfgVersion(ConfigurationValue cv, boolean dummy)
    {
        // intercepted upstream in order to allow version into to be printed even when required args are missing
    }

	//
	// compute-digest option
	//

	private boolean computeDigest = true;

	public boolean getComputeDigest()
	{
		return computeDigest;
	}

	/**
	 * compute-digest option
	 *
	 * @param cv
	 * @param b
	 */
	public void cfgComputeDigest(ConfigurationValue cv, boolean b)
	{
		computeDigest = b;
	}
}


text:
package space.spacelift.mq.proxy.serializers

import akka.serialization.Serializer
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization

object JsonSerializer extends Serializer {
  implicit val formats = org.json4s.DefaultFormats ++ org.json4s.ext.JodaTimeSerializers.all

  // scalastyle:off magic.number
  def identifier: Int = 123456789
  // scalastyle:on magic.number

  def includeManifest: Boolean = true

  def toBinary(o: AnyRef): Array[Byte] = Serialization.write(o).getBytes("UTF-8")

  def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = {
    require(manifest.isDefined)
    val string = new String(bytes)
    implicit val mf = Manifest.classType(manifest.get)
    Serialization.read(if (string.length == 0) "{}" else string)
  }
}


text:
"""Test entity_registry API."""
from unittest.mock import ANY

import pytest

from homeassistant.components.config import entity_registry
from homeassistant.const import ATTR_ICON
from homeassistant.helpers.device_registry import DeviceEntryDisabler
from homeassistant.helpers.entity_registry import (
    EVENT_ENTITY_REGISTRY_UPDATED,
    RegistryEntry,
    RegistryEntryDisabler,
    RegistryEntryHider,
    async_get as async_get_entity_registry,
)

from tests.common import (
    MockConfigEntry,
    MockEntity,
    MockEntityPlatform,
    mock_device_registry,
    mock_registry,
)

@pytest.fixture
def client(hass, hass_ws_client):
    """Fixture that can interact with the config manager API."""
    hass.loop.run_until_complete(entity_registry.async_setup(hass))
    yield hass.loop.run_until_complete(hass_ws_client(hass))

@pytest.fixture
def device_registry(hass):
    """Return an empty, loaded, registry."""
    return mock_device_registry(hass)

async def test_list_entities(hass, client):
    """Test list entries."""
    mock_registry(
        hass,
        {
            "test_domain.name": RegistryEntry(
                entity_id="test_domain.name",
                unique_id="1234",
                platform="test_platform",
                name="Hello World",
            ),
            "test_domain.no_name": RegistryEntry(
                entity_id="test_domain.no_name",
                unique_id="6789",
                platform="test_platform",
            ),
        },
    )

    await client.send_json({"id": 5, "type": "config/entity_registry/list"})
    msg = await client.receive_json()

    assert msg["result"] == [
        {
            "area_id": None,
            "config_entry_id": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.name",
            "has_entity_name": False,
            "hidden_by": None,
            "icon": None,
            "id": ANY,
            "unique_id": ANY,
            "name": "Hello World",
            "original_name": None,
            "platform": "test_platform",
        },
        {
            "area_id": None,
            "config_entry_id": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.no_name",
            "has_entity_name": False,
            "hidden_by": None,
            "icon": None,
            "id": ANY,
            "unique_id": ANY,
            "name": None,
            "original_name": None,
            "platform": "test_platform",
        },
    ]

    mock_registry(
        hass,
        {
            "test_domain.name": RegistryEntry(
                entity_id="test_domain.name",
                unique_id="1234",
                platform="test_platform",
                name="Hello World",
            ),
        },
    )

    hass.bus.async_fire(
        EVENT_ENTITY_REGISTRY_UPDATED,
        {"action": "create", "entity_id": "test_domain.no_name"},
    )
    await client.send_json({"id": 6, "type": "config/entity_registry/list"})
    msg = await client.receive_json()

    assert msg["result"] == [
        {
            "area_id": None,
            "config_entry_id": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.name",
            "has_entity_name": False,
            "hidden_by": None,
            "icon": None,
            "id": ANY,
            "unique_id": ANY,
            "name": "Hello World",
            "original_name": None,
            "platform": "test_platform",
        },
    ]

async def test_get_entity(hass, client):
    """Test get entry."""
    mock_registry(
        hass,
        {
            "test_domain.name": RegistryEntry(
                entity_id="test_domain.name",
                unique_id="1234",
                platform="test_platform",
                name="Hello World",
            ),
            "test_domain.no_name": RegistryEntry(
                entity_id="test_domain.no_name",
                unique_id="6789",
                platform="test_platform",
            ),
        },
    )

    await client.send_json(
        {"id": 5, "type": "config/entity_registry/get", "entity_id": "test_domain.name"}
    )
    msg = await client.receive_json()

    assert msg["result"] == {
        "area_id": None,
        "capabilities": None,
        "config_entry_id": None,
        "device_class": None,
        "device_id": None,
        "disabled_by": None,
        "entity_category": None,
        "entity_id": "test_domain.name",
        "hidden_by": None,
        "icon": None,
        "id": ANY,
        "has_entity_name": False,
        "name": "Hello World",
        "options": {},
        "original_device_class": None,
        "original_icon": None,
        "original_name": None,
        "platform": "test_platform",
        "unique_id": "1234",
    }

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/get",
            "entity_id": "test_domain.no_name",
        }
    )
    msg = await client.receive_json()

    assert msg["result"] == {
        "area_id": None,
        "capabilities": None,
        "config_entry_id": None,
        "device_class": None,
        "device_id": None,
        "disabled_by": None,
        "entity_category": None,
        "entity_id": "test_domain.no_name",
        "hidden_by": None,
        "icon": None,
        "id": ANY,
        "has_entity_name": False,
        "name": None,
        "options": {},
        "original_device_class": None,
        "original_icon": None,
        "original_name": None,
        "platform": "test_platform",
        "unique_id": "6789",
    }

async def test_update_entity(hass, client):
    """Test updating entity."""
    registry = mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                name="before update",
                icon="icon:before update",
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get("test_domain.world")
    assert state is not None
    assert state.name == "before update"
    assert state.attributes[ATTR_ICON] == "icon:before update"

    # UPDATE AREA, DEVICE_CLASS, HIDDEN_BY, ICON AND NAME
    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "area_id": "mock-area-id",
            "device_class": "custom_device_class",
            "hidden_by": "user",  # We exchange strings over the WS API, not enums
            "icon": "icon:after update",
            "name": "after update",
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": "mock-area-id",
            "capabilities": None,
            "config_entry_id": None,
            "device_class": "custom_device_class",
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.world",
            "hidden_by": "user",  # We exchange strings over the WS API, not enums
            "icon": "icon:after update",
            "id": ANY,
            "has_entity_name": False,
            "name": "after update",
            "options": {},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        }
    }

    state = hass.states.get("test_domain.world")
    assert state.name == "after update"
    assert state.attributes[ATTR_ICON] == "icon:after update"

    # UPDATE HIDDEN_BY TO ILLEGAL VALUE
    await client.send_json(
        {
            "id": 7,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "hidden_by": "ivy",
        }
    )

    msg = await client.receive_json()
    assert not msg["success"]

    assert registry.entities["test_domain.world"].hidden_by is RegistryEntryHider.USER

    # UPDATE DISABLED_BY TO USER
    await client.send_json(
        {
            "id": 8,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "disabled_by": "user",  # We exchange strings over the WS API, not enums
        }
    )

    msg = await client.receive_json()
    assert msg["success"]

    assert hass.states.get("test_domain.world") is None
    assert (
        registry.entities["test_domain.world"].disabled_by is RegistryEntryDisabler.USER
    )

    # UPDATE DISABLED_BY TO NONE
    await client.send_json(
        {
            "id": 9,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "disabled_by": None,
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": "mock-area-id",
            "capabilities": None,
            "config_entry_id": None,
            "device_class": "custom_device_class",
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.world",
            "hidden_by": "user",  # We exchange strings over the WS API, not enums
            "icon": "icon:after update",
            "id": ANY,
            "has_entity_name": False,
            "name": "after update",
            "options": {},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        },
        "require_restart": True,
    }

    # UPDATE ENTITY OPTION
    await client.send_json(
        {
            "id": 10,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "options_domain": "sensor",
            "options": {"unit_of_measurement": "beard_second"},
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": "mock-area-id",
            "capabilities": None,
            "config_entry_id": None,
            "device_class": "custom_device_class",
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.world",
            "hidden_by": "user",  # We exchange strings over the WS API, not enums
            "icon": "icon:after update",
            "id": ANY,
            "has_entity_name": False,
            "name": "after update",
            "options": {"sensor": {"unit_of_measurement": "beard_second"}},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        },
    }

async def test_update_entity_require_restart(hass, client):
    """Test updating entity."""
    entity_id = "test_domain.test_platform_1234"
    config_entry = MockConfigEntry(domain="test_platform")
    config_entry.add_to_hass(hass)
    platform = MockEntityPlatform(hass)
    platform.config_entry = config_entry
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get(entity_id)
    assert state is not None

    # UPDATE DISABLED_BY TO NONE
    await client.send_json(
        {
            "id": 8,
            "type": "config/entity_registry/update",
            "entity_id": entity_id,
            "disabled_by": None,
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": None,
            "capabilities": None,
            "config_entry_id": config_entry.entry_id,
            "device_class": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": entity_id,
            "icon": None,
            "id": ANY,
            "hidden_by": None,
            "has_entity_name": False,
            "name": None,
            "options": {},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        },
        "require_restart": True,
    }

async def test_enable_entity_disabled_device(hass, client, device_registry):
    """Test enabling entity of disabled device."""
    entity_id = "test_domain.test_platform_1234"
    config_entry = MockConfigEntry(domain="test_platform")
    config_entry.add_to_hass(hass)

    device = device_registry.async_get_or_create(
        config_entry_id="1234",
        connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
        identifiers={("bridgeid", "0123")},
        manufacturer="manufacturer",
        model="model",
        disabled_by=DeviceEntryDisabler.USER,
    )
    device_info = {
        "connections": {("ethernet", "12:34:56:78:90:AB:CD:EF")},
    }

    platform = MockEntityPlatform(hass)
    platform.config_entry = config_entry
    entity = MockEntity(unique_id="1234", device_info=device_info)
    await platform.async_add_entities([entity])

    state = hass.states.get(entity_id)
    assert state is None

    entity_reg = async_get_entity_registry(hass)
    entity_entry = entity_reg.async_get(entity_id)
    assert entity_entry.config_entry_id == config_entry.entry_id
    assert entity_entry.device_id == device.id
    assert entity_entry.disabled_by == RegistryEntryDisabler.DEVICE

    # UPDATE DISABLED_BY TO NONE
    await client.send_json(
        {
            "id": 8,
            "type": "config/entity_registry/update",
            "entity_id": entity_id,
            "disabled_by": None,
        }
    )

    msg = await client.receive_json()

    assert not msg["success"]

async def test_update_entity_no_changes(hass, client):
    """Test update entity with no changes."""
    mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                name="name of entity",
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get("test_domain.world")
    assert state is not None
    assert state.name == "name of entity"

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "name": "name of entity",
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": None,
            "capabilities": None,
            "config_entry_id": None,
            "device_class": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.world",
            "hidden_by": None,
            "icon": None,
            "id": ANY,
            "has_entity_name": False,
            "name": "name of entity",
            "options": {},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        }
    }

    state = hass.states.get("test_domain.world")
    assert state.name == "name of entity"

async def test_get_nonexisting_entity(client):
    """Test get entry with nonexisting entity."""
    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/get",
            "entity_id": "test_domain.no_name",
        }
    )
    msg = await client.receive_json()

    assert not msg["success"]

async def test_update_nonexisting_entity(client):
    """Test update a nonexisting entity."""
    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.no_name",
            "name": "new-name",
        }
    )
    msg = await client.receive_json()

    assert not msg["success"]

async def test_update_entity_id(hass, client):
    """Test update entity id."""
    mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    assert hass.states.get("test_domain.world") is not None

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "new_entity_id": "test_domain.planet",
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": None,
            "capabilities": None,
            "config_entry_id": None,
            "device_class": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": "test_domain.planet",
            "hidden_by": None,
            "icon": None,
            "id": ANY,
            "has_entity_name": False,
            "name": None,
            "options": {},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        }
    }

    assert hass.states.get("test_domain.world") is None
    assert hass.states.get("test_domain.planet") is not None

async def test_update_existing_entity_id(hass, client):
    """Test update entity id to an already registered entity id."""
    mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
            ),
            "test_domain.planet": RegistryEntry(
                entity_id="test_domain.planet",
                unique_id="2345",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
            ),
        },
    )
    platform = MockEntityPlatform(hass)
    entities = [MockEntity(unique_id="1234"), MockEntity(unique_id="2345")]
    await platform.async_add_entities(entities)

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "new_entity_id": "test_domain.planet",
        }
    )

    msg = await client.receive_json()

    assert not msg["success"]

async def test_update_invalid_entity_id(hass, client):
    """Test update entity id to an invalid entity id."""
    mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entities = [MockEntity(unique_id="1234"), MockEntity(unique_id="2345")]
    await platform.async_add_entities(entities)

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "new_entity_id": "another_domain.planet",
        }
    )

    msg = await client.receive_json()

    assert not msg["success"]

async def test_remove_entity(hass, client):
    """Test removing entity."""
    registry = mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                name="before update",
            )
        },
    )

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/remove",
            "entity_id": "test_domain.world",
        }
    )

    msg = await client.receive_json()

    assert msg["success"]
    assert len(registry.entities) == 0

async def test_remove_non_existing_entity(hass, client):
    """Test removing non existing entity."""
    mock_registry(hass, {})

    await client.send_json(
        {
            "id": 6,
            "type": "config/entity_registry/remove",
            "entity_id": "test_domain.world",
        }
    )

    msg = await client.receive_json()

    assert not msg["success"]


text:
package org.ovirt.engine.core.bll;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.ovirt.engine.core.bll.session.SessionDataContainer;
import org.ovirt.engine.core.common.PermissionSubject;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.users.VdcUser;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.ThreadLocalParamsContainer;

/** A test case for {@link CommandBase} */
public class CommandBaseTest {

    /** The session to use */
    private String session = "";

    /** A dummy class for testing CommandBase's functionality */
    @SuppressWarnings("serial")
    private class CommandBaseDummy extends CommandBase<VdcActionParametersBase> {

        /** A dummy constructor to pass parameters, since constructors aren't inherited in Java */
        protected CommandBaseDummy(VdcActionParametersBase params) {
            super(params);
        }

        @Override
        protected void executeCommand() {
            // Do nothing
        }

        @Override
        public List<PermissionSubject> getPermissionCheckSubjects() {
            return Collections.emptyList();
        }
    }

    @Before
    @After
    public void clearEnvironment() {
        ThreadLocalParamsContainer.clean();
        SessionDataContainer.getInstance().removeSession();
        SessionDataContainer.getInstance().removeSession(session);
    }

    /** Testing the constructor, which adds the user id to the thread local container */
    @Test
    public void testConstructor() {
        session = RandomStringUtils.random(10);

        VdcUser user = mock(VdcUser.class);
        when(user.getUserId()).thenReturn(Guid.EVERYONE);

        // Mock the parameters
        VdcActionParametersBase paramterMock = mock(VdcActionParametersBase.class);
        when(paramterMock.getSessionId()).thenReturn(session);

        SessionDataContainer.getInstance().setUser(session, user);

        // Create a command
        CommandBase<VdcActionParametersBase> command = new CommandBaseDummy(paramterMock);

        // Check the session
        assertEquals("wrong user id on command", user.getUserId(), command.getUserId());
        assertEquals("wrong user id on threadlocal", user, ThreadLocalParamsContainer.getVdcUser());
    }
}


text:
package com.microsoft.bingads.campaignmanagement;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ProductAd complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ProductAd">
 *   <complexContent>
 *     <extension base="{https://bingads.microsoft.com/CampaignManagement/v9}Ad">
 *       <sequence>
 *         <element name="PromotionalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProductAd", propOrder = {
    "promotionalText"
})
public class ProductAd
    extends Ad
{

    @XmlElement(name = "PromotionalText", nillable = true)
    protected String promotionalText;

    /**
     * Gets the value of the promotionalText property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPromotionalText() {
        return promotionalText;
    }

    /**
     * Sets the value of the promotionalText property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPromotionalText(String value) {
        this.promotionalText = value;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.

     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file.
-->
<org.chromium.chrome.browser.signin.AccountSigninView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:chrome="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="72dp"
        android:fillViewport="true">

        <LinearLayout
            android:id="@+id/fre_main_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center_horizontal">

            <TextView
                android:id="@+id/title"
                android:text="@string/signin_set_up_chrome"
                style="@style/FreTitle"/>

            <!-- The orientation of this view is changed dynamically to give a nicer layout when in
            landscape mode on devices with small screens. -->
            <LinearLayout
                android:id="@+id/fre_image_and_content"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:gravity="center_horizontal"
                android:layout_marginTop="@dimen/fre_vertical_spacing">

                <org.chromium.chrome.browser.firstrun.ImageCarousel
                    android:id="@+id/image"
                    android:layout_width="@dimen/signin_image_carousel_width"
                    android:layout_height="@dimen/fre_image_height" />

                <LinearLayout
                    android:id="@+id/fre_content_wrapper"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:layout_marginTop="@dimen/fre_vertical_spacing"
                    android:layout_marginEnd="@dimen/fre_content_margin"
                    android:layout_marginStart="@dimen/fre_content_margin"
                    android:orientation="vertical" >

                    <Spinner
                        style="@style/Widget.AppCompat.Spinner.Underlined"
                        android:id="@+id/google_accounts_spinner"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/fre_vertical_spacing"
                        android:layout_gravity="center_horizontal"
                        android:popupBackground="#ffffff"
                        android:paddingStart="0dp"
                        android:paddingEnd="0dp"
                        android:textColor="@color/fre_text_color" />

                    <TextView
                        android:id="@+id/confirm_account_email"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginBottom="16dp"
                        android:paddingTop="12dp"
                        android:paddingBottom="8dp"
                        android:textColor="@color/fre_text_color"
                        android:visibility="gone" />

                    <org.chromium.ui.widget.TextViewWithClickableSpans
                        android:id="@+id/description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:lineSpacingMultiplier="1.4"
                        android:text="@string/signin_account_choice_description"
                        android:textColor="@color/signin_light_text_color"
                        android:textSize="@dimen/fre_normal_text_size" />
                    </LinearLayout>

            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <!-- layout_height = 72dp = fre_button_bar_height + paddingTop -->
    <LinearLayout
        android:id="@+id/button_bar"
        android:layout_width="match_parent"
        android:layout_height="72dp"
        android:layout_gravity="bottom"
        android:orientation="horizontal"
        android:paddingTop="16dp"
        android:paddingStart="16dp"
        android:paddingEnd="16dp" >

        <!--suppress ButtonStyle -->
        <Button
            android:id="@+id/negative_button"
            style="@style/ButtonCompatBorderless"
            android:layout_width="wrap_content"
            android:layout_height="36dp"
            android:text="@string/fre_skip_text"
            android:textAllCaps="true"
            android:textColor="@color/light_active_color"
            android:textSize="14sp"
            android:layout_marginBottom="24dp" />

        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:visibility="invisible"/>

        <!--suppress ButtonStyle -->
        <org.chromium.ui.widget.ButtonCompat
            android:id="@+id/positive_button"
            android:layout_width="wrap_content"
            android:layout_height="36dp"
            android:text="@string/choose_account_sign_in"
            android:textAllCaps="true"
            android:textColor="@android:color/white"
            android:textSize="14sp"
            chrome:buttonColor="@color/light_active_color"
            android:layout_marginBottom="24dp" />

        <View
            android:id="@+id/positive_button_end_padding"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:visibility="gone"/>
    </LinearLayout>

</org.chromium.chrome.browser.signin.AccountSigninView>


text:
import {Component} from '@angular/core';
import {TestBed, async} from '@angular/core/testing';
import {MainComponent} from './main';

@Component({selector: 'fountain-techs', template: ''})
class MockTechsComponent {}
@Component({selector: 'fountain-footer', template: ''})
class MockFooterComponent {}
@Component({selector: 'fountain-header', template: ''})
class MockHeaderComponent {}
@Component({selector: 'calculator', template: ''})
class MockTitleComponent {}

describe('Main Component', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MainComponent,
        MockTechsComponent,
        MockFooterComponent,
        MockHeaderComponent,
        MockTitleComponent
      ]
    });
    TestBed.compileComponents();
  }));

  it('should render the header, title, techs and footer', () => {
    const fixture = TestBed.createComponent(MainComponent);
    fixture.detectChanges();
    const main = fixture.nativeElement;
    expect(main.querySelector('fountain-header')).toBeDefined();
    expect(main.querySelector('calculator')).toBeDefined();
    expect(main.querySelector('fountain-techs')).toBeDefined();
    expect(main.querySelector('fountain-footer')).toBeDefined();
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Orleankka.Core
{
    static class AssemblyScanner
    {
        public static IEnumerable<Type> ActorTypes(this Assembly assembly) => assembly.GetTypes()
            .Where(type => !type.IsAbstract && typeof(Actor).IsAssignableFrom(type));
    }
}


text:
package org.mybatis.guice.objectfactory;

import javax.inject.Inject;

import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

public class CustomObjectFactory extends DefaultObjectFactory {
    private static final long serialVersionUID = 7195913612693620013L;
    @Inject
    private CustomObject customObject;

    public CustomObject getCustomObject() {
        return customObject;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ImageView
        android:id="@+id/tweet__iv_profile_image"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="8dp"
        android:contentDescription="@string/profile_image"
        android:src="@drawable/default_profile_1_normal"/>

    <TextView
        android:id="@+id/tweet__tv_user_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/tweet__iv_profile_image"
        android:text="@string/user_name"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tweet__tv_screen_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tweet__tv_user_name"
        android:layout_marginStart="4dp"
        android:layout_toEndOf="@+id/tweet__tv_user_name"
        android:text="@string/screen_name"
        android:textColor="#a0a0a0"
        android:textSize="10sp"/>

    <TextView
        android:id="@+id/tweet__tv_create_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:text="@string/create_time"
        android:textColor="#a0a0a0"/>

    <TextView
        android:id="@+id/tweet__tv_text_body"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/tweet__tv_user_name"
        android:layout_below="@+id/tweet__tv_user_name"
        android:text="@string/text_body"/>

    <GridView
        android:id="@+id/tweet__gv_images"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/tweet__tv_user_name"
        android:layout_below="@+id/tweet__tv_text_body"
        android:horizontalSpacing="2dp"
        android:stretchMode="columnWidth">
    </GridView>

    <!-- control bar -->
    <ImageView
        android:id="@+id/tweet__iv_reply"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignStart="@+id/tweet__tv_user_name"
        android:layout_below="@+id/tweet__gv_images"
        android:contentDescription="@string/reply"
        android:paddingTop="4dp"
        android:src="@drawable/ic_action_reply_light"/>

    <ImageView
        android:id="@+id/tweet__iv_retweet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/tweet__tv_user_name"
        android:layout_below="@+id/tweet__gv_images"
        android:layout_marginStart="80dp"
        android:contentDescription="@string/retweet"
        android:paddingTop="8dp"
        android:src="@drawable/tw__ic_retweet_light"/>

    <TextView
        android:id="@+id/tweet__tv_retweet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tweet__gv_images"
        android:layout_marginStart="4dp"
        android:layout_toEndOf="@+id/tweet__iv_retweet"
        android:paddingTop="4dp"
        android:text="@string/zero"/>

    <ImageView
        android:id="@+id/tweet__iv_favorite"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignStart="@+id/tweet__tv_user_name"
        android:layout_below="@+id/tweet__gv_images"
        android:layout_marginStart="160dp"
        android:contentDescription="@string/favorite"
        android:paddingTop="4dp"
        android:src="@drawable/ic_tweet_action_inline_favorite"/>

    <TextView
        android:id="@+id/tweet__tv_favorite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tweet__gv_images"
        android:layout_marginStart="4dp"
        android:layout_toEndOf="@+id/tweet__iv_favorite"
        android:paddingTop="4dp"
        android:text="@string/zero"/>

</RelativeLayout>


text:
/*
  Murmur hash function, based on Austin Appleby's code from
  http://murmurhash.googlepages.com.  Murmur is a very fast, very
  well distributed hash function.
*/

#ifndef _KRB_MURMUR_HASH_HPP
#define _KRB_MURMUR_HASH_HPP

#include <inttypes.h>
#include <string.h>

class murmur_hash
{
public:
  uint32_t operator()(const void *key, uint32_t sz, uint32_t seed) const;
};

template <class Key>
struct murmur_hash_func : protected murmur_hash
{
  uint32_t operator()(Key v) const;
};

//////////////////////////////////////////////////////////////////////
// implementation details
//////////////////////////////////////////////////////////////////////

template <class Key>
uint32_t murmur_hash_func<Key>::operator()(Key v) const
{
  return this->operator()(&v, sizeof(v), 0);
}

// string specializations

template <>
struct murmur_hash_func<const char *> : protected murmur_hash
{
  uint32_t operator()(const char *v) const
  {
    return murmur_hash::operator()(v, strlen(v), 0);
  }
};

template <>
struct murmur_hash_func<char *> : protected murmur_hash
{
  uint32_t operator()(char *v) const
  {
    return murmur_hash::operator()(v, strlen(v), 0);
  }
};

#endif // _KRB_MURMUR_HASH_HPP