text:
// ---------------------------------------------------------------------------------
// <copyright file="DatabaseSettings.cs" company="https://github.com/sant0ro/Yupi">
//   Copyright (c) 2016 Claudio Santoro, TheDoctor
// </copyright>
// <license>
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </license>
// ---------------------------------------------------------------------------------
namespace Yupi.Util.Settings
{
    using System;

    using Config.Net;

    public class DatabaseSettings : SettingsContainer
    {
        private static readonly DatabaseSettings instance = new DatabaseSettings();

        public static DatabaseSettings Instance
        {
            get
            {
                return instance;
            }
        }

        #region Fields

        public readonly Option<string> Host = new Option<string> ("DB.Host", "localhost");
        public readonly Option<string> Name = new Option<string> ("DB.Name", "yupi");
        public readonly Option<string> Password = new Option<string> ("DB.Password", null);
        public readonly Option<DatabaseType> Type = new Option<DatabaseType> ("DB.Type", DatabaseType.SQLite);
        public readonly Option<string> Username = new Option<string> ("DB.Username", "yupi");

        #endregion Fields

        #region Methods

        protected override void OnConfigure(IConfigConfiguration configuration)
        {
            configuration.UseIniFile(Settings.GetPath("database.ini"));
        }

        public string BuildConnectionString()
        {
            switch ((DatabaseType)Type) {
            case DatabaseType.MySQL:
                return "Server = " + Host + "; Database = " + Name + "; Uid = " + Username + ";Pwd = " + Password;
            case DatabaseType.SQLite:
                return "Data Source="+Name+".sqlite;Version=3;";
            default:
                throw new InvalidOperationException ("Unsupported type");
            }
        }

        #endregion Methods
    }
}


text:
package org.apache.jackrabbit.oak.plugins.index.property;

import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexUtils.createIndexDefinition;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.jackrabbit.oak.Oak;
import org.apache.jackrabbit.oak.api.ContentRepository;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.api.ResultRow;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.InitialContent;
import org.apache.jackrabbit.oak.InitialContentHelper;
import org.apache.jackrabbit.oak.query.AbstractQueryTest;
import org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.plugins.memory.PropertyValues;
import org.apache.jackrabbit.oak.spi.security.OpenSecurityProvider;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.jetbrains.annotations.NotNull;
import org.junit.Ignore;
import org.junit.Test;

import com.google.common.collect.ImmutableSet;

/**
 * Tests the query engine using the default index implementation: the
 * {@link PropertyIndexProvider}
 */
public class PropertyIndexQueryTest extends AbstractQueryTest {

    @Override
    protected ContentRepository createRepository() {
        return getOakRepositoryInstance().createContentRepository();
    }

    /**
     * return an instance of {@link Oak} repository ready to be built with
     * {@link Oak#createContentRepository()}.
     *
     * @return
     */
    @NotNull
    Oak getOakRepositoryInstance() {
        return new Oak(new MemoryNodeStore(InitialContentHelper.INITIAL_CONTENT))
            .with(new OpenSecurityProvider())
            .with(new PropertyIndexProvider())
            .with(new PropertyIndexEditorProvider());
    }

    @Test
    public void nativeQuery() throws Exception {
        test("sql2_native.txt");
    }

    @Test
    public void xpath() throws Exception {
        test("xpath.txt");
    }

    @Ignore("OAK-1517")
    @Test
    public void testInvalidNamespace() throws Exception {
        new Oak().with(new InitialContent())
                .with(new OpenSecurityProvider())
                .with(new PropertyIndexEditorProvider())
                .with(new RepositoryInitializer(){

                    @Override
                    public void initialize(@NotNull NodeBuilder builder) {
                        createIndexDefinition(
                                builder.child(INDEX_DEFINITIONS_NAME),
                                "foo",
                                true,
                                false,
                                ImmutableSet.of("illegal:namespaceProperty"), null);
                    }
                })
                .createContentRepository();
        fail("creating an index definition with an illegal namespace should fail.");
    }

    @Test
    public void bindVariableTest() throws Exception {
        Tree tree = root.getTree("/");
        Tree test = tree.addChild("test");
        test.addChild("hello").setProperty("id", "1");
        test.addChild("world").setProperty("id", "2");
        root.commit();

        Map<String, PropertyValue> sv = new HashMap<String, PropertyValue>();
        sv.put("id", PropertyValues.newString("1"));
        Iterator<? extends ResultRow> result;
        result = executeQuery("select * from [nt:base] where id = $id",
                SQL2, sv).getRows().iterator();
        assertTrue(result.hasNext());
        assertEquals("/test/hello", result.next().getPath());

        sv.put("id", PropertyValues.newString("2"));
        result = executeQuery("select * from [nt:base] where id = $id",
                SQL2, sv).getRows().iterator();
        assertTrue(result.hasNext());
        assertEquals("/test/world", result.next().getPath());
    }

    @Test
    public void sql2Index() throws Exception {
        test("sql2_index.txt");
    }

    @Test
    public void sql2Measure() throws Exception {
        test("sql2_measure.txt");
    }

    @Test
    public void sql1() throws Exception {
        test("sql1.txt");
    }

    @Test
    public void sql2() throws Exception {
        test("sql2.txt");
    }

}

redpajama_set_name: RedPajamaGithub


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

namespace Arma3BE.Server.Models
{
    public class AdminList : StateList<Admin>
    {
        public AdminList(ServerMessage message)
            : base(Parse(message.Message))
        {
        }

        private static IEnumerable<Admin> Parse(string text)
        {
            var lines = text.Split(Environment.NewLine.ToCharArray()).ToArray();
            return lines.Select(Admin.Parse).Where(p => p != null).ToList();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hymenomyc. eur. (Upsaliae) 465 (1874)

#### Original name
Agaricus peronatus var. calceolatus Pers.

### Remarks
null


text:
package com.google.inject.grapher;

import com.google.inject.Binding;

/**
 * Creator of graph nodes.
 *
 * @author bojand@google.com (Bojan Djordjevic)
 */
public interface NodeCreator {

  /** Returns nodes for the given dependency graph. */
  Iterable<Node> getNodes(Iterable<Binding<?>> bindings);
}


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

package com.cloudera.impala.catalog;

import com.cloudera.impala.common.Id;
import com.cloudera.impala.common.IdGenerator;

public class TableId extends Id<TableId> {
  // Construction only allowed via an IdGenerator.
  protected TableId(int id) {
    super(id);
  }

  public static IdGenerator<TableId> createGenerator() {
    return new IdGenerator<TableId>() {
      @Override
      public TableId getNextId() { return new TableId(nextId_++); }
      @Override
      public TableId getMaxId() { return new TableId(nextId_ - 1); }
    };
  }

  /**
   * Returns an invalid table id intended for temporary use, e.g., for CTAS.
   */
  public static TableId createInvalidId() { return new TableId(INVALID_ID); }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { VisitorService } from './visitor.service';

describe('VisitorService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [VisitorService]
    });
  });

  it('should be created', inject([VisitorService], (service: VisitorService) => {
    expect(service).toBeTruthy();
  }));
});


text:
<?php
/**
 * @package cms
 * @subpackage model
 */
class SiteTreeFileExtension extends DataExtension {

	private static $belongs_many_many = array(
		'BackLinkTracking' => 'SiteTree'
	);

	public function updateCMSFields(FieldList $fields) {
		$fields->insertAfter(
			ReadonlyField::create(
				'BackLinkCount',
				_t('AssetTableField.BACKLINKCOUNT', 'Used on:'),
				$this->BackLinkTracking()->Count() . ' ' . _t('AssetTableField.PAGES', 'page(s)'))
			->addExtraClass('cms-description-toggle')
			->setDescription($this->BackLinkHTMLList()),
			'LastEdited'
		);
	}

	/**
	 * Generate an HTML list which provides links to where a file is used.
	 *
	 * @return String
	 */
	public function BackLinkHTMLList() {
		$html = '' . _t('SiteTreeFileExtension.BACKLINK_LIST_DESCRIPTION', 'This list shows all pages where the file has been added through a WYSIWYG editor.') . '';
		$html .= '
';

		foreach ($this->BackLinkTracking() as $backLink) {
			$listItem = '
';

			// Add the page link
			$listItem .= 'Link() . '" target="_blank">' . Convert::raw2xml($backLink->MenuTitle) . ' – ';

			// Add the CMS link
			$listItem .= 'CMSEditLink() . '">' . _t('SiteTreeFileExtension.EDIT', 'Edit') . '';

			$html .= $listItem . '
';
		}

		return $html .= '
';
	}

