text:
#include <cstdlib>
#include <string>
#include <algorithm>

#include "rf/utils.h"
#include "rf/context.h"
#include "rf/ui.h"

#include "definitions.h"

#include "Systems/water.h"
#include "Systems/atmosphere.h"
#include "Systems/planet.h"
#include "Game/sun.h"
#include "tests.h"

// PLATFORM
int RadarMain(int argc, char **argv);
#if RF_WIN32
#include "radar_win32.cpp"
#elif RF_UNIX
#include "radar_unix.cpp"
#endif

#define DO_ATMOSPHERE 1
#define DO_WATER 0
#define DO_PLANET 0

memory *InitMemory()
{
    memory *Memory = (memory*)calloc(1, sizeof(memory));

	Memory->PermanentMemPool = rf::PoolCreate(32 * MB);
	Memory->SessionMemPool = rf::PoolCreate(512 * MB);
	Memory->ScratchMemPool = rf::PoolCreate(64 * MB);

    Memory->IsValid = Memory->PermanentMemPool && Memory->SessionMemPool && Memory->ScratchMemPool;

    return Memory;
}
void DestroyMemory(memory *Memory)
{
    if(Memory->IsValid)
    {
		rf::PoolFree(&Memory->PermanentMemPool);
		rf::PoolFree(&Memory->SessionMemPool);
		rf::PoolFree(&Memory->ScratchMemPool);
        Memory->IsValid = false;
    }
}

bool ParseConfig(config *ConfigOut, char const *Filename)
{
	path ExePath;
	rf::GetExecutablePath(ExePath);

	path ConfigPath;
	rf::ConcatStrings(ConfigPath, ExePath, Filename);

	void *Content = rf::ReadFileContentsNoContext(ConfigPath, 0);

	cJSON *root = nullptr;
	if (Content)
	{
		root = cJSON_Parse((char*)Content);
	}
	else
	{
		printf("Error parsing config file.\n");
	}

	ConfigOut->WindowX = rf::JSON_Get(root, "iWindowX", 200);
	ConfigOut->WindowY = rf::JSON_Get(root, "iWindowY", 200);
	ConfigOut->WindowWidth = rf::JSON_Get(root, "iWindowWidth", 960);
	ConfigOut->WindowHeight = rf::JSON_Get(root, "iWindowHeight", 540);
	ConfigOut->MSAA = rf::JSON_Get(root, "iMSAA", 0);
	ConfigOut->FullScreen = rf::JSON_Get(root, "bFullScreen", 0) != 0;
	ConfigOut->VSync = rf::JSON_Get(root, "bVSync", 0) != 0;
	ConfigOut->FOV = (real32)rf::JSON_Get(root, "fFOV", 75.0);
	ConfigOut->NearPlane = (real32)rf::JSON_Get(root, "fNearPlane", 0.1);
	ConfigOut->FarPlane = (real32)rf::JSON_Get(root, "fFarPlane", 10000.0);
	ConfigOut->AnisotropicFiltering = rf::JSON_Get(root, "iAnisotropicFiltering", 1);

	ConfigOut->CameraSpeedBase = (real32)rf::JSON_Get(root, "fCameraSpeedBase", 20.0);
	ConfigOut->CameraSpeedMult = rf::JSON_Get(root, "vCameraSpeedMult", vec4f(1));
	ConfigOut->CameraSpeedAngular = (real32)rf::JSON_Get(root, "fCameraSpeedAngular", 0.3);

	ConfigOut->CameraPosition = rf::JSON_Get(root, "vCameraPosition", vec3f(0, 6360001, 0));
	ConfigOut->CameraForward = rf::JSON_Get(root, "vCameraForward", vec3f(1, 0, 0));

	ConfigOut->TimeScale = (real32)rf::JSON_Get(root, "fTimescale", 30.0);

	if (Content) free(Content);

	return true;
}

void ReloadShaders(rf::context *Context)
{
    rf::ctx::RegisteredShaderClear(Context);
    path const &ExePath = rf::ctx::GetExePath(Context);

    path VSPath, FSPath;

    // TODO - TODO - PostProcessprogram shouldnt live in Context, this is application dependent
    rf::ConcatStrings(VSPath, ExePath, "data/shaders/screenquad_vert.glsl");
    rf::ConcatStrings(FSPath, ExePath, "data/shaders/hdr_frag.glsl");
    Context->ProgramPostProcess = BuildShader(Context, VSPath, FSPath);
    glUseProgram(Context->ProgramPostProcess);
    rf::SendInt(glGetUniformLocation(Context->ProgramPostProcess, "HDRFB"), 0);
    rf::CheckGLError("HDR Shader");

    Tests::ReloadShaders(Context);
    rf::ui::ReloadShaders(Context);

#if DO_WATER
    water::ReloadShaders(Context);
#endif
#if DO_ATMOSPHERE
    atmosphere::ReloadShaders(Context);
#endif
#if DO_PLANET
	planet::ReloadShaders(Context);
#endif
    rf::ctx::UpdateShaderProjection(Context);

    glUseProgram(0);
}

void MakeUI(memory *Memory, rf::context *Context, rf::input * /*Input*/)
{
    //game_system *System = (game_system*)Memory->PermanentMemPool;

#if 0
    console_log *Log = System->ConsoleLog;
    font *FontInfo = ui::GetFont(ui::FONT_DEFAULT);
    int32 LineGap = FontInfo->LineGap;
    int32 LogHeight = Context->WindowHeight/3;
    int32 LogCapacity = Log->StringCount - std::ceil((LogHeight) / (real32)LineGap);

    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    // NOTE - Drop Down Console
    static bool   ConsoleShow = false;
    static uint32 ConsolePanel = 0;
    static vec3i  ConsolePanelPos(0,0,0);
    static vec2i  ConsolePanelSize(Context->WindowWidth, LogHeight);
    static real32 ConsoleSlider = 0.f;
    uint32 ConsoleDecorationFlags = ui::DECORATION_BORDER;

    if(KEY_HIT(Input->KeyTilde))
    {
        ConsoleShow = !ConsoleShow;
        ConsoleDecorationFlags |= ui::DECORATION_FOCUS; // force focus when opening the console
    }

    if(ConsoleShow)
    {
        ConsolePanelSize = vec2i(Context->WindowWidth, LogHeight);
        ui::BeginPanel(&ConsolePanel, "", &ConsolePanelPos, &ConsolePanelSize, ui::COLOR_CONSOLEBG, ConsoleDecorationFlags);
            ui::MakeSlider(&ConsoleSlider, 0.f, (real32)LogCapacity);
            for(uint32 i = 0; i < Log->StringCount; ++i)
            {
                uint32 RIdx = (Log->ReadIdx + i) % CONSOLE_CAPACITY;
                real32 YOffset = (real32)i + ConsoleSlider - (real32)Log->StringCount;
                real32 YPos = LogHeight + YOffset * LineGap;
                if(YPos < 0)
                    continue;
                if(YPos >= LogHeight)
                    break;
                vec2i Position(0, YPos);
                ui::MakeText((void*)Log->MsgStack[RIdx], Log->MsgStack[RIdx], ui::FONT_CONSOLE, Position,
                        ui::COLOR_CONSOLEFG, 1.f, Context->WindowWidth);
            }
        ui::EndPanel();
    }
#endif

    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    // NOTE - System Panel
    static bool SystemShow = false;

    vec2i UIStackPanelSize(360, 0);

    static uint32 SystemButtonPanel = 0;
    static char SystemButtonStr[16];
    static vec2i SystemButtonSize(25);
    vec3i SystemButtonPos(Context->WindowWidth-SystemButtonSize.x, 0, 0);
    static uint32 SystemButtonID = 0;
    snprintf(SystemButtonStr, 16, "%s", ICON_FA_COG);
    rf::ui::BeginPanel(&SystemButtonPanel, "", &SystemButtonPos, &SystemButtonSize, rf::ui::COLOR_PANELBG, rf::ui::DECORATION_INVISIBLE);
        if(rf::ui::MakeButton(&SystemButtonID, SystemButtonStr, rf::ui::FONT_AWESOME, vec2i(0), SystemButtonSize, 0.4f, rf::ui::DECORATION_BORDER))
        {
            SystemShow = !SystemShow;
        }
    rf::ui::EndPanel();

    static uint32 SystemPanelID = 0;
    static vec2i SystemPanelSize(210, 500);
    static vec3i SystemPanelPos(Context->WindowWidth - 50 - SystemPanelSize.x, 100, 0);

    if(SystemShow)
    {
        rf::ui::BeginPanel(&SystemPanelID, "System Info", &SystemPanelPos, &SystemPanelSize, rf::ui::COLOR_PANELBG);
            // Session Pool occupancy
            int CurrHeight = 0;
            real32 ToMiB = 1.f / (real32)MB;
            char OccupancyStr[64];

			static real32 PermanentOccupancy = 0.0f;
			PermanentOccupancy = rf::PoolOccupancy(Memory->PermanentMemPool);
			uint64 permanentUsedSpace = (uint64)(PermanentOccupancy * Memory->PermanentMemPool->Capacity);
            snprintf(OccupancyStr, 64, "permanent stack %.3f / %.2f MiB", permanentUsedSpace*ToMiB, Memory->PermanentMemPool->Capacity*ToMiB);
            rf::ui::MakeText(NULL, OccupancyStr, rf::ui::FONT_DEFAULT, vec2i(0, CurrHeight), rf::ui::COLOR_PANELFG);
            CurrHeight += 16;
            rf::ui::MakeProgressbar(&PermanentOccupancy, 1.f, vec2i(0, CurrHeight), vec2i(300, 10));
            CurrHeight += 16;

			static real32 SessionOccupancy = 0.0f;
			SessionOccupancy = rf::PoolOccupancy(Memory->SessionMemPool);
			uint64 sessionUsedSpace = (uint64)(SessionOccupancy * Memory->SessionMemPool->Capacity);
            snprintf(OccupancyStr, 64, "session stack %.3f / %.2f MiB", sessionUsedSpace*ToMiB, Memory->SessionMemPool->Capacity*ToMiB);
            rf::ui::MakeText(NULL, OccupancyStr, rf::ui::FONT_DEFAULT, vec2i(0, CurrHeight), rf::ui::COLOR_PANELFG);
            CurrHeight += 16;
            rf::ui::MakeProgressbar(&SessionOccupancy, 1.f, vec2i(0, CurrHeight), vec2i(300, 10));
            CurrHeight += 16;

			static real32 ScratchOccupancy = 0.0f;
			ScratchOccupancy = rf::PoolOccupancy(Memory->ScratchMemPool);
			uint64 scratchUsedSpace = (uint64)(ScratchOccupancy * Memory->ScratchMemPool->Capacity);
            snprintf(OccupancyStr, 64, "scratch stack %.3f / %.2f MiB", scratchUsedSpace*ToMiB, Memory->ScratchMemPool->Capacity*ToMiB);
            rf::ui::MakeText(NULL, OccupancyStr, rf::ui::FONT_DEFAULT, vec2i(0, CurrHeight), rf::ui::COLOR_PANELFG);
            CurrHeight += 16;
            rf::ui::MakeProgressbar(&ScratchOccupancy, 1.f, vec2i(0, CurrHeight), vec2i(300, 10));
            CurrHeight += 16;

            static uint32 TmpBut = 0;
            rf::ui::MakeButton(&TmpBut, "a", rf::ui::FONT_DEFAULT, vec2i(0, CurrHeight), vec2i(20));
            CurrHeight += 26;

            static uint32 TmpBut2 = 0;
            rf::ui::MakeButton(&TmpBut2, "Hello", rf::ui::FONT_DEFAULT, vec2i(0, CurrHeight), vec2i(60,20));
            CurrHeight += 26;

            char Str[16];
            snprintf(Str, 16, "%s%s%s", ICON_FA_SEARCH, ICON_FA_GLASS, ICON_FA_SHARE);
            rf::ui::MakeText(NULL, Str, rf::ui::FONT_AWESOME, vec2i(0, 180), rf::ui::COLOR_BORDERBG);
        rf::ui::EndPanel();
    }
}