	/**
	 * Extend through {@link updateBackLinkTracking()} in your own {@link Extension}.
	 *
	 * @param string|array $filter
	 * @param string $sort
	 * @param string $join
	 * @param string $limit
	 * @return ManyManyList
	 */
	public function BackLinkTracking($filter = null, $sort = null, $join = null, $limit = null) {
		if($filter !== null || $sort !== null || $join !== null || $limit !== null) {
			Deprecation::notice('4.0', 'The $filter, $sort, $join and $limit parameters for
				SiteTreeFileExtension::BackLinkTracking() have been deprecated.
				Please manipluate the returned list directly.', Deprecation::SCOPE_GLOBAL);
		}

		if(class_exists("Subsite")){
			$rememberSubsiteFilter = Subsite::$disable_subsite_filter;
			Subsite::disable_subsite_filter(true);
		}

		if($filter || $sort || $join || $limit) {
			Deprecation::notice('4.0', 'The $filter, $sort, $join and $limit parameters for
				SiteTreeFileExtension::BackLinkTracking() have been deprecated.
				Please manipluate the returned list directly.', Deprecation::SCOPE_GLOBAL);
		}

		$links = $this->owner->getManyManyComponents('BackLinkTracking');
		if($this->owner->ID) {
			$links = $links
				->where($filter)
				->sort($sort)
				->limit($limit);
		}
		$this->owner->extend('updateBackLinkTracking', $links);

		if(class_exists("Subsite")){
			Subsite::disable_subsite_filter($rememberSubsiteFilter);
		}

		return $links;
	}

	/**
	 * @todo Unnecessary shortcut for AssetTableField, coupled with cms module.
	 *
	 * @return Integer
	 */
	public function BackLinkTrackingCount() {
		$pages = $this->owner->BackLinkTracking();
		if($pages) {
			return $pages->Count();
		} else {
			return 0;
		}
	}

	/**
	 * Updates link tracking.
	 */
	public function onAfterDelete() {
		// We query the explicit ID list, because BackLinkTracking will get modified after the stage
		// site does its thing
		$brokenPageIDs = $this->owner->BackLinkTracking()->column("ID");
		if($brokenPageIDs) {
			$origStage = Versioned::current_stage();

			// This will syncLinkTracking on draft
			Versioned::reading_stage('Stage');
			$brokenPages = DataObject::get('SiteTree')->byIDs($brokenPageIDs);
			foreach($brokenPages as $brokenPage) $brokenPage->write();

			// This will syncLinkTracking on published
			Versioned::reading_stage('Live');
			$liveBrokenPages = DataObject::get('SiteTree')->byIDs($brokenPageIDs);
			foreach($liveBrokenPages as $brokenPage) {
				$brokenPage->write();
			}

			Versioned::reading_stage($origStage);
		}
	}

	/**
	 * Rewrite links to the $old file to now point to the $new file.
	 *
	 * @uses SiteTree->rewriteFileURL()
	 *
	 * @param String $old File path relative to the webroot
	 * @param String $new File path relative to the webroot
	 */
	public function updateLinks($old, $new) {
		if(class_exists('Subsite')) Subsite::disable_subsite_filter(true);

		$pages = $this->owner->BackLinkTracking();

		$summary = "";
		if($pages) {
			foreach($pages as $page) $page->rewriteFileURL($old,$new);
		}

		if(class_exists('Subsite')) Subsite::disable_subsite_filter(false);
	}

}


text:
@interface BSONIdGenerator : NSObject
+ (NSString *)generate;
@end


text:
using Serilog;

namespace SysLog2Seri
{
    public class SysLogService
    {
        public void Start()
        {
            Log.Logger = new LoggerConfiguration()
               .ReadFrom.AppSettings()
               .CreateLogger();

            UdpSysLog.Start();

        }
        public void Stop()
        {
            UdpSysLog.Stop();
            Log.CloseAndFlush();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TerabyteToBits
{
    class TerabyteToBits
    {
        static void Main(string[] args)
        {
            double terabytes = double.Parse(Console.ReadLine());

            double terabyteToBits = 8796093022208;

            double result = terabytes * terabyteToBits;

            Console.WriteLine(result);
        }
    }
}


text:
#include <float.h>
#include <algorithm>
#include "common/common.h"
#include "data/glsl_shaders.h"
#include "maths/camera.h"
#include "maths/formatpacking.h"
#include "maths/matrix.h"
#include "strings/string_utils.h"
#include "gl_driver.h"
#include "gl_replay.h"
#include "gl_resources.h"

#define OPENGL 1
#include "data/glsl/glsl_ubos_cpp.h"

void GLReplay::CreateOverlayProgram(GLuint Program, GLuint Pipeline, GLuint fragShader)
{
  WrappedOpenGL &drv = *m_pDriver;

  ContextPair &ctx = drv.GetCtx();

  // delete the old program if it exists
  if(DebugData.overlayProg != 0)
    drv.glDeleteProgram(DebugData.overlayProg);

  DebugData.overlayProg = drv.glCreateProgram();

  // these are the shaders to attach, and the programs to copy details from
  GLuint shaders[4] = {0};
  GLuint programs[4] = {0};

  // temporary programs created as needed if the original program was created with
  // glCreateShaderProgramv and we don't have a shader to attach
  GLuint tmpShaders[4] = {0};

  // the reflection for the vertex shader, used to copy vertex bindings
  ShaderReflection *vsRefl = NULL;

  if(Program == 0)
  {
    if(Pipeline == 0)
    {
      return;
    }
    else
    {
      ResourceId id = m_pDriver->GetResourceManager()->GetID(ProgramPipeRes(ctx, Pipeline));
      const WrappedOpenGL::PipelineData &pipeDetails = m_pDriver->m_Pipelines[id];

      // fetch the corresponding shaders and programs for each stage
      for(size_t i = 0; i < 4; i++)
      {
        if(pipeDetails.stageShaders[i] != ResourceId())
        {
          programs[i] =
              m_pDriver->GetResourceManager()->GetCurrentResource(pipeDetails.stagePrograms[i]).name;
          shaders[i] =
              m_pDriver->GetResourceManager()->GetCurrentResource(pipeDetails.stageShaders[i]).name;

          if(pipeDetails.stagePrograms[i] == pipeDetails.stageShaders[i])
          {
            const WrappedOpenGL::ProgramData &progDetails =
                m_pDriver->m_Programs[pipeDetails.stagePrograms[i]];

            if(progDetails.shaderProgramUnlinkable)
            {
              const WrappedOpenGL::ShaderData &shadDetails =
                  m_pDriver->m_Shaders[pipeDetails.stageShaders[i]];

              std::vector<const char *> sources;
              sources.reserve(shadDetails.sources.size());

              for(const std::string &s : shadDetails.sources)
                sources.push_back(s.c_str());

              shaders[i] = tmpShaders[i] = drv.glCreateShader(ShaderEnum(i));
              drv.glShaderSource(tmpShaders[i], (GLsizei)sources.size(), sources.data(), NULL);
              drv.glCompileShader(tmpShaders[i]);

              GLint status = 0;
              drv.glGetShaderiv(tmpShaders[i], eGL_COMPILE_STATUS, &status);

              if(status == 0)
              {
                char buffer[1024] = {};
                drv.glGetShaderInfoLog(tmpShaders[i], 1024, NULL, buffer);
                RDCERR("Trying to recreate overlay program, couldn't compile shader:\n%s", buffer);
              }
            }
          }

          if(i == 0)
            vsRefl = GetShader(pipeDetails.stageShaders[i], ShaderEntryPoint());
        }
      }
    }
  }
  else
  {
    const WrappedOpenGL::ProgramData &progDetails =
        m_pDriver->m_Programs[m_pDriver->GetResourceManager()->GetID(ProgramRes(ctx, Program))];

    // fetch any and all non-fragment shader shaders
    for(size_t i = 0; i < 4; i++)
    {
      if(progDetails.stageShaders[i] != ResourceId())
      {
        programs[i] = Program;
        shaders[i] =
            m_pDriver->GetResourceManager()->GetCurrentResource(progDetails.stageShaders[i]).name;

        if(i == 0)
          vsRefl = GetShader(progDetails.stageShaders[0], ShaderEntryPoint());
      }
    }
  }

  // attach the shaders
  for(size_t i = 0; i < 4; i++)
    if(shaders[i])
      drv.glAttachShader(DebugData.overlayProg, shaders[i]);

  drv.glAttachShader(DebugData.overlayProg, fragShader);

  // copy the vertex attribs over from the source program
  if(vsRefl && programs[0])
    CopyProgramAttribBindings(programs[0], DebugData.overlayProg, vsRefl);

  // link the overlay program
  drv.glLinkProgram(DebugData.overlayProg);

  // detach the shaders
  for(size_t i = 0; i < 4; i++)
    if(shaders[i])
      drv.glDetachShader(DebugData.overlayProg, shaders[i]);

  drv.glDetachShader(DebugData.overlayProg, fragShader);

  // delete any temporaries
  for(size_t i = 0; i < 4; i++)
    if(tmpShaders[i])
      drv.glDeleteShader(tmpShaders[i]);

  // check that the link succeeded
  char buffer[1024] = {};
  GLint status = 0;
  drv.glGetProgramiv(DebugData.overlayProg, eGL_LINK_STATUS, &status);
  if(status == 0)
  {
    drv.glGetProgramInfoLog(DebugData.overlayProg, 1024, NULL, buffer);
    RDCERR("Error linking overlay program: %s", buffer);
    return;
  }

  // copy the uniform values over from the source program. This is redundant but harmless if the
  // same program is bound to multiple stages. It's just inefficient
  for(size_t i = 0; i < 4; i++)
    if(programs[i])
      CopyProgramUniforms(programs[i], DebugData.overlayProg);
}

ResourceId GLReplay::RenderOverlay(ResourceId texid, CompType typeHint, DebugOverlay overlay,
                                   uint32_t eventId, const vector<uint32_t> &passEvents)
{
  WrappedOpenGL &drv = *m_pDriver;

  MakeCurrentReplayContext(&m_ReplayCtx);

  GLMarkerRegion renderoverlay(StringFormat::Fmt("RenderOverlay %d", overlay));

  ContextPair &ctx = drv.GetCtx();

  GLRenderState rs;
  rs.FetchState(&drv);

  if(rs.Program.name == 0 && rs.Pipeline.name == 0)
    return ResourceId();

  // use our overlay program that we'll fill up with all the right
  // shaders, then replace the fragment shader with our own.
  drv.glBindProgramPipeline(0);

  if(DebugData.fixedcolFragShader)
    drv.glDeleteShader(DebugData.fixedcolFragShader);
  if(DebugData.quadoverdrawFragShader)
    drv.glDeleteShader(DebugData.quadoverdrawFragShader);

  DebugData.fixedcolFragShader = DebugData.quadoverdrawFragShader = 0;

  ShaderType shaderType;
  int glslVer;

  if(IsGLES)
  {
    shaderType = eShaderGLSLES;

    // default to 100 just in case something is broken
    glslVer = 100;

    // GLES requires that versions *precisely* match, so here we must figure out what version the
    // existing shader was using (we pick the vertex shader for simplicity since by definition it
    // must match any others) and recompile our shaders with that version. We've ensured they are
    // compatible with anything after the minimum version
    ResourceId vs;

    if(rs.Program.name)
      vs = m_pDriver->m_Programs[m_pDriver->GetResourceManager()->GetID(rs.Program)].stageShaders[0];
    else
      vs = m_pDriver->m_Pipelines[m_pDriver->GetResourceManager()->GetID(rs.Pipeline)].stageShaders[0];

    if(vs != ResourceId())
    {
      glslVer = m_pDriver->m_Shaders[vs].version;
      if(glslVer == 0)
        glslVer = 100;
    }
  }
  else
  {
    // Desktop GL is vastly better, it can link any program so we just default to 150
    glslVer = 150;
    shaderType = eShaderGLSL;
  }

  // this is always compatible.
  {
    std::string source =
        GenerateGLSLShader(GetEmbeddedResource(glsl_fixedcol_frag), shaderType, glslVer);
    DebugData.fixedcolFragShader = CreateShader(eGL_FRAGMENT_SHADER, source);
  }

  // this is not supported on GLES
  if(shaderType == eShaderGLSL)
  {
    std::string defines = "";

    if(!HasExt[ARB_derivative_control])
    {
      // dFdx fine functions not available before GLSL 450. Use normal dFdx, which might be coarse,
      // so won't show quad overdraw properly
      defines += "#define dFdxFine dFdx\n\n";
      defines += "#define dFdyFine dFdy\n\n";

      RDCWARN("Quad overdraw requires GLSL 4.50 for dFd(xy)fine, using possibly coarse dFd(xy).");
    }

    DebugData.quadoverdrawFragShader = 0;

    // needs these extensions
    if(HasExt[ARB_gpu_shader5] && HasExt[ARB_shader_image_load_store])
    {
      std::string source =
          GenerateGLSLShader(GetEmbeddedResource(glsl_quadwrite_frag), shaderType, glslVer, defines);
      DebugData.quadoverdrawFragShader = CreateShader(eGL_FRAGMENT_SHADER, source);
    }
  }
  else
  {
    if(overlay == DebugOverlay::QuadOverdrawDraw || overlay == DebugOverlay::QuadOverdrawPass)
      RDCWARN("Quad overdraw not supported on GLES", glslVer);
  }

  // we bind the separable program created for each shader, and copy
  // uniforms and attrib bindings from the 'real' programs, wherever
  // they are.
  CreateOverlayProgram(rs.Program.name, rs.Pipeline.name, DebugData.fixedcolFragShader);
  drv.glUseProgram(DebugData.overlayProg);

  auto &texDetails = m_pDriver->m_Textures[texid];

  GLenum texBindingEnum = eGL_TEXTURE_2D;
  GLenum texQueryEnum = eGL_TEXTURE_BINDING_2D;

  if(texDetails.samples > 1)
  {
    texBindingEnum = eGL_TEXTURE_2D_MULTISAMPLE;
    texQueryEnum = eGL_TEXTURE_BINDING_2D_MULTISAMPLE;
  }

  // resize (or create) the overlay texture and FBO if necessary
  if(DebugData.overlayTexWidth != texDetails.width ||
     DebugData.overlayTexHeight != texDetails.height ||
     DebugData.overlayTexSamples != texDetails.samples)
  {
    if(DebugData.overlayFBO)
    {
      drv.glDeleteFramebuffers(1, &DebugData.overlayFBO);
      drv.glDeleteTextures(1, &DebugData.overlayTex);
    }

    drv.glGenFramebuffers(1, &DebugData.overlayFBO);
    drv.glBindFramebuffer(eGL_FRAMEBUFFER, DebugData.overlayFBO);

    GLuint curTex = 0;
    drv.glGetIntegerv(texQueryEnum, (GLint *)&curTex);

    drv.glGenTextures(1, &DebugData.overlayTex);
    drv.glBindTexture(texBindingEnum, DebugData.overlayTex);

    DebugData.overlayTexWidth = texDetails.width;
    DebugData.overlayTexHeight = texDetails.height;
    DebugData.overlayTexSamples = texDetails.samples;

    if(DebugData.overlayTexSamples > 1)
    {
      drv.glTextureStorage2DMultisampleEXT(DebugData.overlayTex, texBindingEnum, texDetails.samples,
                                           eGL_RGBA16F, texDetails.width, texDetails.height, true);
    }
    else
    {
      GLint internalFormat = eGL_RGBA16F;
      GLenum format = eGL_RGBA;
      GLenum type = eGL_FLOAT;

      if(IsGLES && !HasExt[EXT_color_buffer_float])
      {
        internalFormat = eGL_RGBA8;
        type = eGL_UNSIGNED_BYTE;
      }

      drv.glTextureImage2DEXT(DebugData.overlayTex, texBindingEnum, 0, internalFormat,
                              texDetails.width, texDetails.height, 0, format, type, NULL);
      drv.glTexParameteri(texBindingEnum, eGL_TEXTURE_MAX_LEVEL, 0);
      drv.glTexParameteri(texBindingEnum, eGL_TEXTURE_MIN_FILTER, eGL_NEAREST);
      drv.glTexParameteri(texBindingEnum, eGL_TEXTURE_MAG_FILTER, eGL_NEAREST);
      drv.glTexParameteri(texBindingEnum, eGL_TEXTURE_WRAP_S, eGL_CLAMP_TO_EDGE);
      drv.glTexParameteri(texBindingEnum, eGL_TEXTURE_WRAP_T, eGL_CLAMP_TO_EDGE);
    }
    drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, texBindingEnum,
                               DebugData.overlayTex, 0);

    drv.glBindTexture(texBindingEnum, curTex);
  }

  drv.glBindFramebuffer(eGL_FRAMEBUFFER, DebugData.overlayFBO);

  // disable several tests/allow rendering - some overlays will override
  // these states but commonly we don't want to inherit these states from
  // the program's state.
  drv.glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  drv.glDisable(eGL_BLEND);
  drv.glDisable(eGL_SCISSOR_TEST);
  drv.glDepthMask(GL_FALSE);
  drv.glDisable(eGL_CULL_FACE);
  drv.glDisable(eGL_DEPTH_TEST);
  drv.glDisable(eGL_STENCIL_TEST);
  drv.glStencilMask(0);
  if(!IsGLES)
  {
    drv.glPolygonMode(eGL_FRONT_AND_BACK, eGL_FILL);
    drv.glEnable(eGL_DEPTH_CLAMP);
  }

  if(overlay == DebugOverlay::NaN || overlay == DebugOverlay::Clipping)
  {
    // just need the basic texture
    float black[] = {0.0f, 0.0f, 0.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, black);
  }
  else if(overlay == DebugOverlay::Drawcall)
  {
    float black[] = {0.0f, 0.0f, 0.0f, 0.5f};
    drv.glClearBufferfv(eGL_COLOR, 0, black);

    GLint colLoc = drv.glGetUniformLocation(DebugData.overlayProg, "RENDERDOC_Fixed_Color");
    float colVal[] = {0.8f, 0.1f, 0.8f, 1.0f};
    drv.glProgramUniform4fv(DebugData.overlayProg, colLoc, 1, colVal);

    ReplayLog(eventId, eReplay_OnlyDraw);
  }
  else if(overlay == DebugOverlay::Wireframe)
  {
    float wireCol[] = {200.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, wireCol);

    GLint colLoc = drv.glGetUniformLocation(DebugData.overlayProg, "RENDERDOC_Fixed_Color");
    wireCol[3] = 1.0f;
    drv.glProgramUniform4fv(DebugData.overlayProg, colLoc, 1, wireCol);

    if(!IsGLES)
    {
      // desktop GL is simple
      drv.glPolygonMode(eGL_FRONT_AND_BACK, eGL_LINE);

      ReplayLog(eventId, eReplay_OnlyDraw);
    }
    else
    {
      // GLES is hard. We need to readback the index buffer, convert it to a line list, then draw
      // with that. We can at least use a client-side pointer for the index buffer.
      GLint idxbuf = 0;
      drv.glGetIntegerv(eGL_ELEMENT_ARRAY_BUFFER_BINDING, &idxbuf);

      const DrawcallDescription *draw = m_pDriver->GetDrawcall(eventId);

      std::vector<uint32_t> patchedIndices;

      // readback the index buffer data
      if(idxbuf)
      {
        std::vector<byte> idxs;
        uint32_t offset = draw->indexOffset * draw->indexByteWidth;
        uint32_t length = 1;
        drv.glGetNamedBufferParameterivEXT(idxbuf, eGL_BUFFER_SIZE, (GLint *)&length);

        idxs.resize(length);
        drv.glGetBufferSubData(
            eGL_ELEMENT_ARRAY_BUFFER, offset,
            RDCMIN(GLsizeiptr(length - offset),
                   GLsizeiptr(draw->numIndices) * GLsizeiptr(draw->indexByteWidth)),
            &idxs[0]);

        // unbind the real index buffer
        drv.glBindBuffer(eGL_ELEMENT_ARRAY_BUFFER, 0);

        uint32_t expectedSize = draw->numIndices * draw->indexByteWidth;

        if(idxs.size() < expectedSize)
        {
          RDCERR("Index buffer is as large as expected");
          idxs.resize(expectedSize);
        }

        PatchLineStripIndexBuffer(
            draw, draw->indexByteWidth == 1 ? (uint8_t *)idxs.data() : (uint8_t *)NULL,
            draw->indexByteWidth == 2 ? (uint16_t *)idxs.data() : (uint16_t *)NULL,
            draw->indexByteWidth == 4 ? (uint32_t *)idxs.data() : (uint32_t *)NULL, patchedIndices);
      }
      else
      {
        // generate 'index' list
        std::vector<uint32_t> idxs;
        idxs.resize(draw->numIndices);
        for(uint32_t i = 0; i < draw->numIndices; i++)
          idxs[i] = i;
        PatchLineStripIndexBuffer(draw, NULL, NULL, idxs.data(), patchedIndices);
      }

      GLboolean primRestart = drv.glIsEnabled(eGL_PRIMITIVE_RESTART_FIXED_INDEX);
      drv.glEnable(eGL_PRIMITIVE_RESTART_FIXED_INDEX);

      if(draw->flags & DrawFlags::Instanced)
      {
        if(HasExt[ARB_base_instance])
        {
          drv.glDrawElementsInstancedBaseVertexBaseInstance(
              eGL_LINE_STRIP, (GLsizei)patchedIndices.size(), eGL_UNSIGNED_INT,
              patchedIndices.data(), draw->numInstances, 0, draw->instanceOffset);
        }
        else
        {
          drv.glDrawElementsInstancedBaseVertex(eGL_LINE_STRIP, (GLsizei)patchedIndices.size(),
                                                eGL_UNSIGNED_INT, patchedIndices.data(),
                                                draw->numInstances, 0);
        }
      }
      else
      {
        drv.glDrawElementsBaseVertex(eGL_LINE_STRIP, (GLsizei)patchedIndices.size(),
                                     eGL_UNSIGNED_INT, patchedIndices.data(), 0);
      }

      if(!primRestart)
        drv.glDisable(eGL_PRIMITIVE_RESTART_FIXED_INDEX);

      drv.glBindBuffer(eGL_ELEMENT_ARRAY_BUFFER, idxbuf);
    }
  }
  else if(overlay == DebugOverlay::ViewportScissor)
  {
    float col[] = {0.0f, 0.0f, 0.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, col);

    // don't need to use the existing program at all!
    drv.glUseProgram(DebugData.checkerProg);
    drv.glBindProgramPipeline(0);

    if(HasExt[ARB_viewport_array])
    {
      drv.glDisablei(eGL_SCISSOR_TEST, 0);

      drv.glViewportIndexedf(0, rs.Viewports[0].x, rs.Viewports[0].y, rs.Viewports[0].width,
                             rs.Viewports[0].height);
    }
    else
    {
      drv.glDisable(eGL_SCISSOR_TEST);

      drv.glViewport((GLint)rs.Viewports[0].x, (GLint)rs.Viewports[0].y,
                     (GLsizei)rs.Viewports[0].width, (GLsizei)rs.Viewports[0].height);
    }

    if(HasExt[ARB_draw_buffers_blend])
    {
      drv.glEnablei(eGL_BLEND, 0);

      drv.glBlendFuncSeparatei(0, eGL_SRC_ALPHA, eGL_ONE_MINUS_SRC_ALPHA, eGL_SRC_ALPHA,
                               eGL_ONE_MINUS_SRC_ALPHA);
      drv.glBlendEquationSeparatei(0, eGL_FUNC_ADD, eGL_FUNC_ADD);
    }
    else
    {
      drv.glBlendFuncSeparate(eGL_SRC_ALPHA, eGL_ONE_MINUS_SRC_ALPHA, eGL_SRC_ALPHA,
                              eGL_ONE_MINUS_SRC_ALPHA);
      drv.glBlendEquationSeparate(eGL_FUNC_ADD, eGL_FUNC_ADD);

      drv.glEnable(eGL_BLEND);
    }

    drv.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f);

    drv.glBindBufferBase(eGL_UNIFORM_BUFFER, 0, DebugData.UBOs[0]);
    CheckerboardUBOData *cdata = (CheckerboardUBOData *)drv.glMapBufferRange(
        eGL_UNIFORM_BUFFER, 0, sizeof(CheckerboardUBOData),
        GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

    cdata->BorderWidth = 3;
    cdata->CheckerSquareDimension = 16.0f;

    // set primary/secondary to the same to 'disable' checkerboard
    cdata->PrimaryColor = cdata->SecondaryColor = Vec4f(0.1f, 0.1f, 0.1f, 1.0f);
    cdata->InnerColor = Vec4f(0.2f, 0.2f, 0.9f, 0.7f);

    // set viewport rect
    cdata->RectPosition = Vec2f(rs.Viewports[0].x, rs.Viewports[0].y);
    cdata->RectSize = Vec2f(rs.Viewports[0].width, rs.Viewports[0].height);

    drv.glUnmapBuffer(eGL_UNIFORM_BUFFER);

    drv.glDrawArrays(eGL_TRIANGLE_STRIP, 0, 4);

    if(rs.Scissors[0].enabled)
    {
      Vec4f scissor((float)rs.Scissors[0].x, (float)rs.Scissors[0].y, (float)rs.Scissors[0].width,
                    (float)rs.Scissors[0].height);

      if(HasExt[ARB_viewport_array])
        drv.glViewportIndexedf(0, scissor.x, scissor.y, scissor.z, scissor.w);
      else
        drv.glViewport(rs.Scissors[0].x, rs.Scissors[0].y, rs.Scissors[0].width,
                       rs.Scissors[0].height);

      cdata = (CheckerboardUBOData *)drv.glMapBufferRange(
          eGL_UNIFORM_BUFFER, 0, sizeof(CheckerboardUBOData),
          GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

      cdata->BorderWidth = 3;
      cdata->CheckerSquareDimension = 16.0f;

      // black/white checkered border
      cdata->PrimaryColor = Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
      cdata->SecondaryColor = Vec4f(0.0f, 0.0f, 0.0f, 1.0f);

      // nothing at all inside
      cdata->InnerColor = Vec4f(0.0f, 0.0f, 0.0f, 0.0f);

      cdata->RectPosition = Vec2f(scissor.x, scissor.y);
      cdata->RectSize = Vec2f(scissor.z, scissor.w);

      drv.glUnmapBuffer(eGL_UNIFORM_BUFFER);

      drv.glDrawArrays(eGL_TRIANGLE_STRIP, 0, 4);
    }
  }
  else if(overlay == DebugOverlay::Depth || overlay == DebugOverlay::Stencil)
  {
    float black[] = {0.0f, 0.0f, 0.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, black);

    GLint colLoc = drv.glGetUniformLocation(DebugData.overlayProg, "RENDERDOC_Fixed_Color");
    float red[] = {1.0f, 0.0f, 0.0f, 1.0f};
    drv.glProgramUniform4fv(DebugData.overlayProg, colLoc, 1, red);

    ReplayLog(eventId, eReplay_OnlyDraw);

    GLuint curDepth = 0, curStencil = 0;

    drv.glGetNamedFramebufferAttachmentParameterivEXT(rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT,
                                                      eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                                      (GLint *)&curDepth);
    drv.glGetNamedFramebufferAttachmentParameterivEXT(rs.DrawFBO.name, eGL_STENCIL_ATTACHMENT,
                                                      eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                                      (GLint *)&curStencil);

    GLenum copyBindingEnum = texBindingEnum;
    GLenum copyQueryEnum = texQueryEnum;

    GLuint depthCopy = 0, stencilCopy = 0;

    GLint mip = 0;
    GLint layer = 0;

    // create matching depth for existing FBO
    if(curDepth != 0)
    {
      GLint type = 0;
      drv.glGetNamedFramebufferAttachmentParameterivEXT(
          rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT, eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);

      GLenum fmt;

      if(type != eGL_RENDERBUFFER)
      {
        ResourceId id = m_pDriver->GetResourceManager()->GetID(TextureRes(ctx, curDepth));
        WrappedOpenGL::TextureData &details = m_pDriver->m_Textures[id];

        fmt = details.internalFormat;

        drv.glGetNamedFramebufferAttachmentParameterivEXT(
            rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT, eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &mip);

        if(details.curType == eGL_TEXTURE_CUBE_MAP)
        {
          GLenum face;
          drv.glGetNamedFramebufferAttachmentParameterivEXT(
              rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT,
              eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, (GLint *)&face);

          layer = CubeTargetIndex(face);
        }
      }
      else
      {
        ResourceId id = m_pDriver->GetResourceManager()->GetID(RenderbufferRes(ctx, curDepth));
        WrappedOpenGL::TextureData &details = m_pDriver->m_Textures[id];

        fmt = details.internalFormat;
      }

      if(copyBindingEnum == eGL_TEXTURE_CUBE_MAP)
      {
        copyBindingEnum = eGL_TEXTURE_2D;
        copyQueryEnum = eGL_TEXTURE_BINDING_2D;
      }

      GLuint curTex = 0;
      drv.glGetIntegerv(copyQueryEnum, (GLint *)&curTex);

      drv.glGenTextures(1, &depthCopy);
      drv.glBindTexture(copyBindingEnum, depthCopy);
      if(DebugData.overlayTexSamples > 1)
      {
        drv.glTextureStorage2DMultisampleEXT(depthCopy, copyBindingEnum, DebugData.overlayTexSamples,
                                             fmt, DebugData.overlayTexWidth,
                                             DebugData.overlayTexHeight, true);
      }
      else
      {
        drv.glTextureImage2DEXT(depthCopy, copyBindingEnum, 0, fmt, DebugData.overlayTexWidth,
                                DebugData.overlayTexHeight, 0, GetBaseFormat(fmt), GetDataType(fmt),
                                NULL);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_MAX_LEVEL, 0);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_MIN_FILTER, eGL_NEAREST);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_MAG_FILTER, eGL_NEAREST);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_WRAP_S, eGL_CLAMP_TO_EDGE);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_WRAP_T, eGL_CLAMP_TO_EDGE);
      }

      drv.glBindTexture(copyBindingEnum, curTex);
    }

    // create matching separate stencil if relevant
    if(curStencil != curDepth && curStencil != 0)
    {
      GLint type = 0;
      drv.glGetNamedFramebufferAttachmentParameterivEXT(
          rs.DrawFBO.name, eGL_STENCIL_ATTACHMENT, eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);

      GLenum fmt;

      if(type != eGL_RENDERBUFFER)
      {
        ResourceId id = m_pDriver->GetResourceManager()->GetID(TextureRes(ctx, curDepth));
        WrappedOpenGL::TextureData &details = m_pDriver->m_Textures[id];

        fmt = details.internalFormat;

        if(details.curType == eGL_TEXTURE_CUBE_MAP)
        {
          GLenum face;
          drv.glGetNamedFramebufferAttachmentParameterivEXT(
              rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT,
              eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, (GLint *)&face);

          layer = CubeTargetIndex(face);
        }
      }
      else
      {
        ResourceId id = m_pDriver->GetResourceManager()->GetID(RenderbufferRes(ctx, curDepth));
        WrappedOpenGL::TextureData &details = m_pDriver->m_Textures[id];

        fmt = details.internalFormat;
      }

      GLuint curTex = 0;
      drv.glGetIntegerv(copyQueryEnum, (GLint *)&curTex);

      drv.glGenTextures(1, &stencilCopy);
      drv.glBindTexture(copyBindingEnum, stencilCopy);
      if(DebugData.overlayTexSamples > 1)
      {
        drv.glTextureStorage2DMultisampleEXT(
            stencilCopy, copyBindingEnum, DebugData.overlayTexSamples, fmt,
            DebugData.overlayTexWidth, DebugData.overlayTexHeight, true);
      }
      else
      {
        drv.glTextureImage2DEXT(stencilCopy, copyBindingEnum, 0, fmt, DebugData.overlayTexWidth,
                                DebugData.overlayTexHeight, 0, GetBaseFormat(fmt), GetDataType(fmt),
                                NULL);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_MAX_LEVEL, 0);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_MIN_FILTER, eGL_NEAREST);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_MAG_FILTER, eGL_NEAREST);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_WRAP_S, eGL_CLAMP_TO_EDGE);
        drv.glTexParameteri(copyBindingEnum, eGL_TEXTURE_WRAP_T, eGL_CLAMP_TO_EDGE);
      }

      drv.glBindTexture(copyBindingEnum, curTex);
    }

    // bind depth/stencil to overlay FBO (currently bound to DRAW_FRAMEBUFFER)
    if(curDepth != 0 && curDepth == curStencil)
    {
      if(layer == 0)
        drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, eGL_DEPTH_STENCIL_ATTACHMENT,
                                   eGL_TEXTURE_2D, depthCopy, mip);
      else
        drv.glFramebufferTextureLayer(eGL_DRAW_FRAMEBUFFER, eGL_DEPTH_STENCIL_ATTACHMENT, depthCopy,
                                      mip, layer);
    }
    else if(curDepth != 0)
    {
      if(layer == 0)
        drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, eGL_DEPTH_ATTACHMENT, eGL_TEXTURE_2D,
                                   depthCopy, mip);
      else
        drv.glFramebufferTextureLayer(eGL_DRAW_FRAMEBUFFER, eGL_DEPTH_ATTACHMENT, depthCopy, mip,
                                      layer);
    }
    else if(curStencil != 0)
    {
      if(layer == 0)
        drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, eGL_STENCIL_ATTACHMENT, eGL_TEXTURE_2D,
                                   stencilCopy, mip);
      else
        drv.glFramebufferTextureLayer(eGL_DRAW_FRAMEBUFFER, eGL_STENCIL_ATTACHMENT, stencilCopy,
                                      mip, layer);
    }

    // bind the 'real' fbo to the read framebuffer, so we can blit from it
    drv.glBindFramebuffer(eGL_READ_FRAMEBUFFER, rs.DrawFBO.name);

    float green[] = {0.0f, 1.0f, 0.0f, 1.0f};
    drv.glProgramUniform4fv(DebugData.overlayProg, colLoc, 1, green);

    if(overlay == DebugOverlay::Depth)
    {
      if(rs.Enabled[GLRenderState::eEnabled_DepthTest])
        drv.glEnable(eGL_DEPTH_TEST);
      else
        drv.glDisable(eGL_DEPTH_TEST);

      if(rs.DepthWriteMask)
        drv.glDepthMask(GL_TRUE);
      else
        drv.glDepthMask(GL_FALSE);
    }
    else
    {
      if(rs.Enabled[GLRenderState::eEnabled_StencilTest])
        drv.glEnable(eGL_STENCIL_TEST);
      else
        drv.glDisable(eGL_STENCIL_TEST);

      drv.glStencilMaskSeparate(eGL_FRONT, rs.StencilFront.writemask);
      drv.glStencilMaskSeparate(eGL_BACK, rs.StencilBack.writemask);
    }

    if(rs.Enabled[GLRenderState::eEnabled_CullFace])
      drv.glEnable(eGL_CULL_FACE);
    if(!IsGLES && !rs.Enabled[GLRenderState::eEnabled_DepthClamp])
      drv.glDisable(eGL_DEPTH_CLAMP);

    // get latest depth/stencil from read FBO (existing FBO) into draw FBO (overlay FBO)
    SafeBlitFramebuffer(0, 0, DebugData.overlayTexWidth, DebugData.overlayTexHeight, 0, 0,
                        DebugData.overlayTexWidth, DebugData.overlayTexHeight,
                        GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, eGL_NEAREST);

    ReplayLog(eventId, eReplay_OnlyDraw);

    // unset depth/stencil textures from overlay FBO and delete temp depth/stencil
    if(curDepth != 0 && curDepth == curStencil)
      drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, eGL_DEPTH_STENCIL_ATTACHMENT, eGL_TEXTURE_2D,
                                 0, 0);
    else if(curDepth != 0)
      drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, eGL_DEPTH_ATTACHMENT, eGL_TEXTURE_2D, 0, 0);
    else if(curStencil != 0)
      drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, eGL_STENCIL_ATTACHMENT, eGL_TEXTURE_2D, 0, 0);
    if(depthCopy != 0)
      drv.glDeleteTextures(1, &depthCopy);
    if(stencilCopy != 0)
      drv.glDeleteTextures(1, &stencilCopy);
  }
  else if(overlay == DebugOverlay::BackfaceCull)
  {
    float col[] = {0.0f, 0.0f, 0.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, col);

    col[0] = 1.0f;
    col[3] = 1.0f;

    GLint colLoc = drv.glGetUniformLocation(DebugData.overlayProg, "RENDERDOC_Fixed_Color");
    drv.glProgramUniform4fv(DebugData.overlayProg, colLoc, 1, col);

    ReplayLog(eventId, eReplay_OnlyDraw);

    // only enable cull face if it was enabled originally (otherwise
    // we just render green over the exact same area, so it shows up "passing")
    if(rs.Enabled[GLRenderState::eEnabled_CullFace])
      drv.glEnable(eGL_CULL_FACE);

    col[0] = 0.0f;
    col[1] = 1.0f;

    drv.glProgramUniform4fv(DebugData.overlayProg, colLoc, 1, col);

    ReplayLog(eventId, eReplay_OnlyDraw);
  }
  else if(overlay == DebugOverlay::ClearBeforeDraw || overlay == DebugOverlay::ClearBeforePass)
  {
    float col[] = {0.0f, 0.0f, 0.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, col);

    vector<uint32_t> events = passEvents;

    if(overlay == DebugOverlay::ClearBeforeDraw)
      events.clear();

    events.push_back(eventId);

    if(!events.empty())
    {
      if(overlay == DebugOverlay::ClearBeforePass)
      {
        m_pDriver->ReplayLog(0, events[0], eReplay_WithoutDraw);
      }
      else
      {
        // if we don't replay the real state, restore what we've changed
        rs.ApplyState(&drv);
      }

      float black[] = {0.0f, 0.0f, 0.0f, 0.0f};
      for(int i = 0; i < 8; i++)
        drv.glClearBufferfv(eGL_COLOR, i, black);

      for(size_t i = 0; i < events.size(); i++)
      {
        m_pDriver->ReplayLog(events[i], events[i], eReplay_OnlyDraw);

        if(overlay == DebugOverlay::ClearBeforePass && i + 1 < events.size())
          m_pDriver->ReplayLog(events[i] + 1, events[i + 1], eReplay_WithoutDraw);
      }
    }
  }
  else if(overlay == DebugOverlay::TriangleSizeDraw || overlay == DebugOverlay::TriangleSizePass)
  {
    SCOPED_TIMER("Triangle Size");

    float black[] = {0.0f, 0.0f, 0.0f, 0.0f};
    drv.glClearBufferfv(eGL_COLOR, 0, black);

    MeshUBOData uboParams = {};
    uboParams.homogenousInput = 1;
    uboParams.invProj = Matrix4f::Identity();
    uboParams.mvp = Matrix4f::Identity();

    drv.glBindBuffer(eGL_COPY_WRITE_BUFFER, DebugData.UBOs[0]);

    MeshUBOData *uboptr =
        (MeshUBOData *)drv.glMapBufferRange(eGL_COPY_WRITE_BUFFER, 0, sizeof(MeshUBOData),
                                            GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
    *uboptr = uboParams;
    drv.glUnmapBuffer(eGL_COPY_WRITE_BUFFER);

    drv.glBindBuffer(eGL_COPY_WRITE_BUFFER, DebugData.UBOs[2]);
    Vec4f *v = (Vec4f *)drv.glMapBufferRange(eGL_COPY_WRITE_BUFFER, 0, sizeof(Vec4f),
                                             GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
    *v = Vec4f(rs.Viewports[0].width, rs.Viewports[0].height);
    drv.glUnmapBuffer(eGL_COPY_WRITE_BUFFER);

    vector<uint32_t> events = passEvents;

    if(overlay == DebugOverlay::TriangleSizeDraw)
      events.clear();

    events.push_back(eventId);

    if(!events.empty() && DebugData.trisizeProg)
    {
      if(overlay == DebugOverlay::TriangleSizePass)
        ReplayLog(events[0], eReplay_WithoutDraw);
      else
        rs.ApplyState(m_pDriver);

      // this all happens on the replay context so we need a temp FBO/VAO
      GLuint overlayFBO = 0, tempVAO = 0;
      drv.glGenFramebuffers(1, &overlayFBO);
      drv.glGenVertexArrays(1, &tempVAO);

      for(size_t i = 0; i < events.size(); i++)
      {
        GLboolean blending = GL_FALSE;
        GLint depthwritemask = 1;
        GLint stencilfmask = 0xff, stencilbmask = 0xff;
        GLuint drawFBO = 0, prevVAO = 0;
        struct UBO
        {
          GLuint buf;
          GLint64 offs;
          GLint64 size;
        } ubos[3];

        // save the state we're going to mess with
        {
          drv.glGetIntegerv(eGL_DEPTH_WRITEMASK, &depthwritemask);
          drv.glGetIntegerv(eGL_STENCIL_WRITEMASK, &stencilfmask);
          drv.glGetIntegerv(eGL_STENCIL_BACK_WRITEMASK, &stencilbmask);

          drv.glGetIntegerv(eGL_DRAW_FRAMEBUFFER_BINDING, (GLint *)&drawFBO);
          drv.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO);

          blending = drv.glIsEnabled(eGL_BLEND);

          for(uint32_t u = 0; u < 3; u++)
          {
            drv.glGetIntegeri_v(eGL_UNIFORM_BUFFER_BINDING, u, (GLint *)&ubos[u].buf);
            drv.glGetInteger64i_v(eGL_UNIFORM_BUFFER_START, u, (GLint64 *)&ubos[u].offs);
            drv.glGetInteger64i_v(eGL_UNIFORM_BUFFER_SIZE, u, (GLint64 *)&ubos[u].size);
          }
        }

        // disable depth and stencil writes
        drv.glDepthMask(GL_FALSE);
        drv.glStencilMask(GL_FALSE);

        // disable blending
        drv.glDisable(eGL_BLEND);

        // bind our UBOs
        drv.glBindBufferBase(eGL_UNIFORM_BUFFER, 0, DebugData.UBOs[0]);
        drv.glBindBufferBase(eGL_UNIFORM_BUFFER, 2, DebugData.UBOs[2]);

        GLenum att = eGL_DEPTH_ATTACHMENT;
        GLuint depthObj = 0, stencilObj = 0;
        GLint type = 0, level = 0, layered = 0, layer = 0;

        // do we have a stencil object?
        drv.glGetNamedFramebufferAttachmentParameterivEXT(drawFBO, eGL_STENCIL_ATTACHMENT,
                                                          eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                                          (GLint *)&stencilObj);

        // fetch the details of the 'real' depth attachment
        drv.glGetNamedFramebufferAttachmentParameterivEXT(
            drawFBO, att, eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, (GLint *)&depthObj);
        drv.glGetNamedFramebufferAttachmentParameterivEXT(
            drawFBO, att, eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);

        if(depthObj && stencilObj)
        {
          att = eGL_DEPTH_STENCIL_ATTACHMENT;
        }
        else if(depthObj == 0 && stencilObj)
        {
          att = eGL_STENCIL_ATTACHMENT;
          depthObj = stencilObj;
        }

        if(depthObj && type != eGL_RENDERBUFFER)
        {
          drv.glGetNamedFramebufferAttachmentParameterivEXT(
              drawFBO, att, eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
          drv.glGetNamedFramebufferAttachmentParameterivEXT(
              drawFBO, att, eGL_FRAMEBUFFER_ATTACHMENT_LAYERED, &layered);

          layered = (layered != 0);

          layer = 0;
          if(layered == 0)
            drv.glGetNamedFramebufferAttachmentParameterivEXT(
                drawFBO, att, eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, &layer);

          ResourceId id = m_pDriver->GetResourceManager()->GetID(TextureRes(ctx, depthObj));
          WrappedOpenGL::TextureData &details = m_pDriver->m_Textures[id];

          if(details.curType == eGL_TEXTURE_CUBE_MAP)
          {
            GLenum face;
            drv.glGetNamedFramebufferAttachmentParameterivEXT(
                drawFBO, att, eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, (GLint *)&face);

            layer = CubeTargetIndex(face);
          }
        }

        // bind our FBO
        drv.glBindFramebuffer(eGL_DRAW_FRAMEBUFFER, overlayFBO);
        drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, texBindingEnum,
                                   DebugData.overlayTex, 0);

        // now apply the depth texture binding
        if(depthObj)
        {
          if(type == eGL_RENDERBUFFER)
          {
            drv.glNamedFramebufferRenderbufferEXT(overlayFBO, att, eGL_RENDERBUFFER, depthObj);
          }
          else
          {
            if(!layered)
            {
              // we use old-style non-DSA for this because binding cubemap faces with EXT_dsa
              // is completely messed up and broken

              // if obj is a cubemap use face-specific targets
              ResourceId id = m_pDriver->GetResourceManager()->GetID(TextureRes(ctx, depthObj));
              WrappedOpenGL::TextureData &details = m_pDriver->m_Textures[id];

              if(details.curType == eGL_TEXTURE_CUBE_MAP)
              {
                GLenum faces[] = {
                    eGL_TEXTURE_CUBE_MAP_POSITIVE_X, eGL_TEXTURE_CUBE_MAP_NEGATIVE_X,
                    eGL_TEXTURE_CUBE_MAP_POSITIVE_Y, eGL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
                    eGL_TEXTURE_CUBE_MAP_POSITIVE_Z, eGL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
                };

                if(layer < 6)
                {
                  drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, att, faces[layer], depthObj,
                                             level);
                }
                else
                {
                  RDCWARN(
                      "Invalid layer %u used to bind cubemap to framebuffer. Binding POSITIVE_X");
                  drv.glFramebufferTexture2D(eGL_DRAW_FRAMEBUFFER, att, faces[0], depthObj, level);
                }
              }
              else if(details.curType == eGL_TEXTURE_CUBE_MAP_ARRAY ||
                      details.curType == eGL_TEXTURE_1D_ARRAY ||
                      details.curType == eGL_TEXTURE_2D_ARRAY)
              {
                drv.glFramebufferTextureLayer(eGL_DRAW_FRAMEBUFFER, att, depthObj, level, layer);
              }
              else
              {
                RDCASSERT(layer == 0);
                drv.glNamedFramebufferTextureEXT(overlayFBO, att, depthObj, level);
              }
            }
            else
            {
              drv.glNamedFramebufferTextureEXT(overlayFBO, att, depthObj, level);
            }
          }
        }

        GLuint prog = 0, pipe = 0;
        drv.glGetIntegerv(eGL_CURRENT_PROGRAM, (GLint *)&prog);
        drv.glGetIntegerv(eGL_PROGRAM_PIPELINE_BINDING, (GLint *)&pipe);

        drv.glUseProgram(DebugData.trisizeProg);
        drv.glBindProgramPipeline(0);

        const DrawcallDescription *draw = m_pDriver->GetDrawcall(events[i]);

        for(uint32_t inst = 0; draw && inst < RDCMAX(1U, draw->numInstances); inst++)
        {
          MeshFormat postvs = GetPostVSBuffers(events[i], inst, 0, MeshDataStage::GSOut);
          if(postvs.vertexResourceId == ResourceId())
            postvs = GetPostVSBuffers(events[i], inst, 0, MeshDataStage::VSOut);

          if(postvs.vertexResourceId != ResourceId())
          {
            GLenum topo = MakeGLPrimitiveTopology(postvs.topology);

            drv.glBindVertexArray(tempVAO);

            {
              if(postvs.format.Special())
              {
                if(postvs.format.type == ResourceFormatType::R10G10B10A2)
                {
                  if(postvs.format.compType == CompType::UInt)
                    drv.glVertexAttribIFormat(0, 4, eGL_UNSIGNED_INT_2_10_10_10_REV, 0);
                  if(postvs.format.compType == CompType::SInt)
                    drv.glVertexAttribIFormat(0, 4, eGL_INT_2_10_10_10_REV, 0);
                }
                else if(postvs.format.type == ResourceFormatType::R11G11B10)
                {
                  drv.glVertexAttribFormat(0, 4, eGL_UNSIGNED_INT_10F_11F_11F_REV, GL_FALSE, 0);
                }
                else
                {
                  RDCWARN("Unsupported vertex attribute format: %x", postvs.format.type);
                }
              }
              else if(postvs.format.compType == CompType::Float ||
                      postvs.format.compType == CompType::UNorm ||
                      postvs.format.compType == CompType::SNorm)
              {
                GLenum fmttype = eGL_UNSIGNED_INT;

                if(postvs.format.compByteWidth == 4)
                {
                  if(postvs.format.compType == CompType::Float)
                    fmttype = eGL_FLOAT;
                  else if(postvs.format.compType == CompType::UNorm)
                    fmttype = eGL_UNSIGNED_INT;
                  else if(postvs.format.compType == CompType::SNorm)
                    fmttype = eGL_INT;
                }
                else if(postvs.format.compByteWidth == 2)
                {
                  if(postvs.format.compType == CompType::Float)
                    fmttype = eGL_HALF_FLOAT;
                  else if(postvs.format.compType == CompType::UNorm)
                    fmttype = eGL_UNSIGNED_SHORT;
                  else if(postvs.format.compType == CompType::SNorm)
                    fmttype = eGL_SHORT;
                }
                else if(postvs.format.compByteWidth == 1)
                {
                  if(postvs.format.compType == CompType::UNorm)
                    fmttype = eGL_UNSIGNED_BYTE;
                  else if(postvs.format.compType == CompType::SNorm)
                    fmttype = eGL_BYTE;
                }

                drv.glVertexAttribFormat(0, postvs.format.compCount, fmttype,
                                         postvs.format.compType != CompType::Float, 0);
              }
              else if(postvs.format.compType == CompType::UInt ||
                      postvs.format.compType == CompType::SInt)
              {
                GLenum fmttype = eGL_UNSIGNED_INT;

                if(postvs.format.compByteWidth == 4)
                {
                  if(postvs.format.compType == CompType::UInt)
                    fmttype = eGL_UNSIGNED_INT;
                  else if(postvs.format.compType == CompType::SInt)
                    fmttype = eGL_INT;
                }
                else if(postvs.format.compByteWidth == 2)
                {
                  if(postvs.format.compType == CompType::UInt)
                    fmttype = eGL_UNSIGNED_SHORT;
                  else if(postvs.format.compType == CompType::SInt)
                    fmttype = eGL_SHORT;
                }
                else if(postvs.format.compByteWidth == 1)
                {
                  if(postvs.format.compType == CompType::UInt)
                    fmttype = eGL_UNSIGNED_BYTE;
                  else if(postvs.format.compType == CompType::SInt)
                    fmttype = eGL_BYTE;
                }

                drv.glVertexAttribIFormat(0, postvs.format.compCount, fmttype, 0);
              }
              else if(postvs.format.compType == CompType::Double)
              {
                drv.glVertexAttribLFormat(0, postvs.format.compCount, eGL_DOUBLE, 0);
              }

              GLuint vb =
                  m_pDriver->GetResourceManager()->GetCurrentResource(postvs.vertexResourceId).name;
              drv.glBindVertexBuffer(0, vb, (GLintptr)postvs.vertexByteOffset,
                                     postvs.vertexByteStride);
            }

            drv.glEnableVertexAttribArray(0);
            drv.glDisableVertexAttribArray(1);

            if(postvs.indexByteStride)
            {
              GLenum idxtype = eGL_UNSIGNED_BYTE;
              if(postvs.indexByteStride == 2)
                idxtype = eGL_UNSIGNED_SHORT;
              else if(postvs.indexByteStride == 4)
                idxtype = eGL_UNSIGNED_INT;

              GLuint ib =
                  m_pDriver->GetResourceManager()->GetCurrentResource(postvs.indexResourceId).name;
              drv.glBindBuffer(eGL_ELEMENT_ARRAY_BUFFER, ib);
              drv.glDrawElementsBaseVertex(topo, postvs.numIndices, idxtype,
                                           (const void *)uintptr_t(postvs.indexByteOffset),
                                           postvs.baseVertex);
            }
            else
            {
              drv.glDrawArrays(topo, 0, postvs.numIndices);
            }
          }
        }

        // pop the state that we messed with
        {
          drv.glBindProgramPipeline(pipe);
          drv.glUseProgram(prog);

          if(blending)
            drv.glEnable(eGL_BLEND);
          else
            drv.glDisable(eGL_BLEND);

          // restore the previous FBO/VAO
          drv.glBindFramebuffer(eGL_DRAW_FRAMEBUFFER, drawFBO);
          drv.glBindVertexArray(prevVAO);

          for(uint32_t u = 0; u < 3; u++)
          {
            if(ubos[u].buf == 0 || (ubos[u].offs == 0 && ubos[u].size == 0))
              drv.glBindBufferBase(eGL_UNIFORM_BUFFER, u, ubos[u].buf);
            else
              drv.glBindBufferRange(eGL_UNIFORM_BUFFER, u, ubos[u].buf, (GLintptr)ubos[u].offs,
                                    (GLsizeiptr)ubos[u].size);
          }

          drv.glDepthMask(depthwritemask ? GL_TRUE : GL_FALSE);
          drv.glStencilMaskSeparate(eGL_FRONT, (GLuint)stencilfmask);
          drv.glStencilMaskSeparate(eGL_BACK, (GLuint)stencilbmask);
        }

        if(overlay == DebugOverlay::TriangleSizePass)
        {
          m_pDriver->ReplayLog(0, events[i], eReplay_OnlyDraw);

          if(i + 1 < events.size())
            m_pDriver->ReplayLog(events[i] + 1, events[i + 1], eReplay_WithoutDraw);
        }
      }

      drv.glDeleteFramebuffers(1, &overlayFBO);
      drv.glDeleteVertexArrays(1, &tempVAO);

      if(overlay == DebugOverlay::TriangleSizePass)
        ReplayLog(eventId, eReplay_WithoutDraw);
    }
  }
  else if(overlay == DebugOverlay::QuadOverdrawDraw || overlay == DebugOverlay::QuadOverdrawPass)
  {
    if(DebugData.quadoverdrawFragShader)
    {
      SCOPED_TIMER("Quad Overdraw");

      float black[] = {0.0f, 0.0f, 0.0f, 0.0f};
      drv.glClearBufferfv(eGL_COLOR, 0, black);

      vector<uint32_t> events = passEvents;

      if(overlay == DebugOverlay::QuadOverdrawDraw)
        events.clear();

      events.push_back(eventId);

      if(!events.empty())
      {
        GLuint replacefbo = 0;
        GLuint quadtexs[3] = {0};
        drv.glGenFramebuffers(1, &replacefbo);
        drv.glBindFramebuffer(eGL_FRAMEBUFFER, replacefbo);

        drv.glGenTextures(3, quadtexs);

        // image for quad usage
        drv.glBindTexture(eGL_TEXTURE_2D_ARRAY, quadtexs[2]);
        drv.glTextureImage3DEXT(quadtexs[2], eGL_TEXTURE_2D_ARRAY, 0, eGL_R32UI,
                                RDCMAX(1, texDetails.width >> 1), RDCMAX(1, texDetails.height >> 1),
                                4, 0, eGL_RED_INTEGER, eGL_UNSIGNED_INT, NULL);
        drv.glTexParameteri(eGL_TEXTURE_2D_ARRAY, eGL_TEXTURE_MAX_LEVEL, 0);

        // temporarily attach to FBO to clear it
        GLint zero[4] = {0};
        drv.glFramebufferTextureLayer(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, quadtexs[2], 0, 0);
        drv.glClearBufferiv(eGL_COLOR, 0, zero);
        drv.glFramebufferTextureLayer(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, quadtexs[2], 0, 1);
        drv.glClearBufferiv(eGL_COLOR, 0, zero);
        drv.glFramebufferTextureLayer(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, quadtexs[2], 0, 2);
        drv.glClearBufferiv(eGL_COLOR, 0, zero);
        drv.glFramebufferTextureLayer(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, quadtexs[2], 0, 3);
        drv.glClearBufferiv(eGL_COLOR, 0, zero);

        drv.glBindTexture(eGL_TEXTURE_2D, quadtexs[0]);
        drv.glTextureImage2DEXT(quadtexs[0], eGL_TEXTURE_2D, 0, eGL_RGBA8, texDetails.width,
                                texDetails.height, 0, eGL_RGBA, eGL_UNSIGNED_BYTE, NULL);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_MAX_LEVEL, 0);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_MIN_FILTER, eGL_NEAREST);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_MAG_FILTER, eGL_NEAREST);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_WRAP_S, eGL_CLAMP_TO_EDGE);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_WRAP_T, eGL_CLAMP_TO_EDGE);
        drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, eGL_TEXTURE_2D,
                                   quadtexs[0], 0);

        GLuint curDepth = 0, depthType = 0;

        // TODO handle non-2D depth/stencil attachments and fetch slice or cubemap face
        GLint mip = 0;

        drv.glGetNamedFramebufferAttachmentParameterivEXT(rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT,
                                                          eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                                          (GLint *)&curDepth);
        drv.glGetNamedFramebufferAttachmentParameterivEXT(rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT,
                                                          eGL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
                                                          (GLint *)&depthType);

        GLenum fmt = eGL_DEPTH32F_STENCIL8;

        if(curDepth)
        {
          if(depthType == eGL_TEXTURE)
          {
            drv.glGetNamedFramebufferAttachmentParameterivEXT(
                rs.DrawFBO.name, eGL_DEPTH_ATTACHMENT, eGL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
                &mip);
            drv.glGetTextureLevelParameterivEXT(curDepth, eGL_TEXTURE_2D, mip,
                                                eGL_TEXTURE_INTERNAL_FORMAT, (GLint *)&fmt);
          }
          else
          {
            drv.glGetNamedRenderbufferParameterivEXT(curDepth, eGL_RENDERBUFFER_INTERNAL_FORMAT,
                                                     (GLint *)&fmt);
          }
        }

        drv.glBindTexture(eGL_TEXTURE_2D, quadtexs[1]);
        drv.glTextureImage2DEXT(quadtexs[1], eGL_TEXTURE_2D, 0, fmt, texDetails.width,
                                texDetails.height, 0, GetBaseFormat(fmt), GetDataType(fmt), NULL);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_MAX_LEVEL, 0);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_MIN_FILTER, eGL_NEAREST);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_MAG_FILTER, eGL_NEAREST);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_WRAP_S, eGL_CLAMP_TO_EDGE);
        drv.glTexParameteri(eGL_TEXTURE_2D, eGL_TEXTURE_WRAP_T, eGL_CLAMP_TO_EDGE);

        GLenum dsAttach = eGL_DEPTH_STENCIL_ATTACHMENT;

        if(GetBaseFormat(fmt) == eGL_DEPTH_COMPONENT)
          dsAttach = eGL_DEPTH_ATTACHMENT;

        drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, dsAttach, eGL_TEXTURE_2D, quadtexs[1], 0);

        if(overlay == DebugOverlay::QuadOverdrawPass)
          ReplayLog(events[0], eReplay_WithoutDraw);
        else
          rs.ApplyState(m_pDriver);

        for(size_t i = 0; i < events.size(); i++)
        {
          GLint depthwritemask = 1;
          GLint stencilfmask = 0xff, stencilbmask = 0xff;
          GLuint curdrawfbo = 0, curreadfbo = 0;
          struct
          {
            GLuint name;
            GLuint level;
            GLboolean layered;
            GLuint layer;
            GLenum access;
            GLenum format;
          } curimage0 = {0};

          // save the state we're going to mess with
          {
            drv.glGetIntegerv(eGL_DEPTH_WRITEMASK, &depthwritemask);
            drv.glGetIntegerv(eGL_STENCIL_WRITEMASK, &stencilfmask);
            drv.glGetIntegerv(eGL_STENCIL_BACK_WRITEMASK, &stencilbmask);

            drv.glGetIntegerv(eGL_DRAW_FRAMEBUFFER_BINDING, (GLint *)&curdrawfbo);
            drv.glGetIntegerv(eGL_READ_FRAMEBUFFER_BINDING, (GLint *)&curreadfbo);

            drv.glGetIntegeri_v(eGL_IMAGE_BINDING_NAME, 0, (GLint *)&curimage0.name);
            drv.glGetIntegeri_v(eGL_IMAGE_BINDING_LEVEL, 0, (GLint *)&curimage0.level);
            drv.glGetIntegeri_v(eGL_IMAGE_BINDING_ACCESS, 0, (GLint *)&curimage0.access);
            drv.glGetIntegeri_v(eGL_IMAGE_BINDING_FORMAT, 0, (GLint *)&curimage0.format);
            drv.glGetBooleani_v(eGL_IMAGE_BINDING_LAYERED, 0, &curimage0.layered);
            if(curimage0.layered)
              drv.glGetIntegeri_v(eGL_IMAGE_BINDING_LAYER, 0, (GLint *)&curimage0.layer);
          }

          // disable depth and stencil writes
          drv.glDepthMask(GL_FALSE);
          drv.glStencilMask(GL_FALSE);

          // bind our FBO
          drv.glBindFramebuffer(eGL_DRAW_FRAMEBUFFER, replacefbo);
          // bind image
          drv.glBindImageTexture(0, quadtexs[2], 0, GL_TRUE, 0, eGL_READ_WRITE, eGL_R32UI);

          GLuint prog = 0, pipe = 0;
          drv.glGetIntegerv(eGL_CURRENT_PROGRAM, (GLint *)&prog);
          drv.glGetIntegerv(eGL_PROGRAM_PIPELINE_BINDING, (GLint *)&pipe);

          // replace fragment shader. This is exactly what we did
          // at the start of this function for the single-event case, but now we have
          // to do it for every event
          CreateOverlayProgram(prog, pipe, DebugData.quadoverdrawFragShader);
          drv.glUseProgram(DebugData.overlayProg);
          drv.glBindProgramPipeline(0);

          GLint loc = drv.glGetUniformLocation(DebugData.overlayProg, "overdrawImage");
          if(loc != -1)
            drv.glUniform1i(loc, 0);
          else
            RDCERR("Couldn't get location of overdrawImage");

          drv.glBindFramebuffer(eGL_READ_FRAMEBUFFER, curdrawfbo);
          SafeBlitFramebuffer(0, 0, texDetails.width, texDetails.height, 0, 0, texDetails.width,
                              texDetails.height, GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
                              eGL_NEAREST);

          m_pDriver->ReplayLog(0, events[i], eReplay_OnlyDraw);

          // pop the state that we messed with
          {
            drv.glBindProgramPipeline(pipe);
            drv.glUseProgram(prog);

            if(curimage0.name)
              drv.glBindImageTexture(0, curimage0.name, curimage0.level,
                                     curimage0.layered ? GL_TRUE : GL_FALSE, curimage0.layer,
                                     curimage0.access, curimage0.format);
            else
              drv.glBindImageTexture(0, 0, 0, GL_FALSE, 0, eGL_READ_ONLY, eGL_R32UI);

            drv.glBindFramebuffer(eGL_DRAW_FRAMEBUFFER, curdrawfbo);
            drv.glBindFramebuffer(eGL_READ_FRAMEBUFFER, curreadfbo);

            drv.glDepthMask(depthwritemask ? GL_TRUE : GL_FALSE);
            drv.glStencilMaskSeparate(eGL_FRONT, (GLuint)stencilfmask);
            drv.glStencilMaskSeparate(eGL_BACK, (GLuint)stencilbmask);
          }

          if(overlay == DebugOverlay::QuadOverdrawPass)
          {
            m_pDriver->ReplayLog(0, events[i], eReplay_OnlyDraw);

            if(i + 1 < events.size())
              m_pDriver->ReplayLog(events[i] + 1, events[i + 1], eReplay_WithoutDraw);
          }
        }

        // resolve pass
        {
          drv.glUseProgram(DebugData.quadoverdrawResolveProg);
          drv.glBindProgramPipeline(0);

          // modify our fbo to attach the overlay texture instead
          drv.glBindFramebuffer(eGL_FRAMEBUFFER, replacefbo);
          drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, texBindingEnum,
                                     DebugData.overlayTex, 0);
          drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, eGL_DEPTH_STENCIL_ATTACHMENT, texBindingEnum,
                                     0, 0);

          drv.glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
          drv.glDisable(eGL_BLEND);
          drv.glDisable(eGL_SCISSOR_TEST);
          drv.glDepthMask(GL_FALSE);
          drv.glDisable(eGL_CULL_FACE);
          if(!IsGLES)
            drv.glPolygonMode(eGL_FRONT_AND_BACK, eGL_FILL);
          drv.glDisable(eGL_DEPTH_TEST);
          drv.glDisable(eGL_STENCIL_TEST);
          drv.glStencilMask(0);
          drv.glViewport(0, 0, texDetails.width, texDetails.height);

          drv.glBindImageTexture(0, quadtexs[2], 0, GL_TRUE, 0, eGL_READ_WRITE, eGL_R32UI);

          GLuint emptyVAO = 0;
          drv.glGenVertexArrays(1, &emptyVAO);
          drv.glBindVertexArray(emptyVAO);
          drv.glDrawArrays(eGL_TRIANGLE_STRIP, 0, 4);
          drv.glBindVertexArray(0);
          drv.glDeleteVertexArrays(1, &emptyVAO);

          drv.glFramebufferTexture2D(eGL_FRAMEBUFFER, eGL_COLOR_ATTACHMENT0, eGL_TEXTURE_2D,
                                     quadtexs[0], 0);
        }

        drv.glDeleteFramebuffers(1, &replacefbo);
        drv.glDeleteTextures(3, quadtexs);

        if(overlay == DebugOverlay::QuadOverdrawPass)
          ReplayLog(eventId, eReplay_WithoutDraw);
      }
    }
  }
  else
  {
    RDCERR(
        "Unexpected/unimplemented overlay type - should implement a placeholder overlay for all "
        "types");
  }

  rs.ApplyState(m_pDriver);

  DebugData.overlayTexId =
      m_pDriver->GetResourceManager()->GetID(TextureRes(ctx, DebugData.overlayTex));

  return DebugData.overlayTexId;
}


text:
//  This module defines the FunctionObject class whose objects represent
//  each function r in the Gauss-Newton non-linear least squares solver
//  implementation described in main.cpp.
//
//  Each function object is constructed to return either the screen x or
//  screen y error term for a given point. This error term is the
//  distance in pixels between the observed screen position of the point
//  and the computed screen position of the point, given the camera
//  described by the beta vector. These error terms are used as feedback
//  for the Gauss-Newton solver.

#include "function_object.h"

#include <vector>
#include <Eigen/Dense>

#define DEG_TO_RAD (M_PI / 180.0)

//
//  Member Function: FunctionObject::xp
//
//  Return the screen coordinate x (_xp) stored in the object by the
//  constructor.
//
//  No input parameters
//

double FunctionObject::xp() const
{
  return _xp;
}

//
//  Member Function: FunctionObject::yp
//
//  Return the screen coordinate y (_yp) stored in the object by the
//  constructor.
//
//  No input parameters
//

double FunctionObject::yp() const
{
  return _yp;
}

//
//  Member Function: FunctionObject::x3d
//
//  Return the 3d coordinate x (_x3d) stored in the object by the
//  constructor.
//
//  No input parameters
//

double FunctionObject::x3d() const
{
  return _x3d;
}

//
//  Member Function: FunctionObject::y3d
//
//  Return the 3d coordinate y (_y3d) stored in the object by the
//  constructor.
//
//  No input parameters
//