rf::context_descriptor MakeContextDescriptor(memory *Memory, config *Config, path const ExecutableName)
{
    rf::context_descriptor CtxDesc;
    CtxDesc.SessionPool = Memory->SessionMemPool;
    CtxDesc.ScratchPool = Memory->ScratchMemPool;
    // cpy WinX, WinY, WinW, WinH, VSync, FOV, NearPlane, FarPlane from Config to the Descriptor
    CtxDesc.WindowX = (real32)Config->WindowX;
    CtxDesc.WindowY = (real32)Config->WindowY;
    CtxDesc.WindowWidth = Config->WindowWidth;
    CtxDesc.WindowHeight = Config->WindowHeight;
    CtxDesc.VSync = Config->VSync;
    CtxDesc.FOV = Config->FOV;
    CtxDesc.NearPlane = Config->NearPlane;
    CtxDesc.FarPlane = Config->FarPlane;
    memcpy(CtxDesc.ExecutableName, ExecutableName, sizeof(path));

    return CtxDesc;
}

int RadarMain(int /*argc*/, char ** /*argv*/)
{
    // Init Engine memory
    memory *Memory = InitMemory();

    // Parse Engine config file (or get the default config if inexistent)
    config Config;
    if(!ParseConfig(&Config, "config.json"))
        return 1;

    // Create the RF context
    path ExecutableName;
    snprintf(ExecutableName, MAX_PATH, "Radar Engine %d.%d.%d", RADAR_MAJOR, RADAR_MINOR, RADAR_PATCH);
    rf::context_descriptor CtxDesc = MakeContextDescriptor(Memory, &Config, ExecutableName);
    rf::context *Context = rf::ctx::Init(&CtxDesc);
    LogInfo("");
    LogInfo("%s", ExecutableName);

    if(!Context->IsValid || !Memory->IsValid)
        return 1;

    real64 CurrentTime, LastTime = glfwGetTime();
    real64 TimeCounter = 0.0;
    int const GameRefreshHz = 60;
    real64 const TargetSecondsPerFrame = 1.0 / (real64)GameRefreshHz;

    rf::BindTexture2D(0, 0);
    rf::CheckGLError("Engine Start");

    if(!Tests::Init(Context, &Config))
        return 1;

    int LastMouseX = 0, LastMouseY = 0;

    rf::mesh ScreenQuad = rf::Make2DQuad(Context, vec2i(-1,1), vec2i(1, -1));
    rf::frame_buffer FPBackbuffer = {};

    // TMP TextureViewer UI
    static uint32 TW_ID = 0;
    static real32 TW_ImgScale = 1.0f;
    static vec2f TW_ImgOffset(0.f, 0.f);
    static vec2i TW_Size(310, 330);
    static vec3i TW_Position(Context->WindowWidth - 10 - TW_Size.x, Context->WindowHeight - 10 - TW_Size.y, 0);

    // Game State initialization
    game::state *State = rf::PoolAlloc<game::state>(Memory->PermanentMemPool, 1);
    if(!game::Init(State, &Config))
    {
        LogError("Error initializing Game State.");
        return 1;
    }

    // Subsystems initialization
#if DO_ATMOSPHERE
    atmosphere::Init(State, Context);
#endif
#if DO_WATER
    water::Init(State, Context, State->WaterState);
#endif
#if DO_PLANET
	planet::Init(State, Context);
#endif

    // First time shader loading at the end of the initialization phase
    ReloadShaders(Context);

    while(Context->IsRunning)
    {
        rf::input Input = {};

        CurrentTime = glfwGetTime();
        Input.dTime = CurrentTime - LastTime;

        LastTime = CurrentTime;
        State->EngineTime += Input.dTime;
		State->dTime = Input.dTime;
        TimeCounter += Input.dTime;

        // NOTE - Each frame, clear the Scratch Arena Data
        // TODO - Is this too often ? Maybe let it stay several frames
        rf::PoolClear(Memory->ScratchMemPool);

        rf::ctx::GetFrameInput(Context, &Input);

        if(Context->HasResized)
        {
            // Resize FBO
            DestroyFramebuffer(&FPBackbuffer);
            FPBackbuffer = rf::MakeFramebuffer(1, vec2i(Context->WindowWidth, Context->WindowHeight));
            rf::FramebufferAttachBuffer(&FPBackbuffer, 0, 4, true, true, true); // RGBA16F attachment
            rf::CheckGLError("FramebufferAttach");
        }

        Input.MouseDX = Input.MousePosX - LastMouseX;
        Input.MouseDY = Input.MousePosY - LastMouseY;
        LastMouseX = Input.MousePosX;
        LastMouseY = Input.MousePosY;

        glClearColor(Context->ClearColor.x, Context->ClearColor.y, Context->ClearColor.z, Context->ClearColor.w);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        rf::ui::BeginFrame(&Input);

        game::Update(State, &Input, Context);

        // Local timed stuff
        if(TimeCounter > 0.1)
        {
            TimeCounter = 0.0;
        }

		// Additional termination test with escape key
		if (KEY_PRESSED(Input.Keys[KEY_ESCAPE]))
		{
			Context->IsRunning = false;
		}

        // Shader hot reload key (Shift-F11)
        if(KEY_PRESSED(Input.Keys[KEY_LEFT_SHIFT]) && KEY_RELEASED(Input.Keys[KEY_F11]))
        {
            ReloadShaders(Context);
        }

        // Wireframe toggle key (Shift-F10)
        if(KEY_PRESSED(Input.Keys[KEY_LEFT_SHIFT]) && KEY_RELEASED(Input.Keys[KEY_F10]))
        {
            rf::ctx::SetWireframeMode(Context);
        }

        glBindFramebuffer(GL_FRAMEBUFFER, FPBackbuffer.FBO);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        Tests::Render(State, &Input, Context);

#if DO_ATMOSPHERE
        atmosphere::Render(State, Context);
#endif
#if DO_WATER
        water::Update(State, &Input);
        water::Render(State, 0, 0);
#endif
#if DO_PLANET
		planet::Render(State, Context);
#endif

        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // Toggle wireframe off to draw the UI and the PostProcess pass
        GLenum CurrWireframemode = rf::ctx::SetWireframeMode(Context, GL_FILL);

        glUseProgram(Context->ProgramPostProcess);
        uint32 MipmapLogLoc = glGetUniformLocation(Context->ProgramPostProcess, "MipmapQueryLevel");
        uint32 ResolutionLoc = glGetUniformLocation(Context->ProgramPostProcess, "Resolution");
        rf::SendFloat(MipmapLogLoc, Context->WindowSizeLogLevel);
        rf::SendVec2(ResolutionLoc, vec2f((real32)Context->WindowWidth, (real32)Context->WindowHeight));
        rf::SendVec3(glGetUniformLocation(Context->ProgramPostProcess, "CameraPosition"), vec3f(State->Camera.Position + State->Camera.PositionDecimal));
        rf::BindTexture2D(FPBackbuffer.BufferIDs[0], 0);
        glGenerateMipmap(GL_TEXTURE_2D); // generate mipmap for the color buffer
        rf::CheckGLError("TexBind");

        glBindVertexArray(ScreenQuad.VAO);
        rf::RenderMesh(&ScreenQuad);

        MakeUI(Memory, Context, &Input);

#if 0
		rf::font *FontInfo = rf::ui::GetFont(rf::ui::FONT_AWESOME);
		rf::ui::BeginPanel(&TW_ID, "Texture Viewer", &TW_Position, &TW_Size, rf::ui::COLOR_PANELBG, rf::ui::DECORATION_TITLEBAR | rf::ui::DECORATION_BORDER);
		rf::ui::MakeImage(&TW_ImgScale, atmosphere::TransmittanceTexture/*FPBackbuffer.BufferIDs[0]*/, &TW_ImgOffset, vec2i(300, 300), false);
		rf::ui::EndPanel();
#endif

        rf::ui::Draw();

        rf::ctx::SetWireframeMode(Context, CurrWireframemode);

        glfwSwapBuffers(Context->Window);
    }

    rf::DestroyFramebuffer(&FPBackbuffer);
    Tests::Destroy();

    game::Destroy(State);
    rf::ctx::Destroy(Context);
    DestroyMemory(Memory);
    return 0;
}


text:
<?php

class Billmate_Bankpay_Model_Config extends Mage_Paypal_Model_Config
{
}

redpajama_set_name: RedPajamaGithub


text:
package com.communote.server.api.core.property;

import java.util.Collection;
import java.util.Date;
import java.util.Set;

import com.communote.common.converter.Converter;
import com.communote.server.api.core.common.NotFoundException;
import com.communote.server.api.core.security.AuthorizationException;
import com.communote.server.model.property.BinaryProperty;
import com.communote.server.model.property.StringProperty;
import com.communote.server.model.user.User;

/**
 * This service provides means to create, read, update and remove properties including the generic
 * binary property and the properties which are associated with an object like a note or a user.
 *

 * When accessing properties a filter is applied on the group and key to decide whether the property
 * is accessible. Only properties whose group and key were registered with
 * {@link #addObjectPropertyFilter(PropertyType, String, String)} will be accessible.
 *

 *
 * @author Communote GmbH - http://www.communote.com/
 *
 */
public interface PropertyManagement {
    /** Common key group for internal properties. */
    public static final String KEY_GROUP = "com.communote";

    /**
     * Add a combination of a property key group and property key to the accessible properties of
     * the given property type.
     *
     * @param propertyType
     *            the property type
     * @param keyGroup
     *            the key group of the property
     * @param propertyKey
     *            the key of the property
     */
    void addObjectPropertyFilter(PropertyType propertyType, String keyGroup, String propertyKey);