double FunctionObject::y3d() const
{
  return _y3d;
}

//
//  Member Function: FunctionObject::z3d
//
//  Return the 3d coordinate z (_z3d) stored in the object by the
//  constructor.
//
//  No input parameters
//

double FunctionObject::z3d() const
{
  return _z3d;
}

//
//  Member Function: FunctionObject::operator()
//
//  If an even valued index (_indx) has been stored in the object by the
//  constructor, return the difference between the point's x screen
//  coordinate and the x screen backprojection coordinate of the point's
//  3d coordinates backprojected by the camera specified by the input
//  beta parameter vector. Otherwise, return the difference between the
//  point's y screen coordinate and the y screen backprojection coordinate.
//
//  Input parameters:
//  beta -- vector containing camera parameters to optimize
//

double FunctionObject::operator()(Eigen::VectorXd const &beta) const
{
  double ret;

  if(_indx % 2 == 0)
  {
    ret = _xp - EvalBackProject(beta);
  }
  else
  {
    ret = _yp - EvalBackProject(beta);
  }

  return ret;
}

//
// Member Function: FunctionObject::EvalBackProject
//

//  If an even valued index (_indx) has been stored in the object by the
//  constructor, return the x screen backprojection coordinate of the
//  point's 3d coordinates backprojected by the camera specified by the
//  input beta parameter vector. Otherwise, return the y screen
//  backprojection coordinate.
//
//  Input parameters:
//  beta -- vector containing camera parameters to optimize
//

double FunctionObject::EvalBackProject(Eigen::VectorXd const &beta) const
{
  double k = beta[0];
  double tx = beta[1];
  double ty = beta[2];
  double tz = beta[3];
  double rx = beta[4] * DEG_TO_RAD;
  double ry = beta[5] * DEG_TO_RAD;
  double rz = beta[6] * DEG_TO_RAD;

  Eigen::Affine3d rya = Eigen::Affine3d(Eigen::AngleAxisd(-ry,
      Eigen::Vector3d::UnitY()));
  Eigen::Affine3d rxa = Eigen::Affine3d(Eigen::AngleAxisd(-rx,
  Eigen::Vector3d::UnitX()));
  Eigen::Affine3d rza = Eigen::Affine3d(Eigen::AngleAxisd(-rz,
      Eigen::Vector3d::UnitZ()));
  Eigen::Affine3d t1(Eigen::Translation3d(-tx, -ty, -tz));

  Eigen::Matrix4d m4 = (rza * rxa * rya * t1).matrix();
  Eigen::Vector3d pn(_x3d, _y3d, _z3d);
  Eigen::Vector4d pnh = pn.homogeneous();
  Eigen::Vector4d pnh2 = m4 * pnh;
  Eigen::Vector3d pn2 = pnh2.hnormalized();

  //  Handle case when point is behind camera.
  if(pn2[2] > 0.0)
  {
    return 1.e10;
  }

  double ret;
  if(_indx % 2 == 0)
  {
    ret = k * pn2[0] / -pn2[2];
  }
  else
  {
    ret = k * pn2[1] / -pn2[2];
  }

  return ret;
}