    /**
     * Get all filtered properties from a given object for the given property type
     *
     * @param propertyType
     *            the property type
     * @param objectId
     *            the object id
     * @return all filtered properties from the object
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     * @throws NotFoundException
     *             in case the object does not exist
     */
    Set<StringPropertyTO> getAllObjectProperties(PropertyType propertyType, Long objectId)
            throws NotFoundException, AuthorizationException;

    /**
     * Get a binary property not bound to any context
     *
     * @param keyGroup
     *            the key group
     * @param key
     *            the key of the property
     * @return the property (or null)
     */
    BinaryProperty getBinaryProperty(String keyGroup, String key);

    /**
     * Get last modification date of a binary property.
     *
     * @param keyGroup
     *            group of the property key
     * @param key
     *            the key of the property
     * @return the last modification date or null if the property does not exist
     */
    Date getBinaryPropertyLastModificationDate(String keyGroup, String key);

    /**
     * Get a global property which is a property with the predefined key group "global"
     *
     * @param propertyType
     *            the type of property
     * @param objectId
     *            the id of the object to get the property for
     * @param key
     *            the key of the property
     * @return the property (or null)
     * @throws NotFoundException
     *             in case there is no object of the given property type and id
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     */
    StringProperty getGlobalObjectProperty(PropertyType propertyType, Long objectId, String key)
            throws NotFoundException, AuthorizationException;

    /**
     * Get an object property
     *
     * @param propertyType
     *            the type of property
     * @param objectId
     *            the ID of the object whose property should be retrieved
     * @param keyGroup
     *            the key group of the property
     * @param key
     *            the key of the property
     * @return the property or null if there is no such property or the key and group combination is
     *         not in the allowed filters
     * @throws NotFoundException
     *             in case there is no object of the given property type and id
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     */
    StringProperty getObjectProperty(PropertyType propertyType, Long objectId, String keyGroup,
            String key) throws NotFoundException, AuthorizationException;

    /**
     * Get an object property. The filter of will not be applied.
     *
     * @param propertyType
     *            the type of property
     * @param objectId
     *            the ID of the object whose property should be retrieved
     * @param keyGroup
     *            the key group of the property
     * @param key
     *            the key of the property
     * @return the property or null if there is no such property
     * @throws NotFoundException
     *             in case there is no object of the given property type and id
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     */
    StringProperty getObjectPropertyUnfiltered(PropertyType propertyType, Long objectId,
            String keyGroup, String key) throws NotFoundException, AuthorizationException;

    /**
     * Return the users that have a specific note property set for a note. The found users are
     * converted into the target type of the provided converter. Deleted users won't be included.
     *
     * @param <T>
     *            the target type of the conversion
     * @param noteId
     *            the ID of the note for which the users that have the property should be returned
     * @param keyGroup
     *            the group key of the searched property
     * @param key
     *            the group of the searched property
     * @param value
     *            the value of the searched property
     * @param converter
     *            the converter to convert the found users
     * @return the found users or an empty list
     * @throws NotFoundException
     *             in case the note does not exist
     * @throws AuthorizationException
     *             in case the current user is not allowed to read the property
     */
    <T> Collection<T> getUsersOfProperty(Long noteId, String keyGroup, String key, String value,
            Converter<User, T> converter) throws NotFoundException, AuthorizationException;

    /**
     * Test whether a binary property exists.
     *
     * @param keyGroup
     *            the key group
     * @param key
     *            the key of the property
     * @return True, if this property exists.
     */
    boolean hasBinaryProperty(String keyGroup, String key);

    /**
     * Test whether the current user has a given property for a note.
     *
     * @param noteId
     *            the ID of the note for which the existence of the property should be checked
     * @param keyGroup
     *            the group key of the searched property
     * @param key
     *            the group of the searched property
     * @param value
     *            the value of the searched property
     * @return true if the user has the property otherwise false
     * @throws AuthorizationException
     *             in case the current user is not allowed to read the property
     * @throws NotFoundException
     *             in case the note does not exist
     */
    boolean hasUserNoteProperty(Long noteId, String keyGroup, String key, String value)
            throws NotFoundException, AuthorizationException;

    /**
     * Remove a binary property.
     *
     * @param keyGroup
     *            The group of the property key.
     * @param propertyKey
     *            The properties key.
     *
     */
    void removeBinaryProperty(String keyGroup, String propertyKey);

    /**
     * Remove a combination of a property key group and property key from the accessible properties
     * of the given type.
     *
     * @param propertyType
     *            the property type
     * @param keyGroup
     *            the key group of the property
     * @param propertyKey
     *            the key of the property
     */
    void removeObjectPropertyFilter(PropertyType propertyType, String keyGroup, String propertyKey);

    /**
     * Set a binary property.
     *
     * @param keyGroup
     *            the key group
     * @param key
     *            the key of the property
     * @param value
     *            the value to set
     * @return the property
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     */
    BinaryProperty setBinaryProperty(String keyGroup, String key, byte[] value)
            throws AuthorizationException;

    /**
     * Set a global property which is a property with the predefined key group will be "global".
     *
     * @param propertyType
     *            the type of property
     * @param objectId
     *            the id of the object to set the property for
     * @param key
     *            the key of the property
     * @param value
     *            the value to set
     * @return the property
     * @throws NotFoundException
     *             in case there is no object of the given property type and id
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     */
    StringProperty setGlobalObjectProperty(PropertyType propertyType, Long objectId, String key,
            String value) throws NotFoundException, AuthorizationException;

    /**
     * Set several properties of an object.
     *
     * @param propertyType
     *            the type of property
     * @param objectId
     *            the id of the object to set the property for
     * @param properties
     *            Set of transfer objects describing the new properties or property values
     * @throws NotFoundException
     *             in case there is no object of the given property type and id
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     */
    void setObjectProperties(PropertyType propertyType, Long objectId,
            Set<StringPropertyTO> properties) throws NotFoundException, AuthorizationException;

    /**
     * Set a new value of a property. If the property does not exist it will be created and assigned
     * to the object. If the value to set is null, an existing property will be removed. In case the
     * property does not exist nothing will happen.
     *
     * @param propertyType
     *            the type of property
     * @param objectId
     *            the id of the object to set the property for
     * @param keyGroup
     *            the key group of the property
     * @param key
     *            the key of the property
     * @param value
     *            the value to set. Can be null to remove an existing property.
     * @return the created or modified property. Can be null if the value was null and the property
     *         did not exist.
     * @throws NotFoundException
     *             in case there is no object of the given property type and id
     * @throws AuthorizationException
     *             in case the user is not allowed to access the properties of the object
     *
     */
    // TODO use generics to return the correct property subtype - but why return the property
    // anyway?
    StringProperty setObjectProperty(PropertyType propertyType, Long objectId, String keyGroup,
            String key, String value) throws NotFoundException, AuthorizationException;

}


text:
import playwright = require('playwright')
import fs = require('fs')

(async () => {
  try { fs.unlinkSync('*-?.png') } catch (e) { }
  for (const browserType of ['chromium', 'firefox', 'webkit']) {
    process.stdout.write(`Testing ${browserType}: `)
    const browser = await playwright[browserType].launch()
    const context = await browser.newContext({ viewport: { width: 1280, height: 1024 } })
    const page = await context.newPage()
    try {
      await page.goto('http://localhost:1939/', 'networkidle')
    }
    catch (err) {
      process.stdout.write(`${err.message}\r\n`)
      process.stdout.write('forgot to `npm start`?')
      process.exit(1)
    }
    try {
      await page.setViewportSize({ width: 1920, height: 1080 })
      const frame = page.frames().find(frame => frame.name() === 'Info')
      await frame.focus('text=Xterm.js')
      await page.waitForTimeout(1000)
      await page.screenshot({ path: `${browserType}-1.png` })
      //await page.keyboard.press('Enter')
      await frame.click('text=/^CONNECT$/')
      await page.waitForTimeout(500)

      await frame.focus('text=cursor')
      await frame.click('text=/^NEW$/')
      await page.waitForTimeout(500)
      await page.screenshot({ path: `${browserType}-2.png` })

      await frame.focus('text=/Shall we begin/')
      await frame.focus('text=/SPACE BAR/')
      await page.waitForTimeout(500)
      await page.screenshot({ path: `${browserType}-3.png` })
      await page.click('div#terminal')
      await page.keyboard.press('Control+D')

      await frame.focus('text=Xterm.js')
      await page.click('div#terminal')
      await page.keyboard.press('Escape')
      await page.focus('text=Hurst')
      await page.setViewportSize({ width: 640, height: 480 })
      await page.screenshot({ path: `${browserType}-4.png` })
    }
    catch (err) {
      process.stdout.write(`${err.message}\r\n`)
    }
    await browser.close()
  }
})()


text:
int delete_called = 0;
int delete_nothrow_called = 0;

void operator delete(void* p) TEST_NOEXCEPT
{
    ++delete_called;
    std::free(p);
}

void operator delete(void* p, const std::nothrow_t&) TEST_NOEXCEPT
{
    ++delete_nothrow_called;
    std::free(p);
}

int main()
{
    int *x = new int(42);
    DoNotOptimize(x);
    assert(0 == delete_called);
    assert(0 == delete_nothrow_called);

    delete x;
    DoNotOptimize(x);
    assert(1 == delete_called);
    assert(0 == delete_nothrow_called);
}