text:
package org.estatio.module.lease.dom.breaks;

import java.util.List;

import com.google.common.collect.Iterables;

import org.joda.time.LocalDate;

import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.Optionality;
import org.apache.isis.applib.annotation.Parameter;
import org.apache.isis.applib.annotation.Programmatic;

import org.incode.module.base.dom.utils.JodaPeriodUtils;

import org.estatio.module.base.dom.UdoDomainRepositoryAndFactory;
import org.estatio.module.lease.dom.Lease;

@DomainService(nature = NatureOfService.DOMAIN, repositoryFor = BreakOption.class)
public class BreakOptionRepository extends UdoDomainRepositoryAndFactory<BreakOption> {

    public BreakOptionRepository() {
        super(BreakOptionRepository.class, BreakOption.class);
    }

    @Programmatic
    public BreakOption newBreakOption(
            final Lease lease,
            final LocalDate breakDate,
            final String notificationPeriod,
            final BreakType breakType,
            final BreakExerciseType breakExerciseType,
            final @Parameter(optionality = Optionality.OPTIONAL) String description
    ) {
        final BreakOption breakOption = newTransientInstance(breakType.getFactoryClass());
        breakOption.setType(breakType);
        breakOption.setLease(lease);
        breakOption.setExerciseType(breakExerciseType);
        breakOption.setBreakDate(breakDate);
        breakOption.setNotificationPeriod(notificationPeriod);
        breakOption.setExerciseDate(breakDate.minus(JodaPeriodUtils.asPeriod(notificationPeriod)));
        breakOption.setDescription(description);
        persist(breakOption);
        return breakOption;
    }

    @Programmatic
    public String checkNewBreakOptionDuplicate(final Lease lease, final BreakType breakType, final LocalDate breakDate) {
        final Iterable<BreakOption> duplicates =
                Iterables.filter(findByLease(lease),
                        BreakOption.Predicates.whetherTypeAndBreakDate(breakType, breakDate));
        return duplicates.iterator().hasNext() ?
                "This lease already has a " + breakType + " break option for this date" : null;
    }

    @Programmatic
    public List<BreakOption> findByLease(final Lease lease) {
        return allMatches("findByLease", "lease", lease);
    }

    @Programmatic
    public void copyBreakOptions(final Lease lease, final Lease newLease, final LocalDate startDate) {
        for (BreakOption option : findByLease(lease)) {
            if (option.getBreakDate().isAfter(startDate)) {
                newBreakOption(
                        newLease,
                        option.getBreakDate(),
                        option.getNotificationPeriod(),
                        option.getType(),
                        option.getExerciseType(),
                        option.getDescription());
            }
        }
    }

    @Programmatic
    public BreakOption findByLeaseAndTypeAndBreakDateAndExerciseType(
            final Lease lease,
            final BreakType type,
            final LocalDate breakDate,
            final BreakExerciseType exerciseType) {
        return uniqueMatch("findByLeaseAndTypeAndBreakDateAndExerciseType",
                "lease", lease,
                "type", type,
                "breakDate", breakDate,
                "exerciseType", exerciseType
        );
    }

    @Programmatic
    public List<BreakOption> allBreakOptions() {
        return allInstances();
    }
}


text:
var express = require('express');

var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');

// var bodyParser = require('body-parser');
// var cookieSession = require('cookie-session');

require('babel-core/register');

var jsdom = require("jsdom").jsdom;
var doc = jsdom();
window = doc.defaultView;

// Load jQuery with the simulated jsdom window.
$ = jQuery = require('jquery');

require("./database/connection.js");
var Product = require("./database/collections/productsCollection.js");
var User = require("./database/collections/usersCollection.js");

var core = require("./public/scripts/core.js");
var currencies = require("./public/scripts/currencies.js");

var authenticationHelper = require("./public/scripts/helpers/authenticationHelper.js");

var cache = require("memory-cache");

require("./public/scripts/appExtensions/requirements.js")(app, express, __dirname);

// get login page
app.get('/login', function(req, res) {
    if (authenticationHelper.isUserLoggedIn(req)) {
        res.redirect("/products");
    } else {
        res.render('pages/login');
    }
});