text:
package com.github.sviengine.unittest;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class CapturedPostEffectActivity extends UnitTestBaseActivity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean createWindow() {
		// TODO Auto-generated method stub
		mWindow = new CapturedPostEffectWindow(this);

		if( mWindow == null )
			return false;

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu (Menu menu) {

		menu.add("Change Effect");

		menu.add("Start Capture");
		menu.add("Stop Capture");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected (MenuItem item) {
		mWindow.onOptionsItemSelected(item);
		return true;
	}

}


text:
var _hasOwn = Object.prototype.hasOwnProperty;

var _spreadAttribute = function _spreadAttribute(spread) {
  for (var prop in spread) {
    if (_hasOwn.call(spread, prop)) attr(prop, spread[prop]);
  }
};

var _div$statics = ["key", ""];

function render() {
  var _spread, _div$key;

  _spread = props;
  _div$key = _div$statics[1] = props.key++;
  elementOpenStart("div", _div$key, _div$statics);

  _spreadAttribute(_spread);

  elementOpenEnd("div");
  return elementClose("div");
}


text:
package liquibase.integration.ant;

import liquibase.Contexts;
import liquibase.LabelExpression;
import liquibase.Liquibase;
import liquibase.exception.LiquibaseException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.util.DateUtils;
import org.apache.tools.ant.util.FileUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.ParseException;
import java.util.Date;

/**
 * Ant task for rolling back a database.
 */
public class DatabaseRollbackTask extends AbstractChangeLogBasedTask {
    private Date rollbackDate;
    private String rollbackTag;
    private Integer rollbackCount;
    private String rollbackScript;

    @Override
    public void executeWithLiquibaseClassloader() throws BuildException {
        Writer writer = null;
        Liquibase liquibase = getLiquibase();
        try {
            FileResource outputFile = getOutputFile();
            if(rollbackCount != null) {
                if(outputFile != null) {
                    writer = getOutputFileWriter();
                    liquibase.rollback(rollbackCount, rollbackScript, new Contexts(getContexts()), getLabels(), writer);
                } else {
                    liquibase.rollback(rollbackCount, rollbackScript, new Contexts(getContexts()), getLabels());
                }
            } else if(rollbackTag != null) {
                if(outputFile != null) {
                    writer = getOutputFileWriter();
                    liquibase.rollback(rollbackTag, rollbackScript, new Contexts(getContexts()), getLabels(), writer);
                } else {
                    liquibase.rollback(rollbackTag, rollbackScript, new Contexts(getContexts()), getLabels());
                }
            } else if(rollbackDate != null) {
                if(outputFile != null) {
                    writer = getOutputFileWriter();
                    liquibase.rollback(rollbackDate, rollbackScript, new Contexts(getContexts()), getLabels(), writer);
                } else {
                    liquibase.rollback(rollbackDate, rollbackScript, new Contexts(getContexts()), getLabels());
                }
            } else {
                throw new BuildException("Unable to rollback database. No count, tag, or date set.");
            }
        } catch (LiquibaseException e) {
            throw new BuildException("Unable to rollback database. " + e.toString(), e);
        } catch (UnsupportedEncodingException e) {
            throw new BuildException("Unable to generate rollback SQL. Encoding [" + getOutputEncoding() + "] is not supported.", e);
        } catch (IOException e) {
            throw new BuildException("Unable to generate rollback SQL. Error creating output writer.", e);
        } finally {
            FileUtils.close(writer);
        }
    }

    public Date getRollbackDate() {
        if (rollbackDate == null) {
            return null;
        }
        return new Date(rollbackDate.getTime());
    }

    public void setRollbackDate(String rollbackDateStr) {
        if(rollbackTag != null || rollbackCount != null) {
            throw new BuildException("Unable to rollback database. A tag or count has already been set.");
        }
        try {
             this.rollbackDate = DateUtils.parseIso8601DateTimeOrDate(rollbackDateStr);
        } catch (ParseException e) {
            throw new BuildException("Unable to parse rollback date/time string into a Date object. Please make sure the date or date/time is in ISO 8601 format (yyyy-MM-dd or yyyy-MM-ddTHH:mm:ss).", e);
        }
    }

    public String getRollbackTag() {
        return rollbackTag;
    }

    public void setRollbackTag(String rollbackTag) {
        if(rollbackDate != null || rollbackCount != null) {
            throw new BuildException("Unable to rollback database. A date or count has already been set.");
        }
        this.rollbackTag = rollbackTag;
    }

    public Integer getRollbackCount() {
        return rollbackCount;
    }

    public void setRollbackCount(Integer rollbackCount) {
        if(rollbackDate != null || rollbackTag != null) {
            throw new BuildException("Unable to rollback database. A date or tag has already been set.");
        }
        this.rollbackCount = rollbackCount;
    }

    public String getRollbackScript() {
        return rollbackScript;
    }

    public void setRollbackScript(String rollbackScript) {
        this.rollbackScript = rollbackScript;
    }
}


text:
[//]: # (title: Gradle IntelliJ Plugin – Usage Examples)

<!-- Copyright 2000-2022 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -->

## Usage Examples

Marketplace platform provides the [IntelliJ Platform Explorer](https://jb.gg/ipe) – a search tool for browsing Extension Points inside existing implementations of open-source IntelliJ Platform plugins.

One of its features is the possibility of filtering the plugins by those that utilize [Gradle](https://jb.gg/ipe?buildSystem=gradle) or [Gradle KTS](https://jb.gg/ipe?buildSystem=gradle_kts) build scripts.

As examples of using this plugin, you can also check out the following projects:

- [Erlang plugin](https://github.com/ignatov/intellij-erlang) and its [TeamCity build configuration](https://teamcity.jetbrains.com/project.html?projectId=IntellijIdeaPlugins_Erlang&tab=projectOverview)
- [Rust plugin](https://github.com/intellij-rust/intellij-rust)
    - Uses the Gradle Kotlin DSL
    - Fully written in Kotlin
    - Uses [Grammar-Kit]
- [Perl5 plugin](https://github.com/hurricup/Perl5-IDEA)
- [Bamboo Soy plugin](https://github.com/google/bamboo-soy) and its [Travis configuration file](https://github.com/google/bamboo-soy/blob/master/.travis.yml)
- [AceJump plugin](https://github.com/johnlindquist/AceJump)
    - Uses the Gradle Kotlin DSL
- [EmberJS plugin](https://github.com/Turbo87/intellij-emberjs)
- [Robot plugin](https://github.com/AmailP/robot-plugin)
- [SQLDelight Android Studio Plugin](https://github.com/square/sqldelight/tree/master/sqldelight-idea-plugin)
- [idear plugin](https://github.com/breandan/idear)
    - Uses the Gradle Kotlin DSL
- [SonarLint plugin](https://github.com/SonarSource/sonar-intellij)
- [IdeaVim plugin](https://github.com/JetBrains/ideavim) and its [TeamCity build configuration](https://teamcity.jetbrains.com/project.html?projectId=IdeaVim&guest=1)
- [Adb Idea](https://github.com/pbreault/adb-idea) is configured to build and run against stable, beta or preview (canary) releases of Android Studio
- [Gerrit](https://github.com/uwolfer/gerrit-intellij-plugin) uses Travis CI inclusive automated publishing of releases to GitHub and JetBrains plugin repository (triggered by version tag creation)
- [.ignore](https://github.com/JetBrains/idea-gitignore)
- [Minecraft Development](https://github.com/minecraft-dev/MinecraftDev)
    - Uses the Gradle Kotlin DSL
    - Mixes Java, Kotlin, and Groovy code
    - Uses [Grammar-Kit]
    - Uses a Kotlin version not bundled with IntelliJ IDEA
- [Unity 3D plugin](https://github.com/JetBrains/resharper-unity) for JetBrains Rider
- [AEM Tools plugin](https://github.com/aemtools/aemtools) for Adobe Experience Manager integration
    - Uses the Gradle Kotlin DSL
    - Fully written in Kotlin
    - Uses template language
- [F# plugin](https://github.com/JetBrains/resharper-fsharp/tree/net222/rider-fsharp) for JetBrains Rider
    - Uses the Gradle Kotlin DSL
- [Intellij Rainbow Brackets](https://github.com/izhangzhihao/intellij-rainbow-brackets)
    - Fully written in Kotlin
    - Uses other IntelliJ IDEA plugins as test dependencies
    - Circle CI configuration file & Travis CI configuration file
    - Gradle task to verify plugin compatibility cross IntelliJ Platform versions
    - Auto submit anonymous feedback as GitHub issues
- [Requirements](https://github.com/meanmail-dev/requirements)
    - Uses the Gradle Kotlin DSL
    - Fully written in Kotlin
    - Uses other IntelliJ IDEA plugins as test dependencies
    - Uses [Grammar-Kit]
    - Uses a Kotlin version not bundled with IntelliJ IDEA
- [EduTools](https://github.com/JetBrains/educational-plugin)
    - Uses the Gradle Kotlin DSL
    - Mixes Java and Kotlin code

[Grammar-Kit]: https://github.com/JetBrains/Grammar-Kit


text:
import React from 'react';
import TitleBar from '../titleBar/titleBar';
import BottomBar from '../bottomBar/bottomBar';

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    const localStorage = window.localStorage;
    // 验证用户是否登陆,使用localStorage模拟用户登录状态
    if (!localStorage.userId) {
      location.href = '#/login';
    }
  }
  render() {
    return (
      <div>
        <TitleBar />
        {this.props.children}
        <BottomBar />
      </div>
    );
  }
}


text:
exports.up = function(knex) {
  return Promise.all([
    knex.schema.table('messages', table => {
      table.integer('num_replies').defaultsTo(0);
    }),
  ]);
};

exports.down = function(knex) {
  return Promise.all([
    knex.schema.table('messages', table => {
      table.dropColumn('num_replies');
    }),
  ]);
};


text:
#include "igt_core.h"
#include "igt_kms.h"
#include "drmtest.h"

IGT_TEST_DESCRIPTION("Check the debugfs force connector/edid features work"
		     " correctly.");

#define CHECK_MODE(m, h, w, r) igt_assert(m.hdisplay == h && m.vdisplay == w \
					  && m.vrefresh == r)

igt_main
{
	/* force the VGA output and test that it worked */
	int drm_fd = 0;
	drmModeRes *res;
	drmModeConnector *vga_connector = NULL, *temp;
	igt_display_t display;
	int start_n_modes;

	igt_fixture {
		drm_fd = drm_open_any_master();
		res = drmModeGetResources(drm_fd);

		/* find the vga connector */
		for (int i = 0; i < res->count_connectors; i++) {

			vga_connector = drmModeGetConnector(drm_fd, res->connectors[i]);

			if (vga_connector->connector_type == DRM_MODE_CONNECTOR_VGA)
				break;

			drmModeFreeConnector(vga_connector);

			vga_connector = NULL;
		}

		igt_require(vga_connector);
	}

	igt_subtest("force-connector-state") {
		/* force the connector on and check the reported values */
		kmstest_force_connector(drm_fd, vga_connector, FORCE_CONNECTOR_ON);
		temp = drmModeGetConnector(drm_fd, vga_connector->connector_id);
		igt_assert(temp->connection == DRM_MODE_CONNECTED);
		igt_assert(temp->count_modes > 0);
		drmModeFreeConnector(temp);

		/* attempt to use the display */
		kmstest_set_vt_graphics_mode();
		igt_display_init(&display, drm_fd);
		igt_display_commit(&display);

		/* force the connector off */
		kmstest_force_connector(drm_fd, vga_connector,
					FORCE_CONNECTOR_OFF);
		temp = drmModeGetConnector(drm_fd, vga_connector->connector_id);
		igt_assert(temp->connection == DRM_MODE_DISCONNECTED);
		igt_assert(temp->count_modes == 0);
		drmModeFreeConnector(temp);

		/* check that the previous state is restored */
		kmstest_force_connector(drm_fd, vga_connector,
					FORCE_CONNECTOR_UNSPECIFIED);
		temp = drmModeGetConnector(drm_fd, vga_connector->connector_id);
		igt_assert(temp->connection == vga_connector->connection);
		drmModeFreeConnector(temp);
	}

	igt_subtest("force-edid") {
		kmstest_force_connector(drm_fd, vga_connector,
					FORCE_CONNECTOR_ON);
		temp = drmModeGetConnector(drm_fd, vga_connector->connector_id);
		start_n_modes = temp->count_modes;
		drmModeFreeConnector(temp);

		/* test edid forcing */
		kmstest_force_edid(drm_fd, vga_connector,
				   igt_kms_get_base_edid(), EDID_LENGTH);
		temp = drmModeGetConnector(drm_fd,
					   vga_connector->connector_id);

		CHECK_MODE(temp->modes[0], 1920, 1080, 60);
		CHECK_MODE(temp->modes[1], 1280, 720, 60);
		CHECK_MODE(temp->modes[2], 1024, 768, 60);
		CHECK_MODE(temp->modes[3], 800, 600, 60);
		CHECK_MODE(temp->modes[4], 640, 480, 60);

		drmModeFreeConnector(temp);

		/* remove edid */
		kmstest_force_edid(drm_fd, vga_connector, NULL, 0);
		temp = drmModeGetConnector(drm_fd, vga_connector->connector_id);
		/* the connector should now have the same number of modes that
		 * it started with */
		igt_assert(temp->count_modes == start_n_modes);
		drmModeFreeConnector(temp);

		kmstest_force_connector(drm_fd, vga_connector,
					FORCE_CONNECTOR_UNSPECIFIED);
	}

	igt_fixture {
		drmModeFreeConnector(vga_connector);
	}

	igt_exit();
}


text:
<?php

namespace CM\Bundle\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class AudienciasController extends Controller
{
	/**
     * @Route("/audiencias", name="audiencias")
     * @Security("has_role('ROLE_ADMIN') or has_role('ROLE_AUDIENCE_GENERA')")
     * @Template()
     */
    public function indexAction(Request $request)
    {
        return array();
    }

    /**
     * @Route("AU/generarAudiencia", name="generarAudiencias")
     * @Security("has_role('ROLE_ADMIN') or has_role('ROLE_AUDIENCE_GENERA')")
     */

    public function generarAudienciaAction(Request $request)
    {

    	$fanpages = $request->get('fanpages',null);
    	$canalDeInteraccion = $request->get('canalDeInteraccion');
    	$calificaciones = $request->get('calificaciones',null);
    	$texto = $request->get('texto','');
    	$tags = $request->get('search-tags','');
    	$fechas = explode(' - ',$request->get('daterange',''));
    	$desde = $fechas[0];
    	$hasta = $fechas[1];

    	$audiencia = $this->container->get('cm_service')->getAudiencia($fanpages,$canalDeInteraccion,$calificaciones,$texto,$tags,$desde,$hasta);

    	/////EXPORTA A CSV/////////////////////////////
    	$response = new StreamedResponse();
    	$response->setCallback(
    			function () use ($audiencia) {
    				$handle = fopen('php://output', 'r+');

    				foreach ($audiencia as $row) {
    					fputcsv($handle, $row);
    				}

    				fclose($handle);
    			}
    	);

    	$fileName = "audiencia".date('Y-m-d H-i-s').'.csv';
    	$response->headers->set('Content-Type', 'application/force-download');
    	$response->headers->set('Content-Disposition', 'attachment; filename="'.$fileName.'"');
    	//////////////////////////////////////////////////////////////////7

  		return $response;
//    	return new Response(json_encode($audiencia));
    }

    private function exportarCSV($audiencia) {
    	$response = new StreamedResponse();
    	$response->setCallback(
    			function () use ($results) {
    				$handle = fopen('php://output', 'r+');
    				if(!empty($results)) {
    					fputcsv($handle,
    					array_keys($results[0])
    					);
    				}
    				foreach ($results as $row) {
    					fputcsv($handle, $row);
    				}
    				fclose($handle);
    			}
    	);

    	$fileName = "alumnos_ranking_".date('YmdHis').'.csv';
    	$response->headers->set('Content-Type', 'application/force-download');
    	$response->headers->set('Content-Disposition', 'attachment; filename="'.$fileName.'"');

    	return $response;

    }

}

?>


text:
using System;
using Adventure.Framework.Content;

namespace Adventure
{
    public sealed class Tileset : IDisposable
    {
        public Texture2D TilesetTexture { get; set; }
        public string TilesetName { get; set; }
        public int Columns { get; set; }
        public int TileCount { get; set; }
        public int TextureWidth { get; set; }
        public int TextureHeight { get; set; }
        public int TileWidth { get; set; }
        public int TileHeight { get; set; }
        public TileInstance[] TileInstances;

        public void GenerateTileInstances()
        {
            TileInstances = new TileInstance[TileCount];
            for (int i = 0; i < TileCount; i++)
            {
                TileInstances[i] = new TileInstance(i);
            }
        }

        public void Dispose()
        {
            TilesetTexture.Dispose();
        }
    }

    public class TileInstance
    {
        public int ID;
        public int Index;
        public double Timer;
        public double FrameDelay;

        public int[] TileIDs;

        public int CurrentTileID { get { return TileIDs[Index]; } }
        public bool IsAnimated;

        public TileInstance(int id)
        {
            ID = id;
            Index = 0;
            Timer = 0.0;

            IsAnimated = false;

            TileIDs = new int[1] { id };
        }
        public TileInstance(int id, double frameDelay, params int[] animIDs)
        {
            ID = id;
            Index = 0;
            Timer = 0.0;
            FrameDelay = frameDelay;

            IsAnimated = true;

            TileIDs = animIDs;
        }

        public bool UpdateInstance(double deltaMS)
        {
            if (!IsAnimated)
                return false;

            Timer += deltaMS;
            if (Timer >= FrameDelay)
            {
                Timer = 0.0;
                Index++;

                if (Index >= TileIDs.Length)
                    Index = 0;

                return true;
            }

            return false;
        }
    }
}


text:
namespace viz {
class CompositorFrameMetadata;
}

namespace cc {

// Observes RenderFrameMetadata associated with the submission of a frame.
// LayerTreeHostImpl will create the metadata when submitting a CompositorFrame.
//
// Calls to this will be done from the compositor thread.
class CC_EXPORT RenderFrameMetadataObserver {
 public:
  RenderFrameMetadataObserver() = default;
  RenderFrameMetadataObserver(const RenderFrameMetadataObserver&) = delete;
  virtual ~RenderFrameMetadataObserver() = default;

  RenderFrameMetadataObserver& operator=(const RenderFrameMetadataObserver&) =
      delete;

  // Binds on the current thread. This should only be called from the compositor
  // thread.
  virtual void BindToCurrentThread() = 0;

  // Notification of the RendarFrameMetadata for the frame being submitted to
  // the display compositor.
  virtual void OnRenderFrameSubmission(
      const RenderFrameMetadata& render_frame_metadata,
      viz::CompositorFrameMetadata* compositor_frame_metadata,
      bool force_send) = 0;
};

}  // namespace cc

#endif  // CC_TREES_RENDER_FRAME_METADATA_OBSERVER_H_


text:
#ifndef __MICROPY_INCLUDED_PY_RUNTIME_H__
#define __MICROPY_INCLUDED_PY_RUNTIME_H__

#include "py/mpstate.h"
#include "py/obj.h"

typedef enum {
    MP_VM_RETURN_NORMAL,
    MP_VM_RETURN_YIELD,
    MP_VM_RETURN_EXCEPTION,
} mp_vm_return_kind_t;

typedef enum {
    MP_ARG_BOOL      = 0x001,
    MP_ARG_INT       = 0x002,
    MP_ARG_OBJ       = 0x003,
    MP_ARG_KIND_MASK = 0x0ff,
    MP_ARG_REQUIRED  = 0x100,
    MP_ARG_KW_ONLY   = 0x200,
} mp_arg_flag_t;

typedef union _mp_arg_val_t {
    bool u_bool;
    mp_int_t u_int;
    mp_obj_t u_obj;
} mp_arg_val_t;

typedef struct _mp_arg_t {
    qstr qst;
    mp_uint_t flags;
    mp_arg_val_t defval;
} mp_arg_t;

// defined in objtype.c
extern const qstr mp_unary_op_method_name[];
extern const qstr mp_binary_op_method_name[];

void mp_init(void);
void mp_deinit(void);

void mp_arg_check_num(mp_uint_t n_args, mp_uint_t n_kw, mp_uint_t n_args_min, mp_uint_t n_args_max, bool takes_kw);
void mp_arg_parse_all(mp_uint_t n_pos, const mp_obj_t *pos, mp_map_t *kws, mp_uint_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals);
void mp_arg_parse_all_kw_array(mp_uint_t n_pos, mp_uint_t n_kw, const mp_obj_t *args, mp_uint_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals);
NORETURN void mp_arg_error_terse_mismatch(void);
NORETURN void mp_arg_error_unimpl_kw(void);

static inline mp_obj_dict_t *mp_locals_get(void) { return MP_STATE_CTX(dict_locals); }
static inline void mp_locals_set(mp_obj_dict_t *d) { MP_STATE_CTX(dict_locals) = d; }
static inline mp_obj_dict_t *mp_globals_get(void) { return MP_STATE_CTX(dict_globals); }
static inline void mp_globals_set(mp_obj_dict_t *d) { MP_STATE_CTX(dict_globals) = d; }

mp_obj_t mp_load_name(qstr qst);
mp_obj_t mp_load_global(qstr qst);
mp_obj_t mp_load_build_class(void);
void mp_store_name(qstr qst, mp_obj_t obj);
void mp_store_global(qstr qst, mp_obj_t obj);
void mp_delete_name(qstr qst);
void mp_delete_global(qstr qst);

mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg);
mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs);

mp_obj_t mp_load_const_int(qstr qst);
mp_obj_t mp_load_const_dec(qstr qst);
mp_obj_t mp_load_const_str(qstr qst);
mp_obj_t mp_load_const_bytes(qstr qst);

mp_obj_t mp_call_function_0(mp_obj_t fun);
mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg);
mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2);
mp_obj_t mp_call_function_n_kw(mp_obj_t fun, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args);
mp_obj_t mp_call_method_n_kw(mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args);
mp_obj_t mp_call_method_n_kw_var(bool have_self, mp_uint_t n_args_n_kw, const mp_obj_t *args);

typedef struct _mp_call_args_t {
    mp_obj_t fun;
    mp_uint_t n_args, n_kw, n_alloc;
    mp_obj_t *args;
} mp_call_args_t;

#if MICROPY_STACKLESS
// Takes arguments which are the most general mix of Python arg types, and
// prepares argument array suitable for passing to ->call() method of a
// function object (and mp_call_function_n_kw()).
// (Only needed in stackless mode.)
void mp_call_prepare_args_n_kw_var(bool have_self, mp_uint_t n_args_n_kw, const mp_obj_t *args, mp_call_args_t *out_args);
#endif

void mp_unpack_sequence(mp_obj_t seq, mp_uint_t num, mp_obj_t *items);
void mp_unpack_ex(mp_obj_t seq, mp_uint_t num, mp_obj_t *items);
mp_obj_t mp_store_map(mp_obj_t map, mp_obj_t key, mp_obj_t value);
mp_obj_t mp_load_attr(mp_obj_t base, qstr attr);
void mp_convert_member_lookup(mp_obj_t obj, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest);
void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest);
void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest);
void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t val);

mp_obj_t mp_getiter(mp_obj_t o);
mp_obj_t mp_iternext_allow_raise(mp_obj_t o); // may return MP_OBJ_STOP_ITERATION instead of raising StopIteration()
mp_obj_t mp_iternext(mp_obj_t o); // will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration(...)
mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val);

mp_obj_t mp_make_raise_obj(mp_obj_t o);

mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level);
mp_obj_t mp_import_from(mp_obj_t module, qstr name);
void mp_import_all(mp_obj_t module);

// Raise NotImplementedError with given message
NORETURN void mp_not_implemented(const char *msg);
NORETURN void mp_exc_recursion_depth(void);

// helper functions for native/viper code
mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type);
mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type);
mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, mp_uint_t n_args_kw, const mp_obj_t *args);
void mp_native_raise(mp_obj_t o);

#define mp_sys_path ((mp_obj_t)&MP_STATE_VM(mp_sys_path_obj))
#define mp_sys_argv ((mp_obj_t)&MP_STATE_VM(mp_sys_argv_obj))

#if MICROPY_WARNINGS
void mp_warning(const char *msg, ...);
#else
#define mp_warning(msg, ...)
#endif

#endif // __MICROPY_INCLUDED_PY_RUNTIME_H__


text:
package com.asakusafw.compiler.common;

import java.text.MessageFormat;

/**
 * Naming rule for Asakusa DSL.
 * @since 0.1.0
 * @version 0.2.6
 */
public final class Naming {

    /**
     * Returns the simple name of stage client class.
     * @return the simple name of stage client class
     */
    public static String getClientClass() {
        return "StageClient"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of mapper class.
     * @param inputId input port ID
     * @return the simple name of mapper class
     */
    public static String getMapClass(int inputId) {
        return String.format("%s%d", "StageMapper", inputId); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the simple name of reducer class.
     * @return the simple name of reducer class
     */
    public static String getReduceClass() {
        return "StageReducer"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of combiner class.
     * @return the simple name of combiner class
     */
    public static String getCombineClass() {
        return "StageCombiner"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of map fragment class.
     * @param serialNumber the serial number of the target fragment
     * @return the simple name of the target fragment class
     */
    public static String getMapFragmentClass(int serialNumber) {
        return String.format("%s%d", "MapFragment", serialNumber); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the simple name of reduce fragment class.
     * @param serialNumber the serial number of the target fragment
     * @return the simple name of the target fragment class
     */
    public static String getReduceFragmentClass(int serialNumber) {
        return String.format("%s%d", "ReduceFragment", serialNumber); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the simple name of map output fragment class.
     * @param serialNumber the serial number of the target fragment
     * @return the simple name of the target fragment class
     */
    public static String getMapOutputFragmentClass(int serialNumber) {
        return String.format("%s%d", "MapOutputFragment", serialNumber); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the simple name of combine output fragment class.
     * @param serialNumber the serial number of the target fragment
     * @return the simple name of the target fragment class
     */
    public static String getCombineOutputFragmentClass(int serialNumber) {
        return String.format("%s%d", "CombineOutputFragment", serialNumber); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the simple name of combine fragment class.
     * @param serialNumber the serial number of the target fragment
     * @return the simple name of the target fragment class
     */
    public static String getCombineFragmentClass(int serialNumber) {
        return String.format("%s%d", "CombineFragment", serialNumber); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the simple name of shuffle key class.
     * @return the simple name of the target class
     */
    public static String getShuffleKeyClass() {
        return "ShuffleKey"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of shuffle value class.
     * @return the simple name of the target class
     */
    public static String getShuffleValueClass() {
        return "ShuffleValue"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of partitioner class.
     * @return the simple name of the target class
     */
    public static String getShufflePartitionerClass() {
        return "ShufflePartitioner"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of grouping comparator class.
     * @return the simple name of the target class
     */
    public static String getShuffleGroupingComparatorClass() {
        return "ShuffleGroupingComparator"; //$NON-NLS-1$
    }

    /**
     * Returns the simple name of sort comparator class.
     * @return the simple name of the target class
     */
    public static String getShuffleSortComparatorClass() {
        return "ShuffleSortComparator"; //$NON-NLS-1$
    }

    /**
     * Returns the method name of copying shuffle keys.
     * @return the method name
     */
    public static String getShuffleKeyGroupCopier() {
        return "copyGroupFrom"; //$NON-NLS-1$
    }

    /**
     * The property name of grouping property of shuffle keys.
     * @param elementId the target element ID
     * @param termId the target term ID
     * @return the property name
     */
    public static String getShuffleKeyGroupProperty(int elementId, int termId) {
        return String.format("groupElem%dTerm%d", elementId, termId); //$NON-NLS-1$
    }

    /**
     * The property name of sort property of shuffle keys.
     * @param portId the target port ID
     * @param termId the target term ID
     * @return the property name
     */
    public static String getShuffleKeySortProperty(int portId, int termId) {
        return String.format("sortPort%dTerm%d", portId, termId); //$NON-NLS-1$
    }

    /**
     * The setter method name of shuffle key.
     * @param portId the target port ID
     * @return the method name
     */
    public static String getShuffleKeySetter(int portId) {
        return String.format("setPort%d", portId); //$NON-NLS-1$
    }

    /**
     * Returns the getter method name of shuffle value.
     * @param portId the target port ID
     * @return the method name
     */
    public static String getShuffleValueGetter(int portId) {
        return String.format("getPort%d", portId); //$NON-NLS-1$
    }

    /**
     * The setter method name of shuffle value.
     * @param portId the target port ID
     * @return the method name
     */
    public static String getShuffleValueSetter(int portId) {
        return String.format("setPort%d", portId); //$NON-NLS-1$
    }

    /**
     * Returns the stage name for main phase.
     * @param stageNumber the target stage number
     * @return the stage name
     */
    public static String getStageName(int stageNumber) {
        return String.format("stage%04d", stageNumber); //$NON-NLS-1$
    }

    /**
     * Returns the cleanup stage.
     * @return the stage name
     * @since 0.2.6
     */
    public static String getCleanupStageName() {
        return "cleanup"; //$NON-NLS-1$
    }

    /**
     * Returns the stage name for prologue phase.
     * @param moduleId the corresponding module ID
     * @return the stage name
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public static String getPrologueName(String moduleId) {
        Precondition.checkMustNotBeNull(moduleId, "moduleId"); //$NON-NLS-1$
        return MessageFormat.format("prologue.{0}", moduleId); //$NON-NLS-1$
    }

    /**
     * Returns the stage name for prologue phase.
     * @param moduleId the corresponding module ID
     * @param stageId the stage ID
     * @return the stage name
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public static String getPrologueName(String moduleId, String stageId) {
        Precondition.checkMustNotBeNull(moduleId, "moduleId"); //$NON-NLS-1$
        return MessageFormat.format("prologue.{0}.{1}", moduleId, stageId); //$NON-NLS-1$
    }

    /**
     * Returns the stage name for epilogue phase.
     * @param moduleId the corresponding module ID
     * @return the stage name
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public static String getEpilogueName(String moduleId) {
        Precondition.checkMustNotBeNull(moduleId, "moduleId"); //$NON-NLS-1$
        return MessageFormat.format("epilogue.{0}", moduleId); //$NON-NLS-1$
    }

    /**
     * Returns the stage name for epilogue phase.
     * @param moduleId the corresponding module ID
     * @param stageId the stage ID
     * @return the stage name
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public static String getEpilogueName(String moduleId, String stageId) {
        Precondition.checkMustNotBeNull(moduleId, "moduleId"); //$NON-NLS-1$
        return MessageFormat.format("epilogue.{0}.{1}", moduleId, stageId); //$NON-NLS-1$
    }

    /**
     * Returns the jobflow package file name.
     * @param flowId the target flow ID
     * @return the corresponded package file name
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public static String getJobflowClassPackageName(String flowId) {
        Precondition.checkMustNotBeNull(flowId, "flowId"); //$NON-NLS-1$
        return String.format("jobflow-%s%s", flowId, ".jar"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Returns the jobflow source package file name.
     * @param flowId the target flow ID
     * @return the corresponded package file name
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public static String getJobflowSourceBundleName(String flowId) {
        Precondition.checkMustNotBeNull(flowId, "flowId"); //$NON-NLS-1$
        return String.format("jobflow-%s-sources%s", flowId, ".jar"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    private Naming() {
        throw new AssertionError();
    }
}


text:
"""Virtual environment create mixin."""

from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

class CreateMixin(object):

    """Can create new virtual environments.

    This mixin requires the command mixin.
    """

    def create(self, python=None, system_site=False, always_copy=False):
        """Create a new virtual environment.

        Args:
            python (str): The name or path of a python interpreter to use while
                creating the virtual environment.
            system_site (bool): Whether or not use use the system site packages
                within the virtual environment. Default is False.
            always_copy (bool): Whether or not to force copying instead of
                symlinking in the virtual environment. Default is False.
        """
        command = "virtualenv"
        if python:

            command = "{0} --python={1}".format(command, python)

        if system_site:

            command = "{0} --system-site-packages".format(command)

        if always_copy:

            command = "{0} --always-copy".format(command)

        command = "{0} {1}".format(command, self.path)
        self._execute(command)


text:
package com.byte_games.snake2;

import com.byte_games.snake2.engine.Challenge;
import com.byte_games.snake2.engine.Challenge.LevelType;
import com.byte_games.snake2.engine.SnakeEngine;
import com.byte_games.snake2.engine.SESurfaceView;
import com.byte_games.snake2.engine.Ticker;
import com.byte_games.snake2.engine.GraphicsHelper;
import com.byte_games.snake2.engine.TerrainGen;
import com.byte_games.snake2.engine.GraphicsHelper.*;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class ChallengeModeActivity extends GameActivity {
	private boolean DoneSetup = false;
	private Mode OldMode = Mode.Paused;
	private double Speed = 0.30;
	private List<Location> Snake = new ArrayList<Location>();
	private Location Food;
	private AlertDialog Boxy = null;
	private TextView ScoreText;
	private TextView ProgressText;

	private Challenge myChallenge;
	private int InitialSize;
	private boolean ChangingLevel = false;

	protected ChallengeModeActivity myGameReference = this;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_challenge);
		myContext = getBaseContext();
		ScoreText = (TextView) findViewById(R.id.textScore);
		ProgressText = (TextView) findViewById(R.id.textProgress);

		//Setup challenge object
		Intent receivedIntent = getIntent();
		int NumOfLevels = receivedIntent.getIntExtra("com.byte_games.snake2.Challenge_NumOfLevels", 3);
		int Difficulty = receivedIntent.getIntExtra("com.byte_games.snake2.Challenge_Difficulty", 0);
		myChallenge = new Challenge(NumOfLevels, Difficulty);

		//Setup game variables
		Snake.add(new Location(5, 5));
		Snake.add(new Location(4, 5));
		Snake.add(new Location(3, 5));
		Snake.add(new Location(2, 5));
		Snake.add(new Location(1, 5));
		Food = RanLoc();

		//Configure initial level
		InitialSize = Snake.size();

		//Setup renderer and start draw thread
		myEngine = new SnakeEngine((SESurfaceView) findViewById(R.id.surfaceView), new myDrawer(), EngineTickRate, myContext, this);
		myEngine.myThread.setRunning(true);

		myEngine.Surface.setOnTouchListener(gestureListener);
	}

	@Override
	protected void onDestroy() {
		//Kill thread
		myEngine.myThread.setRunning(false);
		boolean retry = true;
		while(retry) {
			try	{
				myEngine.myThread.join();
				retry = false;
			} catch(Exception e) {
				Log.v("Error killing engine", e.getMessage());
			}
		}
		//Take care of any dialogs that need to be cleaned up
		if (Boxy != null) {
			Boxy.cancel();
		}
		super.onDestroy();
	}

	@Override
	public void finishSetup() {
		if (!DoneSetup) {
			//Setup game GUI
			RelativeLayout BigBox = (RelativeLayout) findViewById(R.id.bigBox);
			RelativeLayout PanelL = (RelativeLayout) findViewById(R.id.panelL);
			RelativeLayout PanelR = (RelativeLayout) findViewById(R.id.panelR);
			RelativeLayout PanelT = (RelativeLayout) findViewById(R.id.panelT);

			Unit = (BigBox.getHeight() - PanelT.getHeight()) / (GraphicsHelper.SizeOfGame.Y + 1);
			float GameX = Unit * (GraphicsHelper.SizeOfGame.X + 1);
			float PanelX = (BigBox.getWidth() - GameX) / 2;

			android.widget.RelativeLayout.LayoutParams LayoutDim = (android.widget.RelativeLayout.LayoutParams) PanelL.getLayoutParams();
			LayoutDim.width = (int) Math.floor(PanelX);
			PanelL.setLayoutParams(LayoutDim);
			LayoutDim = (android.widget.RelativeLayout.LayoutParams) PanelR.getLayoutParams();
			LayoutDim.width = (int) Math.floor(PanelX);
			PanelR.setLayoutParams(LayoutDim);

			//Make background for all the panels
			Bitmap bmpBackground = Bitmap.createBitmap(BigBox.getWidth(), BigBox.getHeight(), Bitmap.Config.ARGB_8888);
			Canvas canvasBackground = new Canvas(bmpBackground);
			canvasBackground.drawColor(Color.parseColor("#505050"));

			Paint[] Rocks = {new Paint(), new Paint(), new Paint()};
			Rocks[0].setColor(Color.parseColor("#393939"));
			Rocks[1].setColor(Color.parseColor("#353535"));
			Rocks[2].setColor(Color.parseColor("#303030"));

			int EndPixX = (int) ((BigBox.getWidth() / Unit) + 1);
			int EndPixY = (int) ((BigBox.getHeight() / Unit) + 1);

			for (int countX = 0; countX <= EndPixX; countX++) {
				for (int countY = 0; countY <= EndPixY; countY++) {
					GraphicsHelper.addPixel(canvasBackground, new Location(countX, countY), Rocks[(int) (Math.random() * ((2) + 1))], Unit);
				}
			}

			android.graphics.drawable.BitmapDrawable Background = new android.graphics.drawable.BitmapDrawable(getResources(), bmpBackground);
			PanelT.setBackground(Background);
			Background.setGravity(Gravity.RIGHT);
			PanelL.setBackground(Background);
			Background.setGravity(Gravity.LEFT);
			PanelR.setBackground(Background);

			HideNavBar();

            showTutorial();

			DoneSetup = true;
		}
	}

	protected Location RanLoc() {
		Location Min = new Location(0, 0);
		Location Max = new Location(GraphicsHelper.SizeOfGame.X, GraphicsHelper.SizeOfGame.Y);
		boolean Good = false;
		Location New = new Location(0, 0);

		while (!Good) {
			New.X = Min.X + (int)(Math.random() * ((Max.X - Min.X) + 1));
			New.Y = Min.Y + (int)(Math.random() * ((Max.Y - Min.Y) + 1));
			Good = true;
			for (Location Point : Snake) {
				if (New.equals(Point)) {
					Good = false;
				}
			}
			for (Location Point : myChallenge.getCurrentLevel().Walls) {
				if (New.equals(Point)) {
					Good = false;
				}
			}
		}
		return New;
	}

	private final static int TH_ShowDeathDialog = 1;
	private final static int TH_UpdateBar = 2;
	private final static int TH_ShowWinDialog = 3;

	private static final class ThreadHelper extends Handler {
		private ChallengeModeActivity myGame;

		ThreadHelper(ChallengeModeActivity myGameReferance) {
			myGame = new WeakReference<ChallengeModeActivity>(myGameReferance).get();
		}

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == TH_ShowDeathDialog) {
				AlertDialog.Builder builder = new AlertDialog.Builder(myGame);
				builder.setMessage((String) msg.obj);
				builder.setCancelable(false);
				builder.setPositiveButton("Retry current level", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						//Return snake to original size
						while (myGame.InitialSize != myGame.Snake.size()) {
							myGame.Snake.remove(myGame.Snake.size() - 1);
						}

						//Reset to dig end state
						myGame.Snake.get(0).CopyTo(myGame.Snake.get(myGame.Snake.size() - 1));
						myGame.ChangingLevel = true;
						myGame.CurrentMode = Mode.Right;
					}
				});
				builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						NavUtils.navigateUpFromSameTask(myGame);
					}
				});
				builder.create();
				builder.show();
			} else if (msg.what == TH_UpdateBar) {
				myGame.ProgressText.setText("Level " + myGame.myChallenge.getCurrentLevelNumber() +  "/" + myGame.myChallenge.Levels.size());

				if (myGame.ChangingLevel) {
					myGame.ScoreText.setText("Digging for level " + myGame.myChallenge.getCurrentLevelNumber() + "...");
					myGame.ProgressText.setText("");
				} else if (myGame.myChallenge.getCurrentLevel().getType() == LevelType.Size) {
					int MiceToGo = myGame.myChallenge.getCurrentLevel().getGoal() - (myGame.Snake.size() - myGame.InitialSize);
					if (MiceToGo == 1) {
						myGame.ScoreText.setText("Eat " + MiceToGo + " mouse");
					} else {
						myGame.ScoreText.setText("Eat " + MiceToGo + " mice");
					}
				} else if (myGame.myChallenge.getCurrentLevel().getType() == LevelType.Movement) {
					myGame.ScoreText.setText("Reach the exit hole");
				}
			} else if (msg.what == TH_ShowWinDialog) {
				AlertDialog.Builder builder = new AlertDialog.Builder(myGame);
				builder.setTitle("Challenge Completed");
                String Difficulty = myGame.getResources().getStringArray(R.array.challengeDifficultyChoices)[myGame.myChallenge.Difficulty];
				builder.setMessage("Deaths: " + myGame.myChallenge.getDeathCount() +
                        "\nDifficulty: " + Difficulty +
                        "\nLength: " + myGame.myChallenge.Levels.size() + " levels");
				builder.setCancelable(false);
				builder.setNegativeButton("Return to menu", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						NavUtils.navigateUpFromSameTask(myGame);
					}
				});
				builder.create();
				builder.show();
			}
		}
	};

	@Override
	public void PauseGame() {
		if (CurrentMode != Mode.Paused) {
			OldMode = CurrentMode;
			CurrentMode = Mode.Paused;

			AlertDialog.Builder builder = new AlertDialog.Builder(myGameReference);
			builder.setMessage("Game paused");
			builder.setCancelable(false);
			builder.setPositiveButton("Resume", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Boxy = null;
					HideNavBar();
                    UnpauseGame(OldMode);
				}
			});
			builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					NavUtils.navigateUpFromSameTask(myGameReference);
					Boxy = null;
				}
			});
			builder.create();
			Boxy = builder.show();
		}
	}

	public class myDrawer extends Ticker {
		Paint color_SnakeHead;
		Paint color_SnakeBody1;
		Paint color_SnakeBody2;
		Paint color_Mouse;
		Paint color_Hole1;
		Paint color_Hole2;
		Paint color_Hole3;
		Paint[] colors_Wall;
		Bitmap bmpBackground = null;
		Bitmap bmpBottomWall = null;
		Bitmap bmpWall = null;
		double SpeedCount = 0;
		boolean DrawExitHole = false;
		ThreadHelper myThreadHelper;

		public myDrawer() {
			myThreadHelper = new ThreadHelper(myGameReference);

			color_SnakeHead = new Paint();
			color_SnakeHead.setColor(Color.rgb(190, 14, 14));
			color_SnakeBody1 = new Paint();
			color_SnakeBody1.setColor(Color.rgb(214, 60, 0));
			color_SnakeBody2 = new Paint();
			color_SnakeBody2.setColor(Color.rgb(214, 80, 0));

			color_Mouse = new Paint();
			color_Mouse.setColor(Color.WHITE);

			color_Hole1 = new Paint();
			color_Hole1.setColor(Color.parseColor("#5A3C1E"));
			color_Hole2 = new Paint();
			color_Hole2.setColor(Color.parseColor("#704B25"));
			color_Hole3 = new Paint();
			color_Hole3.setColor(Color.parseColor("#402912"));

			colors_Wall = new Paint[3];
			colors_Wall[0] = new Paint();
			colors_Wall[0].setColor(Color.parseColor("#393939"));
			colors_Wall[1] = new Paint();
			colors_Wall[1].setColor(Color.parseColor("#353535"));
			colors_Wall[2] = new Paint();
			colors_Wall[2].setColor(Color.parseColor("#303030"));

			myThreadHelper.obtainMessage(TH_UpdateBar).sendToTarget();
		}

		@Override
		public Canvas doTick(Canvas CanvasIn) {
			//Draw Background
			if (bmpBackground == null) {
				//Make Game Background
				bmpBackground = Bitmap.createBitmap(CanvasIn.getWidth(), CanvasIn.getHeight(), Bitmap.Config.ARGB_8888);
				Canvas canvasBackground = new Canvas(bmpBackground);
				canvasBackground.drawColor(Color.parseColor("#005000"));
				TerrainGen myTerrainGen = new TerrainGen(Unit, GraphicsHelper.SizeOfGame, GraphicsHelper.BackgroundBiomeSize, getBaseContext());
				canvasBackground = myTerrainGen.makeGameBackground(canvasBackground);

				//Make Rocky Background
				bmpBottomWall = Bitmap.createBitmap(CanvasIn.getWidth(), (int) (CanvasIn.getHeight() - ((GraphicsHelper.SizeOfGame.Y + 1) * Unit)), Bitmap.Config.ARGB_8888);
				Canvas canvasWallBackground = new Canvas(bmpBottomWall);
				canvasWallBackground.drawColor(Color.parseColor("#505050"));

				Paint[] Rocks = {new Paint(), new Paint(), new Paint()};
				Rocks[0].setColor(Color.parseColor("#393939"));
				Rocks[1].setColor(Color.parseColor("#353535"));
				Rocks[2].setColor(Color.parseColor("#303030"));

				int EndY = (int) (canvasWallBackground.getHeight() / Unit) + 1;
				for (int countX = 0; countX <= GraphicsHelper.SizeOfGame.X; countX++) {
					for (int countY = 0; countY <= EndY; countY++) {
						GraphicsHelper.addPixel(canvasWallBackground, new Location(countX, countY), Rocks[(int) (Math.random() * ((2) + 1))], Unit);
					}
				}

				//Draw walls to bmp
				bmpWall = Bitmap.createBitmap(CanvasIn.getWidth(), CanvasIn.getHeight(), Bitmap.Config.ARGB_8888);
				Canvas canvasWall = new Canvas(bmpWall);
				for (Location Block : myChallenge.getCurrentLevel().Walls) {
					GraphicsHelper.addPixel(canvasWall, Block, colors_Wall[(int) (Math.random() * ((2) + 1))], Unit);
				}
			}
			CanvasIn.drawBitmap(bmpBackground, 0, 0, new Paint());

			//Draw exit hole if needed
			if (DrawExitHole) {
				Location HolePoint = new Location(5, 5);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X + 1, HolePoint.Y), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X - 1, HolePoint.Y), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X, HolePoint.Y + 1), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X, HolePoint.Y - 1), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X + 1, HolePoint.Y + 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X + 1, HolePoint.Y - 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X - 1, HolePoint.Y + 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X - 1, HolePoint.Y - 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(HolePoint.X, HolePoint.Y), color_Hole2, Unit);

				if  (!HolePoint.equals(Snake.get(Snake.size() - 1))) {
					DrawExitHole = false;
				}
			}

			//Code that's stopped on pause
			if (CurrentMode != Mode.Paused) {
				SpeedCount += Speed;

				//Normal game code
				if (!ChangingLevel) {
					if (SpeedCount >= 1) {
						SpeedCount--;

						//Move snake's body parts to catch up with the parts in front
						for (int count = Snake.size() - 1; count > 0; count--) {
							Location SnakePart = Snake.get(count);
							Snake.get(count - 1).CopyTo(SnakePart);
							Snake.set(count, SnakePart);
						}

						//Move snake's head in requested direction
						if (CurrentMode == Mode.Left) {
							Location SnakePart = Snake.get(0);
							SnakePart.X -= 1;
							Snake.set(0, SnakePart);
						} else if (CurrentMode == Mode.Right) {
							Location SnakePart = Snake.get(0);
							SnakePart.X += 1;
							Snake.set(0, SnakePart);
						} else if (CurrentMode == Mode.Up) {
							Location SnakePart = Snake.get(0);
							SnakePart.Y -= 1;
							Snake.set(0, SnakePart);
						} else if (CurrentMode == Mode.Down) {
							Location SnakePart = Snake.get(0);
							SnakePart.Y += 1;
							Snake.set(0, SnakePart);
						}

						//Check for hits
						if (Snake.get(0).equals(Food) && myChallenge.getCurrentLevel().getType() != LevelType.Movement) {
							//Yum!
							Location NewTail = new Location(0, 0);
							Snake.get(Snake.size() - 1).CopyTo(NewTail);
							Snake.add(NewTail);
							Food = RanLoc();

							//Every 6 inches increase speed
							if (Snake.size() % 3 == 0) {
								if (Speed >= .5 && Speed < .65) {
									Speed += .01;
								} else if (Speed < .5) {
									Speed += .02;
								}
							}

							myThreadHelper.obtainMessage(TH_UpdateBar).sendToTarget();
						} else if (Snake.get(0).X <= -1 || Snake.get(0).X >= GraphicsHelper.SizeOfGame.X + 1 || Snake.get(0).Y <= -1 || Snake.get(0).Y >= GraphicsHelper.SizeOfGame.Y + 1) {
							//Edge of game wall hit
							CurrentMode = Mode.Paused;
                            myChallenge.advanceDeathCount();
							myThreadHelper.obtainMessage(TH_ShowDeathDialog, "You ran into a wall").sendToTarget();
						} else {
							for (Location Block : myChallenge.getCurrentLevel().Walls) {
								if (Block.equals(Snake.get(0))) {
									//Wall hit
									CurrentMode = Mode.Paused;
                                    myChallenge.advanceDeathCount();
									myThreadHelper.obtainMessage(TH_ShowDeathDialog, "You ran into a wall").sendToTarget();
                                    break;
								}
							}
                            for (int count = 1; count < Snake.size(); count++) {
                                if (Snake.get(count).equals(Snake.get(0))) {
                                    //Snake hit
                                    CurrentMode = Mode.Paused;
                                    myChallenge.advanceDeathCount();
                                    myThreadHelper.obtainMessage(TH_ShowDeathDialog, "You ran into yourself").sendToTarget();
                                    break;
                                }
                            }
						}

						//Check for level completion
						if (myChallenge.getCurrentLevel().getType() == LevelType.Size) {
							//Check current size against initial size and goal size
							if (Snake.size() - InitialSize == myChallenge.getCurrentLevel().getGoal()) {
								AdvanceChallenge();
							}
						} else if (myChallenge.getCurrentLevel().getType() == LevelType.Movement) {
							//Check location
							if (Snake.get(0).equals(myChallenge.getCurrentLevel().getGoalPoint())) {
								AdvanceChallenge();
							}
						}
					}

				//Level switch code
				} else {
					//Check for dig completion
					if (Snake.get(0).equals(Snake.get(Snake.size() - 1))) {
						//Prep for new level
						for (int count = Snake.size() - 1; count >= 0; count--) {
							Snake.set(count, new Location(5, 5));
						}
						ChangingLevel = false;
						DrawExitHole = true;
						CurrentMode = Mode.Right;
						Food = RanLoc();

						//Make new background
						bmpBackground = Bitmap.createBitmap(CanvasIn.getWidth(), CanvasIn.getHeight(), Bitmap.Config.ARGB_8888);
						Canvas canvasBackground = new Canvas(bmpBackground);
						canvasBackground.drawColor(Color.parseColor("#005000"));
						TerrainGen myTerrainGen = new TerrainGen(Unit, GraphicsHelper.SizeOfGame, GraphicsHelper.BackgroundBiomeSize, getBaseContext());
						canvasBackground = myTerrainGen.makeGameBackground(canvasBackground);

						//Draw new walls to bmp
						bmpWall = Bitmap.createBitmap(CanvasIn.getWidth(), CanvasIn.getHeight(), Bitmap.Config.ARGB_8888);
						Canvas canvasWall = new Canvas(bmpWall);
						for (Location Block : myChallenge.getCurrentLevel().Walls) {
							GraphicsHelper.addPixel(canvasWall, Block, colors_Wall[(int) (Math.random() * ((2) + 1))], Unit);
						}

						//Update UI
						myThreadHelper.obtainMessage(TH_UpdateBar).sendToTarget();
					}

					//Dig hole
					if (SpeedCount >= 1) {
						SpeedCount--;

						//Move snake's body parts to catch up with the parts in front
						for (int count = Snake.size() - 1; count > 0; count--) {
							Location SnakePart = Snake.get(count);
							Snake.get(count - 1).CopyTo(SnakePart);
							Snake.set(count, SnakePart);
						}
					}

					//Draw hole
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X + 1, Snake.get(0).Y), color_Hole1, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X - 1, Snake.get(0).Y), color_Hole1, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X, Snake.get(0).Y + 1), color_Hole1, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X, Snake.get(0).Y - 1), color_Hole1, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X + 1, Snake.get(0).Y + 1), color_Hole2, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X + 1, Snake.get(0).Y - 1), color_Hole2, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X - 1, Snake.get(0).Y + 1), color_Hole2, Unit);
					GraphicsHelper.addPixel(CanvasIn, new Location(Snake.get(0).X - 1, Snake.get(0).Y - 1), color_Hole2, Unit);
				}
			}

			//Draw Mouse
			if (myChallenge.getCurrentLevel().getType() != LevelType.Movement) {
				GraphicsHelper.addPixel(CanvasIn, Food, color_Mouse, Unit);
			}

			//Draw hole
			if (myChallenge.getCurrentLevel().getType() == LevelType.Movement || ChangingLevel) {
				Location Hole;
				if (ChangingLevel) {
					Hole = Snake.get(0);
				} else {
					Hole = myChallenge.getCurrentLevel().getGoalPoint();
				}

				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X + 1, Hole.Y), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X - 1, Hole.Y), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X, Hole.Y + 1), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X, Hole.Y - 1), color_Hole1, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X + 1, Hole.Y + 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X + 1, Hole.Y - 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X - 1, Hole.Y + 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X - 1, Hole.Y - 1), color_Hole2, Unit);
				GraphicsHelper.addPixel(CanvasIn, new Location(Hole.X, Hole.Y), color_Hole3, Unit);
			}

			//Draw Snake
			for (int SnakeDrawCount = Snake.size() - 1; SnakeDrawCount >= 0; SnakeDrawCount--) {
				Location SnakePart = Snake.get(SnakeDrawCount);
				if (SnakeDrawCount == 0 && !ChangingLevel) { //Snake head isn't drawn while digging
					GraphicsHelper.addPixel(CanvasIn, SnakePart, color_SnakeHead, Unit);
				} else if (SnakeDrawCount % 2 == 1) { //it's an odd number
					GraphicsHelper.addPixel(CanvasIn, SnakePart, color_SnakeBody1, Unit);
				} else { //it's an even number
					GraphicsHelper.addPixel(CanvasIn, SnakePart, color_SnakeBody2, Unit);
				}
			}

			CanvasIn.drawBitmap(bmpWall, 0, 0, new Paint());
			CanvasIn.drawBitmap(bmpBottomWall, 0, (GraphicsHelper.SizeOfGame.Y + 1) * Unit, new Paint());
			return CanvasIn;
		}

		private void AdvanceChallenge() {
			boolean DoContinue = myChallenge.advanceLevel();
			Food = new Location(-1, -1);

			if (!DoContinue) {
				//Winner!
				CurrentMode = Mode.Paused;
				myThreadHelper.obtainMessage(TH_ShowWinDialog).sendToTarget();
			} else {
				InitialSize = Snake.size();
				ChangingLevel = true;
			}
			myThreadHelper.obtainMessage(TH_UpdateBar).sendToTarget();
		}
	}
}