// post login
app.post('/login', function(req, res) {
    // Get our form values. These rely on the "name" attributes
    User.findOne({ 'username': req.body.username }, function(err, user) {
        if (user) {
            if (authenticationHelper.logUser(req, res, user)) {
                res.redirect("/products");
            } else {
                res.send("Invalid password!");
                return;
            }
        } else {
            res.send("No such user found!");
            return;
        }
    });
});

// get register page
app.get('/register', function(req, res) {
    res.render('pages/register');
});

// post register
app.post('/register', function(req, res) {
    // Get our form values. These rely on the "name" attributes
    var password = req.body.password;
    var confirmPassword = req.body.confirmPassword;
    if (password != confirmPassword) {
        res.send("Password and confirm password are not equal!");
        return;
    }

    var hashedPasword = authenticationHelper.hashPassword(password);
    // Submit to the DB
    new User({
        "username": req.body.username,
        "password": hashedPasword,
        "email": req.body.email,
        "firstName": req.body.firstName,
        "lastName": req.body.lastName
    }).save(function(err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem registering the user.");
        } else {
            // And forward to success page
            res.redirect("/login");
        }
    });
});

app.get('/logout', authenticationHelper.requireAuthentication, function(req, res) {
    req.session = null;
    res.redirect("/login");
});

// index page
app.get('/', authenticationHelper.requireAuthentication, function(req, res) {
    res.render('pages/index');
});

// about page
app.get('/about', authenticationHelper.requireAuthentication, function(req, res) {
    res.render('pages/about');
});

// objects index page
app.get('/products', authenticationHelper.requireAuthentication, function(req, res) {
    var skip = parseInt(req.query.skip);
    if (!skip) {
        skip = 0;
    }
    var take = parseInt(req.query.take);
    if (!take) {
        take = 10;
    }

    var searchText = req.query.search;
    var queryOptions = { skip: skip, limit: take };
    var searchOptions = core.constructSearchOptions(searchText, req.session.accessToken);
    Product.count(searchOptions, function(error, productsCount) {
        Product.find(searchOptions).skip(skip).limit(take).exec(function(err, products) {
            try {
                if (!products || products.length == 0) {
                    res.render('pages/products/index', {
                        "objectslist": [],
                        "objectsCount": 0,
                        "skip": skip,
                        "take": take,
                        "search": searchText
                    });
                    return;
                }

                cache.put("productsLength", products.length);
                cache.put("productsParsed", 0);
                cache.put("products", products);
                core.parseDocRecursively(cache,
                    function(parsedProducts) {
                        res.render('pages/products/index', {
                            "objectslist": parsedProducts,
                            "objectsCount": productsCount,
                            "skip": skip,
                            "take": take,
                            "search": searchText
                        });
                    });
            } catch (e) {
                console.log("error occured: ", e);
            }
        });
    });
});

// objects create page
app.get('/products/edit/:id', authenticationHelper.requireAuthentication, function(req, res) {
    var productId = req.params.id;
    Product.findOne({ '_id': productId }, function(err, doc) {
        if (doc) {
            var currencySymbol = currencies.getCurrencySymbol(doc.currency);
            doc.currencySymbol = currencySymbol;
        } else {
            doc = {};
        }
        res.render('pages/products/edit', {
            "doc": doc
        });
    });
});

app.post('/products/edit/:id', authenticationHelper.requireAuthentication, function(req, res) {
    var productId = req.params.id;

    var updatedProduct = {
        "name": req.body.objectName,
        "description": req.body.objectDescription,
    }

    Product.findByIdAndUpdate(productId, updatedProduct, function(err, doc) {
        res.redirect("/products");
    });
});

// objects create page
app.get('/products/create', authenticationHelper.requireAuthentication, function(req, res) {
    res.render('pages/products/create');
});

// objects create page
app.post('/products/create', authenticationHelper.requireAuthentication, function(req, res) {
    // Get our form values. These rely on the "name" attributes
    var currentUserId = authenticationHelper.getLoggedUserId(req.session.accessToken);
    // Submit to the DB
    new Product({
        "name": req.body.objectName,
        "objectUrl": req.body.objectUrl,
        "oldPrice": req.body.objectPrice,
        "newPrice": req.body.objectPrice,
        "description": req.body.objectDescription,
        "imageUrl": req.body.imageUrl,
        "website": req.body.website,
        "currency": req.body.objectCurrency,
        "dateCreated": new Date(),
        "user": currentUserId,
        "lastChecked": new Date()
    }).save(function(err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        } else {
            // And forward to success page
            res.redirect("/products");
        }
    });

});

app.get("/products/delete/:id", authenticationHelper.requireAuthentication, function(req, res) {
    var productId = req.params.id;
    Product.findByIdAndRemove({ '_id': productId }, function(err, doc) {
        res.redirect("/products");
    });
});

require("./public/scripts/appExtensions/methods.js")(app, authenticationHelper.requireAuthentication);

app.listen(8080);
console.log('Application started on 8080 port');


text:
class QMimeData;

class ImageArea : public QLabel
{
    Q_OBJECT

public:
    explicit ImageArea(QWidget* parent = 0);
    void SetImage(const DAVA::FilePath& filePath);
    void SetImage(const DAVA::ScopedPtr<DAVA::Image>& image);
    inline const DAVA::ScopedPtr<DAVA::Image>& GetImage() const;
    DAVA::Vector2 GetAcceptableSize() const;
    const DAVA::FilePath& GetImagePath() const;

    void SetRequestedImageFormat(const DAVA::PixelFormat format);
    DAVA::PixelFormat GetRequestedImageFormat() const;

public slots:
    void ClearArea();
    void UpdatePreviewPicture();

    void SetAcceptableSize(const DAVA::Vector2& size);

signals:

    void changed();

private:
    void mousePressEvent(QMouseEvent* event);
    void dragEnterEvent(QDragEnterEvent* event);
    void dropEvent(QDropEvent* event);

    void ConnectSignals();
    DAVA::String GetDefaultPath() const;

    DAVA::ScopedPtr<DAVA::Image> image;
    DAVA::Vector2 acceptableSize;
    DAVA::FilePath imagePath;

    DAVA::PixelFormat requestedFormat;
};

inline const DAVA::ScopedPtr<DAVA::Image>& ImageArea::GetImage() const
{
    return image;
}


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class AllExercises(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the AllExercises Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(AllExercises, self).__init__(temboo_session, '/Library/KhanAcademy/Exercises/AllExercises')

    def new_input_set(self):
        return AllExercisesInputSet()

    def _make_result_set(self, result, path):
        return AllExercisesResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return AllExercisesChoreographyExecution(session, exec_id, path)

class AllExercisesInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the AllExercises
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    pass

class AllExercisesResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the AllExercises Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Khan Academy.)
        """
        return self._output.get('Response', None)

class AllExercisesChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return AllExercisesResultSet(response, path)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Xamarin.UITest;
using Xamarin.UITest.Queries;

namespace Microsoft.Identity.Test.UIAutomation.Infrastructure
{
    public interface ITestController
    {
        ///
        /// Taps an element on the UI
        ///
        /// <param name="elementID">ID of the element to tap</param>
        void Tap(string elementID);

        ///
        /// Taps an element on the UI
        ///
        /// <param name="textOrId">ID or text of the element to tap</param>
        /// <param name="xamarinSelector">Strategy for finding the element</param>
        void Tap(string textOrId, XamarinSelector xamarinSelector);

        ///
        /// Taps an element on the UI
        ///
        /// <param name="textOrId">ID or text of the element to tap</param>
        /// <param name="waitTime">The time in seconds in which the test controller will search for the element before it times out</param>
        /// <param name="xamarinSelector">Strategy for finding the element</param>
        void Tap(string elementID, int waitTime, XamarinSelector xamarinSelector);

        ///
        /// enters text into a text field on the UI
        ///
        /// <param name="textOrId">ID or text of the element to tap</param>
        /// <param name="text">The text to be entered into the element</param>
        /// <param name="isWebElement">Set to true if the element to be tapped is within a web view</param>
        void EnterText(string elementID, string text, XamarinSelector xamarinSelector);

        ///
        /// enters text into a text field on the UI
        ///
        /// <param name="textOrId">ID or text of the element to tap</param>
        /// <param name="waitTime">The time in seconds in which the test controller will search for the element before it times out</param>
        /// <param name="text">The text to be entered into the element</param>
        /// <param name="isWebElement">Set to true if the element to be tapped is within a web view</param>
        void EnterText(string textOrId, int waitTime, string text, XamarinSelector xamarinSelector);

        ///
        /// Dismisses the keyboard. This should be called after each text input operation with the keyboard because the keyboard can stay active and hide
        /// buttons from the Ui Automation framework.
        ///
        void DismissKeyboard();

        ///
        /// Returns the text of an element visible on the UI
        ///
        /// <param name="textOrId">ID of the element to get text from</param>
        /// <returns>The text value of the element</returns>
        string GetText(string textOrId);

        ///
        /// Checks if a switch has changed state
        ///
        /// <param name="automationID">ID of the element to tap</param>
        void SetSwitchState(string automationID);

        IApp Application { get; set; }

        ///
        /// Waits for an html element to be present and returns it.
        ///
        /// <param name="resourceId">Id of the html element, exposed as "resource-id" by the UI Automation Viewer tool</param>
        /// <returns></returns>
        AppWebResult[] WaitForWebElementByCssId(string resourceId, TimeSpan? timeout = null);

        ///
        /// Waits for a native XAML widget element to be present and returns it.
        ///
        /// <param name="elementID">An automation id</param>
        /// <returns></returns>
        AppResult[] WaitForXamlElement(string elementID, TimeSpan? timeout = null);

        ///
        /// Waits for an HTML element to be present and returns it. Useful when the WebUI does not have elements with IDs.
        ///
        /// <param name="text">The text of the element, e.g. foo will find the element div in
foo

        /// </param>
        AppWebResult[] WaitForWebElementByText(string text, TimeSpan? timeout = null);

        ///
        /// Platform in which the controller is operating
        ///
        Platform Platform { get; set; }
    }
}


text:
Tie.class_eval do
  include SocialStream::Ostatus::Models::Tie
end


text:
<!DOCTYPE html>

    <title>jQuery Reel Non-Animated Sprite Object Movie Example</title>
    <meta charset='utf-8' content='text/html' http-equiv='Content-type' />

    <link href="../style.css" rel="stylesheet" type="text/css" />

    Examples ‹

Non-Animated Sprite

Erik Kluka

    <img src="f1-ccw.jpg" width="276" height="126"
      class="reel"
      id="image"
      data-image="f1-ccw-reel.jpg"
      data-frames="35"
      data-opening="2"
      data-entry="1">

      To test horizontal/frame stepping events:
      <button id="left">stepLeft</button>
      <button id="right">stepRight</button>

    $("#image").trigger("stepLeft");
    $("#image").trigger("stepRight");

Some text ballast to make the page positively scroll-worthy for testing purposes.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed rutrum semper imperdiet. Integer non auctor orci. Nullam dictum pretium metus, interdum congue sapien lobortis in. Donec sed massa a tellus dapibus auctor et in mauris. Curabitur adipiscing fermentum felis vel molestie. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut semper sem ut nulla fringilla luctus. Curabitur dignissim quam ac libero consequat tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In hac habitasse platea dictumst. Nunc sed lectus eget magna suscipit tempor eget id nibh.


text:
import c3nav.mapdata.fields
from decimal import Decimal
import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('mapdata', '0006_location_icon'),
    ]

    operations = [
        migrations.AddField(
            model_name='locationgroupcategory',
            name='help_text',
            field=c3nav.mapdata.fields.I18nField(fallback_any=True, fallback_value='', plural_name='help_texts', verbose_name='Help text'),
        ),
        migrations.AlterField(
            model_name='area',
            name='slow_down_factor',
            field=models.DecimalField(decimal_places=2, default=1, help_text='values of overlapping areas get multiplied!', max_digits=6, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))], verbose_name='slow down factor'),
        ),
    ]