text:
package com.pinterest.teletraan.resource;

import com.pinterest.deployservice.bean.*;
import com.pinterest.deployservice.common.Constants;
import com.pinterest.deployservice.dao.EnvironDAO;
import com.pinterest.deployservice.handler.ConfigHistoryHandler;
import com.pinterest.deployservice.handler.EnvironHandler;
import com.pinterest.teletraan.TeletraanServiceContext;
import com.pinterest.teletraan.security.Authorizer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;

@Path("/v1/envs/{envName : [a-zA-Z0-9\\-_]+}/{stageName : [a-zA-Z0-9\\-_]+}/web_hooks")
@Api(tags = "Environments")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class EnvWebHooks {
    private static final Logger LOG = LoggerFactory.getLogger(EnvWebHooks.class);
    private EnvironDAO environDAO;
    private EnvironHandler environHandler;
    private ConfigHistoryHandler configHistoryHandler;
    private Authorizer authorizer;

    @Context
    UriInfo uriInfo;

    public EnvWebHooks(TeletraanServiceContext context) {
        environDAO = context.getEnvironDAO();
        environHandler = new EnvironHandler(context);
        configHistoryHandler = new ConfigHistoryHandler(context);
        authorizer = context.getAuthorizer();
    }

    @GET
    @ApiOperation(
            value = "Get webhooks object",
            notes = "Returns a pre/post webhooks object by given environment and stage names",
            response = EnvWebHookBean.class)
    public EnvWebHookBean get(
            @ApiParam(value = "Environment name", required = true)@PathParam("envName") String envName,
            @ApiParam(value = "Stage name", required = true)
            @PathParam("stageName") String stageName) throws Exception {
        EnvironBean environBean = Utils.getEnvStage(environDAO, envName, stageName);
        return environHandler.getHooks(environBean);
    }

    @PUT
    @ApiOperation(
            value = "Update webhooks",
            notes = "Updates pre/deploy webhooks by given environment and stage names with given webhooks object")
    public void update(@Context SecurityContext sc,
                       @ApiParam(value = "Environment name", required = true)@PathParam("envName") String envName,
                       @ApiParam(value = "Stage name", required = true)@PathParam("stageName") String stageName,
        EnvWebHookBean hookBean) throws Exception {
        EnvironBean environBean = Utils.getEnvStage(environDAO, envName, stageName);
        authorizer.authorize(sc, new Resource(environBean.getEnv_name(), Resource.Type.ENV), Role.OPERATOR);
        String userName = sc.getUserPrincipal().getName();
        environHandler.updateHooks(environBean, hookBean, userName);
        configHistoryHandler.updateConfigHistory(environBean.getEnv_id(), Constants.TYPE_ENV_WEBHOOK, hookBean, userName);
        configHistoryHandler.updateChangeFeed(Constants.CONFIG_TYPE_ENV, environBean.getEnv_id(), Constants.TYPE_ENV_WEBHOOK, userName);
        LOG.info("Successfully updated web hooks {} for env {}/{} by {}.",
            hookBean, envName, stageName, userName);
    }
}


text:
package org.jclouds.vsphere;

import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.rest.internal.BaseHttpApiMetadata;
import org.jclouds.vsphere.compute.config.VSphereComputeServiceContextModule;
import org.jclouds.vsphere.config.VSphereConstants;

import java.net.URI;
import java.util.Properties;

import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.reflect.Reflection2.typeToken;

/**
 * Implementation of {@link BaseHttpApiMetadata} for vSphere 5.1 API
 * <p/>
 */
public class VSphereApiMetadata extends BaseHttpApiMetadata<VSphereApi> {

   @Override
   public Builder toBuilder() {
      return new Builder().fromApiMetadata(this);
   }

   public VSphereApiMetadata() {
      this(new Builder());
   }

   protected VSphereApiMetadata(Builder builder) {
      super(builder);
   }

   public static Properties defaultProperties() {
      Properties properties = BaseHttpApiMetadata.defaultProperties();
      properties.setProperty(PROPERTY_SESSION_INTERVAL, 8 * 60 + "");
      properties.setProperty("jclouds.dns_name_length_min", "1");
      properties.setProperty("jclouds.dns_name_length_max", "80");
      properties.setProperty(PROPERTY_SESSION_INTERVAL, 300 + "");
      properties.setProperty(VSphereConstants.JCLOUDS_VSPHERE_VM_PASSWORD, "master");
      properties.setProperty(VSphereConstants.CLONING, "full");
      return properties;
   }

   public static class Builder extends BaseHttpApiMetadata.Builder<VSphereApi, Builder> {
      protected Builder() {
         id("vsphere")
                 .name("vSphere 5.1 API")
                 .identityName("user")
                 .credentialName("password")
                 .endpointName("ESXi endpoint or vCenter server")
                         // .defaultEndpoint("https://localhost/sdk")
                 .documentation(URI.create("http://www.vmware.com/support/pubs/vcd_pubs.html"))
                 .version("5.1")
                 .defaultProperties(VSphereApiMetadata.defaultProperties())
                 .view(typeToken(ComputeServiceContext.class))
                 .defaultModules(ImmutableSet.<Class<? extends Module>>of(VSphereComputeServiceContextModule.class));
      }

      @Override
      public VSphereApiMetadata build() {
         return new VSphereApiMetadata(this);
      }

      @Override
      protected Builder self() {
         return this;
      }
   }
}

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.om2m.commons.obix;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
 * Abstime oBIX object.
 * @author Francois Aissaoui
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "abstime")
@XmlRootElement
public class Abstime extends Obj{

    @XmlAttribute(name = "val")
    @XmlSchemaType(name = "anyURI")
    protected String val;
    @XmlAttribute(name = "min")
    protected Long min;
    @XmlAttribute(name = "max")
    protected Long max;
    @XmlAttribute(name = "tz")
    protected String tz;
    @XmlAttribute(name = "displayName")
    protected String displayName;
    @XmlAttribute(name = "display")
    protected String display;
    @XmlAttribute(name = "icon")
    @XmlSchemaType(name = "anyURI")
    protected String icon;
    @XmlAttribute(name = "precision")
    protected Integer precision;
    @XmlAttribute(name = "status")
    protected Status status;
    @XmlAttribute(name = "unit")
    protected String unit;
    @XmlAttribute(name = "writable")
    protected Boolean writable;
    @XmlAttribute(name = "name")
    protected String name;
    @XmlAttribute(name = "href")
    protected String href;
    @XmlAttribute(name = "null")
    protected Boolean _null;

    /**
     * Default empty contructor
     */
    public Abstime(){}

	/**
	 * @return the val
	 */
	public String getVal() {
		return val;
	}

	/**
	 * @param val the val to set
	 */
	public void setVal(String val) {
		this.val = val;
	}

	/**
	 * @return the min
	 */
	public Long getMin() {
		return min;
	}

	/**
	 * @param min the min to set
	 */
	public void setMin(Long min) {
		this.min = min;
	}

	/**
	 * @return the max
	 */
	public Long getMax() {
		return max;
	}

	/**
	 * @param max the max to set
	 */
	public void setMax(Long max) {
		this.max = max;
	}

	/**
	 * @return the tz
	 */
	public String getTz() {
		return tz;
	}

	/**
	 * @param tz the tz to set
	 */
	public void setTz(String tz) {
		this.tz = tz;
	}

	/**
	 * @return the displayName
	 */
	public String getDisplayName() {
		return displayName;
	}

	/**
	 * @param displayName the displayName to set
	 */
	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}

	/**
	 * @return the display
	 */
	public String getDisplay() {
		return display;
	}

	/**
	 * @param display the display to set
	 */
	public void setDisplay(String display) {
		this.display = display;
	}

	/**
	 * @return the icon
	 */
	public String getIcon() {
		return icon;
	}

	/**
	 * @param icon the icon to set
	 */
	public void setIcon(String icon) {
		this.icon = icon;
	}

	/**
	 * @return the precision
	 */
	public Integer getPrecision() {
		return precision;
	}

	/**
	 * @param precision the precision to set
	 */
	public void setPrecision(Integer precision) {
		this.precision = precision;
	}

	/**
	 * @return the status
	 */
	public Status getStatus() {
		return status;
	}

	/**
	 * @param status the status to set
	 */
	public void setStatus(Status status) {
		this.status = status;
	}

	/**
	 * @return the unit
	 */
	public String getUnit() {
		return unit;
	}

	/**
	 * @param unit the unit to set
	 */
	public void setUnit(String unit) {
		this.unit = unit;
	}

	/**
	 * @return the writable
	 */
	public Boolean getWritable() {
		return writable;
	}

	/**
	 * @param writable the writable to set
	 */
	public void setWritable(Boolean writable) {
		this.writable = writable;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the href
	 */
	public String getHref() {
		return href;
	}

	/**
	 * @param href the href to set
	 */
	public void setHref(String href) {
		this.href = href;
	}

	/**
	 * @return the _null
	 */
	public Boolean get_null() {
		return _null;
	}

	/**
	 * @param _null the _null to set
	 */
	public void set_null(Boolean _null) {
		this._null = _null;
	}

}


text:
package com.thoughtworks.go.util;

import java.util.Calendar;
import java.util.Date;

import org.joda.time.DateTime;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class DateUtilsTest {

    @Test public void shouldBeAbleToParseRFC822Dates() throws Exception {
        Date date = DateUtils.parseRFC822("Tue, 09 Dec 2008 18:56:14 +0800");
        assertThat(date, is(new DateTime("2008-12-09T18:56:14+08:00").toDate()));
    }

    @Test
    public void shouldFormatDateToDisplayOnUI() {
        Calendar instance = Calendar.getInstance();
        instance.set(2009, Calendar.NOVEMBER, 5);
        Date date = instance.getTime();
        String formattedDate = DateUtils.formatToSimpleDate(date);
        assertThat(formattedDate, is("05 Nov 2009"));
    }
}


text:
'use strict';

var ensureArray  = require('es5-ext/array/valid-array')
  , ensureObject = require('es5-ext/object/valid-object')
  , generateId   = require('dom-ext/html-document/generate-id');

var generateTableBody = function (rows, master) {
	return rows.map(function (row) {
		return tr(th(row.label, span({ class: 'hint' }, row.inputHint)),
			list(row.paths, function (path) {
				if (path == null) return td();
				var resolved = master.resolveSKeyPath(path);
				return td(input({
					control: { id: 'matrix-display-input-' + path },
					dbjs: resolved.observable,
					required: false
				}));
			}),
			td({ id: row.totalId }));
	});
};

module.exports = function (config) {
	var horizontalTotal, horizontalTotals = [], verticalTotals = [], skipVerticalTotal,
		totalId, rows, columnLabels, lastRowLabel, tableId, master, formId;
	ensureObject(config);
	rows              = ensureArray(config.rows);
	columnLabels      = ensureArray(config.columnLabels);
	lastRowLabel      = config.lastRowLabel;
	master            = ensureObject(config.master);
	tableId           = config.tableId || generateId();
	formId            = config.formId || tableId;
	skipVerticalTotal = config.skipVerticalTotal;

	totalId = generateId('total');
	//vertical totals
	if (!skipVerticalTotal) {
		rows.forEach(function (row) {
			var verticalTotal = {
				totalId: generateId('total'),
				paths: row.paths
			};
			verticalTotals.push(verticalTotal);
			row.totalId = verticalTotal.totalId;
		});
	}
	//horizontal totals
	rows[0].paths.forEach(function (path, index) {
		horizontalTotal = {
			totalId: generateId('total'),
			paths: []
		};
		rows.forEach(function (row) {
			horizontalTotal.paths.push(row.paths[index]);
		});
		horizontalTotals.push(horizontalTotal);
	});

	return table({ id: tableId },
		thead(tr(
			th(),
			list(columnLabels, function (label) {
				return th(label);
			})
		)),
		tbody(generateTableBody(rows, master)),
		tfoot(tr(
			th(lastRowLabel),
			list(horizontalTotals, function (horizontalTotal) {
				return td({ id: horizontalTotal.totalId });
			}),
			td({ id: totalId })
		)),

		script(function (formId, horizontalTotals, verticalTotals, totalId) {
			var form = $(formId), totals = [], fullTotal = { total: $(totalId), subTotals: [] };
			$.forEach(horizontalTotals.concat(verticalTotals), function (total) {
				var subTotatals = [];
				$.forEach(total.paths, function (path) {
					if (path == null) return;
					subTotatals.push($('matrix-display-input-' + path));
				});
				totals.push({
					total: $(total.totalId),
					subTotals: subTotatals
				});
			});
			$.forEach(verticalTotals, function (total) {
				var subTotatals = [];
				$.forEach(total.paths, function (path) {
					if (path == null) return;
					subTotatals.push($('matrix-display-input-' + path));
				});
				fullTotal.subTotals = fullTotal.subTotals.concat(subTotatals);
			});
			if (verticalTotals.length > 0) totals.push(fullTotal);

			$.onEnvUpdate(form, function () {
				$.forEach(totals, function (total) {
					var sum = 0;
					$.forEach(total.subTotals, function (subTotal) {
						sum += (subTotal.value ? Number(subTotal.value) : 0);
					});
					total.total.innerText = sum.toLocaleString();
				});
			});
		}, formId, horizontalTotals, verticalTotals, totalId));
};


text:
set TWITTERWALL_FRONTEND_MAX_RESULTS=200
set TWITTERWALL_SHOW_USERS_MENU=true
set TWITTERWALL_CONTEXT_TEST=true
set TWITTER_PAGE_SIZE=50
set TWITTER_FETCH_TESTDATA=false
set TWITTERWALL_WAIT_FOR_TEST=120000
set TWITTERWALL_URL_TEST_DATA_VERBOSE=false
set TWITTERWALL_SCHEDULER_ALLOW_UPDATE_TWEETS=false
set TWITTERWALL_SCHEDULER_ALLOW_UPDATE_USERS=false
set TWITTERWALL_SCHEDULER_ALLOW_UPDATE_USERS_FROM_MENTION=false
set TWITTERWALL_SCHEDULER_ALLOW_REMOVE_OLD_DATA_FROM_STORAGE=false
set TWITTERWALL_SCHEDULER_ALLOW_SEARCH=false
set TWITTER_SEARCH_TERM='#hibernate OR #java OR #TYPO3'
set TWITTERWALL_INFO_WEBPAGE=https://github.com/phasenraum2010/twitterwall2
set TWITTERWALL_THEME=typo3
set TWITTERWALL_APP_NAME=Twitterwall
set TWITTERWALL_INFO_IMPRINT_SCREEN_NAME=port80guru
set TWITTERWALL_GOOGLE_ANALYTICS_ID=TWITTERWALL_GOOGLE_ANALYTICS_ID
set TWITTERWALL_SCHEDULER_HEROKU_DB_LIMIT=false
set TWITTERWALL_SCHEDULER_USER_LIST_NAME=test-typo3-hibernate-java
set TWITTERWALL_SCHEDULER_USER_LIST_ALLOW=false
set TWITTERWALL_JPA_HIBERNATE_DDL_AUTO=update
@REM set TWITTERWALL_JPA_HIBERNATE_DDL_AUTO=create-drop
set TWITTERWALL_LOGIN_USERNAME=tw
set TWITTERWALL_LOGIN_PASSWORD=vbfvjdgar64r67tf7a46tf76rgtfgf7d6g

@REM psql -U twitterwall2test < etc/drop-tables.sql

@REM psql -c 'DROP DATABASE kandidatentest;' -U postgres
@REM psql -c 'DROP USER kandidatentest;' -U postgres
@REM psql -c 'DROP ROLE kandidatentest;' -U postgres
@REM psql -c "CREATE USER kandidatentest WITH PASSWORD 'kandidatentestpwd' LOGIN SUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION;" -U postgres
@REM psql -c 'GRANT pg_signal_backend, postgres TO kandidatentest WITH ADMIN OPTION;' -U postgres
@REM psql -c "CREATE DATABASE kandidatentest WITH OWNER = kandidatentest TEMPLATE = template1 ENCODING = 'UTF8' LC_COLLATE = 'de_DE.UTF-8' LC_CTYPE = 'de_DE.UTF-8' CONNECTION LIMIT = -1;" -U postgres

psql -c 'select * from version();' -U twitterwall2test
psql -c '\l' -U postgres
psql -c '\dg' -U postgres
psql -c '\dn' -U postgres

mvnw install -DskipTests=true -Dmaven.javadoc.skip=true -B -V
mvnw clean site site:deploy -Ptravis -Dtest=AlphaTopLevelSuiteIT  -B -V

exit 0


text:
import { moduleForComponent, test } from 'ember-qunit'
import hbs from 'htmlbars-inline-precompile'
import { find } from 'ember-native-dom-helpers'

moduleForComponent('primer-group', 'Integration | Component | primer group', {
  integration: true,
})

test('it renders', function(assert) {
  this.render(hbs`
    {{#primer-group}}
      template block text
    {{/primer-group}}
  `)

  assert.equal(find('g').textContent.trim(), 'template block text')
})


text:
<?php

namespace Tienvx\Bundle\MbtBundle\Command\Wait;

use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Tienvx\Bundle\MbtBundle\Model\ValuesInterface;

class WaitForElementNotPresentCommand extends AbstractWaitCommand
{
    public function run(?string $target, ?string $value, ValuesInterface $values, RemoteWebDriver $driver): void
    {
        parent::run($target, $value, $values, $driver);
        $elements = $driver->findElements($this->getSelector($target));
        if (count($elements) > 0) {
            $driver->wait((int) $value)->until(
                WebDriverExpectedCondition::stalenessOf($elements[0])
            );
        }
    }
}


text:
package com.zaren.hometeachinghelper.model;

import android.database.Cursor;
import android.support.annotation.NonNull;

import java.sql.SQLDataException;
import java.util.List;

import lombok.Value;

/**
 * Created by John on 3/7/2015.
 */
@Value
public class HomeTeachingAssignment
{
    private final HomeTeachingSupervisor supervisor;
    private final HomeTeacher homeTeacher1;
    private final HomeTeacher homeTeacher2;
    private final List< Household > households;

    public static Household fromCursor( @NonNull Cursor aCursor ) throws SQLDataException
    {
        if( aCursor.getColumnCount() == 10 )
        {
            return new Household( aCursor.getLong( 0 ),
                                  aCursor.getString( 1 ),
                                  aCursor.getString( 2 ),
                                  aCursor.getString( 3 ),
                                  aCursor.getString( 4 ),
                                  aCursor.getString( 5 ),
                                  aCursor.getString( 6 ),
                                  aCursor.getString( 7 ),
                                  aCursor.getString( 8 ),
                                  aCursor.getString( 9 ) );
        }
        else
        {
            throw new SQLDataException( "Not enough values in cursor to create household" );
        }
    }
}


text:
#ifndef _IDENTT_TOOLS_GETMAIL_HH_
#define _IDENTT_TOOLS_GETMAIL_HH_

#define IDENTT_DEFAULT_EXE_NAME "identt_getmail"
#define IDENTT_DEFAULT_EXE_VERSION "1.0.0"
#define IDENTT_DEFAULT_EXE_COPYRIGHT "Copyright (c) 2017-2018"

#endif


text:
namespace gl {

using ::testing::Exactly;
using ::testing::NotNull;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::SetArgPointee;

class GPUTimingTest : public testing::Test {
 public:
  void SetUp() override {
    setup_ = false;
    cpu_time_bounded_ = false;
  }

  void TearDown() override {
    context_ = nullptr;
    surface_ = nullptr;
    if (setup_) {
      MockGLInterface::SetGLInterface(NULL);
      init::ShutdownGL();
    }
    setup_ = false;
    cpu_time_bounded_ = false;
    gl_.reset();
    gpu_timing_fake_queries_.Reset();
  }

  void SetupGLContext(const char* gl_version, const char* gl_extensions) {
    ASSERT_FALSE(setup_) << "Cannot setup GL context twice.";
    SetGLGetProcAddressProc(MockGLInterface::GetGLProcAddress);
    GLSurfaceTestSupport::InitializeOneOffWithMockBindings();
    gl_.reset(new ::testing::StrictMock<MockGLInterface>());
    MockGLInterface::SetGLInterface(gl_.get());

    context_ = new GLContextStubWithExtensions;
    context_->AddExtensionsString(gl_extensions);
    context_->SetGLVersionString(gl_version);
    surface_ = new GLSurfaceStub;
    context_->MakeCurrent(surface_.get());
    gpu_timing_fake_queries_.Reset();

    setup_ = true;
  }

  scoped_refptr<GPUTimingClient> CreateGPUTimingClient() {
    if (!setup_) {
      SetupGLContext("2.0", "");
    }

    scoped_refptr<GPUTimingClient> client = context_->CreateGPUTimingClient();
    if (!cpu_time_bounded_) {
      client->SetCpuTimeForTesting(base::Bind(&GPUTimingFake::GetFakeCPUTime));
      cpu_time_bounded_ = true;
    }
    return client;
  }

 protected:
  bool setup_ = false;
  bool cpu_time_bounded_ = false;
  std::unique_ptr<::testing::StrictMock<MockGLInterface>> gl_;
  scoped_refptr<GLContextStubWithExtensions> context_;
  scoped_refptr<GLSurfaceStub> surface_;
  GPUTimingFake gpu_timing_fake_queries_;
};

TEST_F(GPUTimingTest, FakeTimerTest) {
  scoped_refptr<GPUTimingClient> gpu_timing_client = CreateGPUTimingClient();

  // Tests that we can properly set fake cpu times.
  gpu_timing_fake_queries_.SetCurrentCPUTime(123);
  EXPECT_EQ(123, gpu_timing_client->GetCurrentCPUTime());

  base::Callback<int64_t(void)> empty;
  gpu_timing_client->SetCpuTimeForTesting(empty);
  EXPECT_NE(123, gpu_timing_client->GetCurrentCPUTime());
}

TEST_F(GPUTimingTest, ForceTimeElapsedQuery) {
  // Test that forcing time elapsed query affects all clients.
  SetupGLContext("3.2", "GL_ARB_timer_query");
  scoped_refptr<GPUTimingClient> client1 = CreateGPUTimingClient();
  EXPECT_FALSE(client1->IsForceTimeElapsedQuery());

  scoped_refptr<GPUTimingClient> client_force = CreateGPUTimingClient();
  EXPECT_FALSE(client1->IsForceTimeElapsedQuery());
  client_force->ForceTimeElapsedQuery();
  EXPECT_TRUE(client1->IsForceTimeElapsedQuery());

  EXPECT_TRUE(client1->IsForceTimeElapsedQuery());

  scoped_refptr<GPUTimingClient> client2 = CreateGPUTimingClient();
  EXPECT_TRUE(client2->IsForceTimeElapsedQuery());
}

TEST_F(GPUTimingTest, QueryTimeStampTest) {
  SetupGLContext("3.2", "GL_ARB_timer_query");
  scoped_refptr<GPUTimingClient> client = CreateGPUTimingClient();
  std::unique_ptr<GPUTimer> gpu_timer = client->CreateGPUTimer(false);

  const int64_t begin_cpu_time = 1230;
  const int64_t begin_gl_time = 10 * base::Time::kNanosecondsPerMicrosecond;
  const int64_t cpu_gl_offset =
      begin_gl_time / base::Time::kNanosecondsPerMicrosecond - begin_cpu_time;
  gpu_timing_fake_queries_.SetCPUGLOffset(cpu_gl_offset);
  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time);
  gpu_timing_fake_queries_.ExpectGPUTimeStampQuery(*gl_, false);

  gpu_timer->QueryTimeStamp();

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time - 1);
  EXPECT_FALSE(gpu_timer->IsAvailable());

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time);
  EXPECT_TRUE(gpu_timer->IsAvailable());

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time + 1);
  EXPECT_TRUE(gpu_timer->IsAvailable());

  EXPECT_EQ(0, gpu_timer->GetDeltaElapsed());

  int64_t start, end;
  gpu_timer->GetStartEndTimestamps(&start, &end);
  EXPECT_EQ(begin_cpu_time, start);
  EXPECT_EQ(begin_cpu_time, end);
}

TEST_F(GPUTimingTest, QueryTimeStampUsingElapsedTest) {
  // Test timestamp queries using GL_EXT_timer_query which does not support
  // timestamp queries. Internally we fall back to time elapsed queries.
  SetupGLContext("3.2", "GL_EXT_timer_query");
  scoped_refptr<GPUTimingClient> client = CreateGPUTimingClient();
  std::unique_ptr<GPUTimer> gpu_timer = client->CreateGPUTimer(false);
  ASSERT_TRUE(client->IsForceTimeElapsedQuery());

  const int64_t begin_cpu_time = 123;
  const int64_t begin_gl_time = 10 * base::Time::kNanosecondsPerMicrosecond;
  const int64_t cpu_gl_offset = begin_gl_time - begin_cpu_time;
  gpu_timing_fake_queries_.SetCPUGLOffset(cpu_gl_offset);
  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time);
  gpu_timing_fake_queries_.ExpectGPUTimeStampQuery(*gl_, true);

  gpu_timer->QueryTimeStamp();

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time - 1);
  EXPECT_FALSE(gpu_timer->IsAvailable());

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time + 1);
  EXPECT_TRUE(gpu_timer->IsAvailable());
  EXPECT_EQ(0, gpu_timer->GetDeltaElapsed());

  int64_t start, end;
  gpu_timer->GetStartEndTimestamps(&start, &end);
  EXPECT_EQ(begin_cpu_time, start);
  EXPECT_EQ(begin_cpu_time, end);
}

TEST_F(GPUTimingTest, QueryTimestampUsingElapsedARBTest) {
  // Test timestamp queries on platforms with GL_ARB_timer_query but still lack
  // support for timestamp queries
  SetupGLContext("3.2", "GL_ARB_timer_query");
  scoped_refptr<GPUTimingClient> client = CreateGPUTimingClient();
  std::unique_ptr<GPUTimer> gpu_timer = client->CreateGPUTimer(false);

  const int64_t begin_cpu_time = 123;
  const int64_t begin_gl_time = 10 * base::Time::kNanosecondsPerMicrosecond;
  const int64_t cpu_gl_offset = begin_gl_time - begin_cpu_time;
  gpu_timing_fake_queries_.SetCPUGLOffset(cpu_gl_offset);
  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time);

  gpu_timing_fake_queries_.ExpectGPUTimeStampQuery(*gl_, true);

  // Custom mock override to ensure the timestamp bits are 0
  EXPECT_CALL(*gl_, GetQueryiv(GL_TIMESTAMP, GL_QUERY_COUNTER_BITS, NotNull()))
      .Times(Exactly(1))
      .WillRepeatedly(DoAll(SetArgPointee<2>(0), Return()));

  gpu_timer->QueryTimeStamp();

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time - 1);
  EXPECT_FALSE(gpu_timer->IsAvailable());

  gpu_timing_fake_queries_.SetCurrentCPUTime(begin_cpu_time + 1);
  EXPECT_TRUE(gpu_timer->IsAvailable());
  EXPECT_EQ(0, gpu_timer->GetDeltaElapsed());

  int64_t start, end;
  gpu_timer->GetStartEndTimestamps(&start, &end);
  // Force time elapsed won't be set until a query is actually attempted
  ASSERT_TRUE(client->IsForceTimeElapsedQuery());
  EXPECT_EQ(begin_cpu_time, start);
  EXPECT_EQ(begin_cpu_time, end);
}

}  // namespace gl


text:
#include "vislib/ArrayAllocator.h"

/*
 * This file is intentionally empty.
 */


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

var app = express();

app.use(express.static(__dirname));
app.use('/js', express.static(path.join(__dirname, '../dist')));
app.use('/angular', express.static(path.join(__dirname, '../node_modules/angular-recursion')));

app.listen(process.env.PORT || 3000, function() {
  console.log('listening on ' + ( process.env.PORT || 3000));
});


text:
package dotty.tools
package dotc
package core
package classfile

import scala.language.unsafeNulls

import dotty.tools.tasty.{ TastyReader, TastyHeaderUnpickler }

import Contexts._, Symbols._, Types._, Names._, StdNames._, NameOps._, Scopes._, Decorators._
import SymDenotations._, unpickleScala2.Scala2Unpickler._, Constants._, Annotations._, util.Spans._
import Phases._
import ast.{ tpd, untpd }
import ast.tpd._, util._
import java.io.{ ByteArrayOutputStream, IOException }

import java.lang.Integer.toHexString
import java.util.UUID

import scala.collection.immutable
import scala.collection.mutable.{ ListBuffer, ArrayBuffer }
import scala.annotation.switch
import typer.Checking.checkNonCyclic
import io.{AbstractFile, ZipArchive}
import scala.util.control.NonFatal
import language.experimental.pureFunctions

object ClassfileParser {
  /** Marker trait for unpicklers that can be embedded in classfiles. */
  trait Embedded

  /** Indicate that there is nothing to unpickle and the corresponding symbols can
    * be invalidated. */
  object NoEmbedded extends Embedded

  /** Replace raw types with wildcard applications */
  def cook(using Context): TypeMap = new TypeMap {
    def apply(tp: Type): Type = tp match {
      case tp: TypeRef if tp.symbol.typeParams.nonEmpty =>
        AppliedType(tp, tp.symbol.typeParams.map(Function.const(TypeBounds.empty)))
      case tp @ AppliedType(tycon, args) =>
        // disregard tycon itself, but map over it to visit the prefix
        tp.derivedAppliedType(mapOver(tycon), args.mapConserve(this))
      case tp @ TempPolyType(_, tpe) =>
        val tpe1 = this(tpe)
        if (tpe1 eq tpe) tp else tp.copy(tpe = tpe1)
      case tp @ TempClassInfoType(parents, _, _) =>
        val parents1 = parents.mapConserve(this)
        if (parents eq parents1) tp else tp.copy(parentTypes = parents1)
      case _ =>
        mapOver(tp)
    }
  }
}

class ClassfileParser(
    classfile: AbstractFile,
    classRoot: ClassDenotation,
    moduleRoot: ClassDenotation)(ictx: Context) {

  import ClassfileConstants._
  import ClassfileParser._

  protected val staticModule: Symbol = moduleRoot.sourceModule(using ictx)

  protected val instanceScope: MutableScope = newScope(0)     // the scope of all instance definitions
  protected val staticScope: MutableScope = newScope(0)       // the scope of all static definitions
  protected var pool: ConstantPool = _              // the classfile's constant pool

  protected var currentClassName: SimpleName = _      // JVM name of the current class
  protected var classTParams: Map[Name, Symbol] = Map()

  private var Scala2UnpicklingMode = Mode.Scala2Unpickling

  classRoot.info = NoLoader().withDecls(instanceScope)
  moduleRoot.info = NoLoader().withDecls(staticScope).withSourceModule(staticModule)

  private def currentIsTopLevel(using Context) = classRoot.owner.is(Flags.PackageClass)

  private def mismatchError(className: SimpleName) =
    throw new IOException(s"class file '${classfile.canonicalPath}' has location not matching its contents: contains class $className")

  def run()(using Context): Option[Embedded] = try ctx.base.reusableDataReader.withInstance { reader =>
    implicit val reader2 = reader.reset(classfile)
    report.debuglog("[class] >> " + classRoot.fullName)
    parseHeader()
    this.pool = new ConstantPool
    val res = parseClass()
    this.pool =  null
    res
  }
  catch {
    case e: RuntimeException =>
      if (ctx.debug) e.printStackTrace()
      throw new IOException(
        i"""class file ${classfile.canonicalPath} is broken, reading aborted with ${e.getClass}
           |${Option(e.getMessage).getOrElse("")}""")
  }

  private def parseHeader()(using in: DataReader): Unit = {
    val magic = in.nextInt
    if (magic != JAVA_MAGIC)
      throw new IOException(s"class file '${classfile}' has wrong magic number 0x${toHexString(magic)}, should be 0x${toHexString(JAVA_MAGIC)}")
    val minorVersion = in.nextChar.toInt
    val majorVersion = in.nextChar.toInt
    if ((majorVersion < JAVA_MAJOR_VERSION) ||
        ((majorVersion == JAVA_MAJOR_VERSION) &&
         (minorVersion < JAVA_MINOR_VERSION)))
      throw new IOException(
        s"class file '${classfile}' has unknown version $majorVersion.$minorVersion, should be at least $JAVA_MAJOR_VERSION.$JAVA_MINOR_VERSION")
  }

  /** Return the class symbol of the given name. */
  def classNameToSymbol(name: Name)(using Context): Symbol =
    val nameStr = name.toString
    innerClasses.get(nameStr) match
      case Some(entry) => innerClasses.classSymbol(entry)
      case None =>
        def lookupTopLevel(): Symbol = requiredClass(name)
        // For inner classes we usually don't get to this branch: `innerClasses.classSymbol` already returns the symbol
        // of the inner class based on the InnerClass table. However, if the classfile is missing the
        // InnerClass entry for `name`, it might still be that there exists an inner symbol (because
        // some other classfile _does_ have an InnerClass entry for `name`). In this case, we want to
        // return the actual inner symbol (C.D, with owner C), not the top-level symbol C$D. This is
        // what the logic below is for (see scala/bug#9937 / lampepfl/dotty#12086).
        val split = nameStr.lastIndexOf('$')
        if split < 0 || split >= nameStr.length - 1 then
          lookupTopLevel()
        else
          val outerNameStr = nameStr.substring(0, split)
          val innerNameStr = nameStr.substring(split + 1, nameStr.length)
          val outerSym = classNameToSymbol(outerNameStr.toTypeName)
          outerSym.denot.infoOrCompleter match
            case _: StubInfo =>
              // If the outer class C cannot be found, look for a top-level class C$D
              lookupTopLevel()
            case _ =>
              // We have a java-defined class name C$D and look for a member D of C. But we don't know if
              // D is declared static or not, so we have to search both in class C and its companion.
              val innerName = innerNameStr.toTypeName
              val r =
                if outerSym eq classRoot.symbol then
                  instanceScope.lookup(innerName).orElse(staticScope.lookup(innerName))
                else
                  outerSym.info.member(innerName).orElse(outerSym.asClass.companionModule.info.member(innerName)).symbol
              r.orElse(lookupTopLevel())

  var sawPrivateConstructor: Boolean = false

  def parseClass()(using ctx: Context, in: DataReader): Option[Embedded] = {
    val jflags       = in.nextChar
    val isAnnotation = hasAnnotation(jflags)
    val sflags       = classTranslation.flags(jflags)
    val isEnum       = (jflags & JAVA_ACC_ENUM) != 0
    val nameIdx      = in.nextChar
    currentClassName = pool.getClassName(nameIdx).name

    if (currentIsTopLevel &&
        currentClassName != classRoot.fullName.toSimpleName &&
        currentClassName != classRoot.fullName.encode.toSimpleName)
      mismatchError(currentClassName)

    addEnclosingTParams()

    /** Parse parents for Java classes. For Scala, return AnyRef, since the real type will be unpickled.
     *  Updates the read pointer of 'in'. */
    def parseParents: List[Type] = {
      val superType =
        if (classRoot.symbol == defn.ComparableClass ||
                 classRoot.symbol == defn.JavaCloneableClass ||
                 classRoot.symbol == defn.JavaSerializableClass) {
          // Treat these interfaces as universal traits
          in.nextChar
          defn.AnyType
        }
        else
          pool.getSuperClass(in.nextChar).typeRef
      val ifaceCount = in.nextChar
      var ifaces = for (i <- (0 until ifaceCount).toList) yield pool.getSuperClass(in.nextChar).typeRef
        // Dotty deviation: was
        //    var ifaces = for (i <- List.range(0, ifaceCount)) ...
        // This does not typecheck because the type parameter of List is now lower-bounded by Int | Char.
        // Consequently, no best implicit for the "Integral" evidence parameter of "range"
        // is found. Previously, this worked because of weak conformance, which has been dropped.

      superType :: ifaces
    }

    val result = unpickleOrParseInnerClasses()
    if (!result.isDefined) {
      var classInfo: Type = TempClassInfoType(parseParents, instanceScope, classRoot.symbol)
      // might be reassigned by later parseAttributes
      val staticInfo = TempClassInfoType(List(), staticScope, moduleRoot.symbol)

      enterOwnInnerClasses()

      classRoot.setFlag(sflags)
      moduleRoot.setFlag(Flags.JavaDefined | Flags.ModuleClassCreationFlags)

      val privateWithin = getPrivateWithin(jflags)

      classRoot.setPrivateWithin(privateWithin)
      moduleRoot.setPrivateWithin(privateWithin)
      moduleRoot.sourceModule.setPrivateWithin(privateWithin)

      for (i <- 0 until in.nextChar) parseMember(method = false)
      for (i <- 0 until in.nextChar) parseMember(method = true)

      classRoot.registerCompanion(moduleRoot.symbol)
      moduleRoot.registerCompanion(classRoot.symbol)

      setClassInfo(moduleRoot, staticInfo, fromScala2 = false)

      classInfo = parseAttributes(classRoot.symbol).complete(classInfo)
      if (isAnnotation)
        // classInfo must be a TempClassInfoType and not a TempPolyType,
        // because Java annotations cannot have type parameters.
        addAnnotationConstructor(classInfo.asInstanceOf[TempClassInfoType])

      setClassInfo(classRoot, classInfo, fromScala2 = false)
      NamerOps.addConstructorProxies(moduleRoot.classSymbol)
    }
    else if (result == Some(NoEmbedded))
      for (sym <- List(moduleRoot.sourceModule, moduleRoot.symbol, classRoot.symbol)) {
        classRoot.owner.asClass.delete(sym)
        sym.markAbsent()
      }

    result
  }

  /** Add type parameters of enclosing classes */
  def addEnclosingTParams()(using Context): Unit = {
    var sym = classRoot.owner
    while (sym.isClass && !sym.is(Flags.ModuleClass)) {
      for (tparam <- sym.typeParams)
        classTParams = classTParams.updated(tparam.name, tparam)
      sym = sym.owner
    }
  }

  def parseMember(method: Boolean)(using ctx: Context, in: DataReader): Unit = {
    val start = indexCoord(in.bp)
    val jflags = in.nextChar
    val sflags =
      if (method) Flags.Method | methodTranslation.flags(jflags)
      else fieldTranslation.flags(jflags)
    val preName = pool.getName(in.nextChar)
    if (!sflags.isOneOf(Flags.PrivateOrArtifact) || preName.name == nme.CONSTRUCTOR) {
      val sig = pool.getExternalName(in.nextChar).value
      val completer = MemberCompleter(preName.name, jflags, sig)
      val member = newSymbol(
        getOwner(jflags), preName.name, sflags, completer,
        getPrivateWithin(jflags), coord = start)

      completer.attrCompleter = parseAttributes(member)

      getScope(jflags).enter(member)

    }
    else {
      in.nextChar // info
      skipAttributes()
    }
  }

  class MemberCompleter(name: SimpleName, jflags: Int, sig: String) extends LazyType {
    var attrCompleter: AttributeCompleter = null

    def complete(denot: SymDenotation)(using Context): Unit = {
      val sym = denot.symbol
      val isEnum = (jflags & JAVA_ACC_ENUM) != 0
      val isNative = (jflags & JAVA_ACC_NATIVE) != 0
      val isTransient = (jflags & JAVA_ACC_TRANSIENT) != 0
      val isVolatile = (jflags & JAVA_ACC_VOLATILE) != 0
      val isConstructor = name eq nme.CONSTRUCTOR

      /** Strip leading outer param from constructor and trailing access tag for
        *  private inner constructors.
        */
      def normalizeConstructorParams() = innerClasses.get(currentClassName.toString) match {
        case Some(entry) if !isStatic(entry.jflags) =>
          val mt @ MethodTpe(paramNames, paramTypes, resultType) = denot.info: @unchecked
          var normalizedParamNames = paramNames.tail
          var normalizedParamTypes = paramTypes.tail
          if ((jflags & JAVA_ACC_SYNTHETIC) != 0) {
            // SI-7455 strip trailing dummy argument ("access constructor tag") from synthetic constructors which
            // are added when an inner class needs to access a private constructor.
            normalizedParamNames = paramNames.dropRight(1)
            normalizedParamTypes = paramTypes.dropRight(1)
          }
          denot.info = mt.derivedLambdaType(normalizedParamNames, normalizedParamTypes, resultType)
        case _ =>
      }

      /** Make return type of constructor be the enclosing class type,
        *  and make constructor type polymorphic in the type parameters of the class
        */
      def normalizeConstructorInfo() = {
        val rt = classRoot.typeRef appliedTo (classRoot.typeParams map (_.typeRef))

        def resultType(tpe: Type): Type = tpe match {
          case mt @ MethodType(paramNames) => mt.derivedLambdaType(paramNames, mt.paramInfos, rt)
          case pt : PolyType => pt.derivedLambdaType(pt.paramNames, pt.paramInfos, resultType(pt.resType))
        }

        denot.info = resultType(denot.info)
        addConstructorTypeParams(denot)
      }

      val isVarargs = denot.is(Flags.Method) && (jflags & JAVA_ACC_VARARGS) != 0
      denot.info = sigToType(sig, isVarargs = isVarargs)
      if (isConstructor) normalizeConstructorParams()
      if isNative then
        attrCompleter.annotations ::= Annotation.deferredSymAndTree(defn.NativeAnnot)(New(defn.NativeAnnot.typeRef, Nil))
      if isTransient then
        attrCompleter.annotations ::= Annotation.deferredSymAndTree(defn.TransientAnnot)(New(defn.TransientAnnot.typeRef, Nil))
      if isVolatile then
        attrCompleter.annotations ::= Annotation.deferredSymAndTree(defn.VolatileAnnot)(New(defn.VolatileAnnot.typeRef, Nil))
      denot.info = translateTempPoly(attrCompleter.complete(denot.info, isVarargs))
      if (isConstructor) normalizeConstructorInfo()

      if (ctx.explicitNulls) denot.info = JavaNullInterop.nullifyMember(denot.symbol, denot.info, isEnum)

      // seal java enums
      if (isEnum) {
        val enumClass = sym.owner.linkedClass
        if (!enumClass.exists)
          report.warning(s"no linked class for java enum $sym in ${sym.owner}. A referencing class file might be missing an InnerClasses entry.")
        else {
          if (!enumClass.is(Flags.Sealed)) enumClass.setFlag(Flags.AbstractSealed)
          enumClass.addAnnotation(Annotation.Child(sym, NoSpan))
        }
      }

    }
  }

  def constantTagToType(tag: Int)(using Context): Type =
    (tag: @switch) match {
      case BYTE_TAG   => defn.ByteType
      case CHAR_TAG   => defn.CharType
      case DOUBLE_TAG => defn.DoubleType
      case FLOAT_TAG  => defn.FloatType
      case INT_TAG    => defn.IntType
      case LONG_TAG   => defn.LongType
      case SHORT_TAG  => defn.ShortType
      case VOID_TAG   => defn.UnitType
      case BOOL_TAG   => defn.BooleanType
    }

  /** As specified in https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.16.1,
   *  an annotation argument of type boolean, byte, char or short will
   *  be represented as a CONSTANT_INTEGER, so we need to convert it to
   *  produce a correctly-typed tree. We need to do this each time the
   *  constant is accessed instead of storing the result of the
   *  conversion in the `values` cache, because the same constant might
   *  be used for annotation arguments of different type.
   */
  def convertTo(ct: Constant, pt: Type)(using Context): Constant = {
    if (pt eq defn.BooleanType) && ct.tag == IntTag then
      Constant(ct.value != 0)
    else
      ct.convertTo(pt)
  }

  private def sigToType(sig: String, owner: Symbol = null, isVarargs: Boolean = false)(using Context): Type = {
    var index = 0
    val end = sig.length
    def accept(ch: Char): Unit = {
      assert(sig(index) == ch, (sig(index), ch))
      index += 1
    }
    def subName(isDelimiter: Char => Boolean): SimpleName = {
      val start = index
      while (!isDelimiter(sig(index))) { index += 1 }
      termName(sig.slice(start, index))
    }
    // Warning: sigToType contains nested completers which might be forced in a later run!
    // So local methods need their own ctx parameters.
    def sig2type(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(using Context): Type = {
      val tag = sig(index); index += 1
      (tag: @switch) match {
        case 'L' =>
          /** A type representation where inner classes become `A#B` instead of `A.this.B` (like with `typeRef`)
           *
           *  Note: the symbol must not be nested in a generic class.
           */
          def innerType(symbol: Symbol): Type =
            if symbol.is(Flags.Package) then
              symbol.thisType
            else if symbol.isType then
              TypeRef(innerType(symbol.owner), symbol)
            else
              throw new RuntimeException("unexpected term symbol " + symbol)

          def processTypeArgs(tp: Type): Type = tp match {
            case tp: TypeRef =>
              if (sig(index) == '<') {
                accept('<')
                val argsBuf = if (skiptvs) null else new ListBuffer[Type]
                while (sig(index) != '>') {
                  val arg = sig(index) match {
                    case variance @ ('+' | '-' | '*') =>
                      index += 1
                      variance match {
                        case '+' => TypeBounds.upper(sig2type(tparams, skiptvs))
                        case '-' =>
                          val argTp = sig2type(tparams, skiptvs)
                          // Interpret `sig2type` returning `Any` as "no bounds";
                          // morally equivalent to TypeBounds.empty, but we're representing Java code, so use FromJavaObjectType as the upper bound
                          if (argTp.typeSymbol == defn.AnyClass) TypeBounds.upper(defn.FromJavaObjectType)
                          else TypeBounds(argTp, defn.FromJavaObjectType)
                        case '*' => TypeBounds.upper(defn.FromJavaObjectType)
                      }
                    case _ => sig2type(tparams, skiptvs)
                  }
                  if (argsBuf != null) argsBuf += arg
                }
                accept('>')
                if (skiptvs) tp else AppliedType(tp, argsBuf.toList)
              }
              else tp
            case tp =>
              assert(sig(index) != '<', tp)
              tp
          }

          val classSym = classNameToSymbol(subName(c => c == ';' || c == '<'))
          val classTpe = if (classSym eq defn.ObjectClass) defn.FromJavaObjectType else innerType(classSym)
          var tpe = processTypeArgs(classTpe)
          while (sig(index) == '.') {
            accept('.')
            val name = subName(c => c == ';' || c == '<' || c == '.').toTypeName
            val tp = tpe.select(name)
            tpe = processTypeArgs(tp)
          }
          accept(';')
          tpe
        case ARRAY_TAG =>
          while ('0' <= sig(index) && sig(index) <= '9') index += 1
          val elemtp = sig2type(tparams, skiptvs)
          defn.ArrayOf(elemtp.translateJavaArrayElementType)
        case '(' =>
          def isMethodEnd(i: Int) = sig(i) == ')'
          def isArray(i: Int) = sig(i) == '['

          /** Is this a repeated parameter type?
           *  This is true if we're in a vararg method and this is the last parameter.
           */
          def isRepeatedParam(i: Int): Boolean =
            if !isVarargs then return false
            var cur = i
            // Repeated parameters are represented as arrays
            if !isArray(cur) then return false
            // Handle nested arrays: int[]...
            while isArray(cur) do
              cur += 1
            // Simple check to see if we're the last parameter: there should be no
            // array in the signature until the method end.
            while !isMethodEnd(cur) do
              if isArray(cur) then return false
              cur += 1
            true
          end isRepeatedParam

          val paramtypes = new ListBuffer[Type]()
          var paramnames = new ListBuffer[TermName]()
          while !isMethodEnd(index) do
            paramnames += nme.syntheticParamName(paramtypes.length)
            paramtypes += {
              if isRepeatedParam(index) then
                index += 1
                val elemType = sig2type(tparams, skiptvs = false)
                // `ElimRepeated` is responsible for correctly erasing this.
                defn.RepeatedParamType.appliedTo(elemType)
              else
                sig2type(tparams, skiptvs = false)
            }

          index += 1
          val restype = sig2type(tparams, skiptvs = false)
          MethodType(paramnames.toList, paramtypes.toList, restype)
        case 'T' =>
          val n = subName(';'.==).toTypeName
          index += 1
          //assert(tparams contains n, s"classTparams = $classTParams, tparams = $tparams, key = $n")
          if (skiptvs) defn.AnyType else tparams(n).typeRef
        case tag =>
          constantTagToType(tag)
      }
    }
    // sig2type(tparams, skiptvs)

    def sig2typeBounds(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(using Context): Type = {
      val ts = new ListBuffer[Type]
      while (sig(index) == ':') {
        index += 1
        if (sig(index) != ':') { // guard against empty class bound
          val tp = sig2type(tparams, skiptvs)
          if (!skiptvs)
            ts += cook(tp)
        }
      }
      if (!skiptvs) {
        val bound = if ts.isEmpty then defn.AnyType else ts.reduceLeft(AndType.apply)
        TypeBounds.upper(bound)
      }
      else NoType
    }

    var tparams = classTParams

    def typeParamCompleter(start: Int) = new LazyType {
      def complete(denot: SymDenotation)(using Context): Unit = {
        val savedIndex = index
        try {
          index = start
          denot.info =
            checkNonCyclic( // we need the checkNonCyclic call to insert LazyRefs for F-bounded cycles
                denot.symbol,
                sig2typeBounds(tparams, skiptvs = false),
                reportErrors = false)
        }
        finally
          index = savedIndex
      }
    }

    val newTParams = new ListBuffer[Symbol]()
    if (sig(index) == '<') {
      assert(owner != null)
      index += 1
      val start = index
      while (sig(index) != '>') {
        val tpname = subName(':'.==).toTypeName
        val s = newSymbol(
          owner, tpname, owner.typeParamCreationFlags,
          typeParamCompleter(index), coord = indexCoord(index))
        if (owner.isClass) owner.asClass.enter(s)
        tparams = tparams + (tpname -> s)
        sig2typeBounds(tparams, skiptvs = true)
        newTParams += s
      }
      index += 1
    }
    val ownTypeParams = newTParams.toList.asInstanceOf[List[TypeSymbol]]
    val tpe =
      if ((owner == null) || !owner.isClass)
        sig2type(tparams, skiptvs = false)
      else {
        classTParams = tparams
        val parents = new ListBuffer[Type]()
        while (index < end)
          parents += sig2type(tparams, skiptvs = false) // here the variance doesn't matter
        TempClassInfoType(parents.toList, instanceScope, owner)
      }
    if (ownTypeParams.isEmpty) tpe else TempPolyType(ownTypeParams, tpe)
  }
  // sigToType

  class EnumTag(sig: String, name: NameOrString) {
    def toTree(using ctx: Context): untpd.Tree = {
      val enumClassTp = sigToType(sig)
      val enumModuleClass = enumClassTp.classSymbol.companionModule
      val tmref = TermRef(enumModuleClass.termRef, name.name)
      untpd.TypedSplice(ref(tmref))
    }
  }

  def parseAnnotArg(skip: Boolean = false)(using ctx: Context, in: DataReader): Option[untpd.Tree | EnumTag] = {

    // If we encounter an empty array literal, we need the type of the corresponding
    // parameter to properly type it, but that would require forcing the annotation
    // early. To avoid this we store annotation arguments as untyped trees

    // ... but constants need to actually be typed with a ConstantType, so we
    // can't rely on type inference, and type them early.
    def lit(c: Constant): untpd.Tree = untpd.TypedSplice(tpd.Literal(c))

    val tag = in.nextByte.toChar
    val index = in.nextChar

    tag match {
      case STRING_TAG =>
        if (skip) None else Some(lit(Constant(pool.getName(index).value)))
      case BOOL_TAG | BYTE_TAG | CHAR_TAG | SHORT_TAG =>
        if (skip) None else {
          val constant = convertTo(pool.getConstant(index), constantTagToType(tag))
          Some(lit(constant))
        }
      case INT_TAG | LONG_TAG | FLOAT_TAG | DOUBLE_TAG =>
        if (skip) None else Some(lit(pool.getConstant(index)))
      case CLASS_TAG =>
        if (skip) None else Some(lit(Constant(pool.getType(index))))
      case ENUM_TAG =>
        val sig = pool.getExternalName(index).value
        val enumCaseName = pool.getName(in.nextChar)
        if (skip) None else Some(EnumTag(sig, enumCaseName))
      case ARRAY_TAG =>
        val arr = new ArrayBuffer[untpd.Tree]()
        var hasError = false
        for (i <- 0 until index)
          parseAnnotArg(skip) match {
            case Some(c: untpd.Tree) => arr += c
            case Some(tag: EnumTag) => arr += tag.toTree
            case None => hasError = true
          }
        if (hasError) None
        else if (skip) None
        else {
          val elems = arr.toList
          Some(untpd.JavaSeqLiteral(elems, untpd.TypeTree()))
        }
      case ANNOTATION_TAG =>
        parseAnnotation(index, skip).map(_.untpdTree)
    }
  }

  class ClassfileAnnotation(annotType: Type, lazyArgs: List[(NameOrString, untpd.Tree | EnumTag)]) extends LazyAnnotation {
    private def args(using Context): List[untpd.Tree] =
      lazyArgs.map {
        case (name, tree: untpd.Tree) => untpd.NamedArg(name.name, tree).withSpan(NoSpan)
        case (name, tag: EnumTag)     => untpd.NamedArg(name.name, tag.toTree).withSpan(NoSpan)
      }

    protected var mySym: Symbol | (Context ?-> Symbol) =
      (ctx: Context) ?=> annotType.classSymbol

    protected var myTree: Tree | (Context ?-> Tree) =
      (ctx: Context) ?=> untpd.resolveConstructor(annotType, args)

    def untpdTree(using Context): untpd.Tree =
      untpd.New(untpd.TypeTree(annotType), List(args))
  }

  /** Parse and return a single annotation.  If it is malformed,
   *  return None.
   */
  def parseAnnotation(attrNameIndex: Char, skip: Boolean = false)(using ctx: Context, in: DataReader): Option[ClassfileAnnotation] = try {
    val attrType = pool.getType(attrNameIndex.toInt)
    val nargs = in.nextChar.toInt
    val argbuf = new ListBuffer[(NameOrString, untpd.Tree | EnumTag)]
    var hasError = false
    for (i <- 0 until nargs) {
      val name = pool.getName(in.nextChar)
      parseAnnotArg(skip) match {
        case Some(arg) =>
          argbuf += name -> arg

        case None =>
          hasError = !skip
      }
    }
    attrType match
      case tp: TypeRef if tp.denot.infoOrCompleter.isInstanceOf[StubInfo] =>
        // Silently ignore missing annotation classes like javac
        if ctx.debug then
          report.warning(i"Error while parsing annotations in ${classfile}: annotation class $tp not present on classpath")
        None
      case _ =>
        if (hasError || skip) None
        else Some(ClassfileAnnotation(attrType, argbuf.toList))
  }
  catch {
    case f: FatalError => throw f // don't eat fatal errors, they mean a class was not found
    case NonFatal(ex) =>
      // We want to be robust when annotations are unavailable, so the very least
      // we can do is warn the user about the exception
      // There was a reference to ticket 1135, but that is outdated: a reference to a class not on
      // the classpath would *not* end up here. A class not found is signaled
      // with a `FatalError` exception, handled above. Here you'd end up after a NPE (for example),
      // and that should never be swallowed silently.
      report.warning("Caught: " + ex + " while parsing annotations in " + classfile)
      if (ctx.debug) ex.printStackTrace()

      None // ignore malformed annotations
  }

  /** A completer for attributes
   *
   *  Top-level classes complete attributes eagerly, while members complete lazily.
   *
   *  @note We cannot simply store the bytes of attributes, as the bytes may
   *  contain references to the constant pool, where the constants are loaded
   *  lazily.
   */
  class AttributeCompleter(sym: Symbol) {
    var sig: String = null
    var constant: Constant = null
    var exceptions: List[NameOrString] = Nil
    var annotations: List[Annotation] = Nil
    var namedParams: Map[Int, TermName] = Map.empty
    def complete(tp: Type, isVarargs: Boolean = false)(using Context): Type = {
      val updatedType =
        if sig == null then tp
        else {
          val newType = sigToType(sig, sym, isVarargs)
          if (ctx.debug && ctx.verbose)
            println("" + sym + "; signature = " + sig + " type = " + newType)
          newType
        }

      val newType =
        if this.constant != null then
          val ct = convertTo(this.constant, updatedType)
          if ct != null then ConstantType(ct) else updatedType
        else updatedType

      annotations.foreach(annot => sym.addAnnotation(annot))

      exceptions.foreach { ex =>
        val cls = getClassSymbol(ex.name)
        sym.addAnnotation(ThrowsAnnotation(cls.asClass))
      }

      def fillInParamNames(t: Type): Type = t match
        case mt @ MethodType(oldp) if namedParams.nonEmpty =>
          mt.derivedLambdaType(List.tabulate(oldp.size)(n => namedParams.getOrElse(n, oldp(n))))
        case pt: PolyType if namedParams.nonEmpty =>
          pt.derivedLambdaType(pt.paramNames, pt.paramInfos, fillInParamNames(pt.resultType))
        case _ => t

      cook.apply(fillInParamNames(newType))
    }
  }

  def parseAttributes(sym: Symbol)(using ctx: Context, in: DataReader): AttributeCompleter = {
    val res = new AttributeCompleter(sym)

    def parseAttribute(): Unit = {
      val attrName = pool.getName(in.nextChar).name.toTypeName
      val attrLen = in.nextInt
      val end = in.bp + attrLen
      attrName match {
        case tpnme.SignatureATTR =>
          val sig = pool.getExternalName(in.nextChar)
          res.sig = sig.value

        case tpnme.SyntheticATTR =>
          sym.setFlag(Flags.SyntheticArtifact)

        case tpnme.BridgeATTR =>
          sym.setFlag(Flags.Bridge)

        case tpnme.DeprecatedATTR =>
          val msg = Literal(Constant("see corresponding Javadoc for more information."))
          val since = Literal(Constant(""))
          res.annotations ::= Annotation.deferredSymAndTree(defn.DeprecatedAnnot) {
            New(defn.DeprecatedAnnot.typeRef, msg :: since :: Nil)
          }

        case tpnme.ConstantValueATTR =>
          val c = pool.getConstant(in.nextChar)
          if (c ne null) res.constant = c
          else report.warning(s"Invalid constant in attribute of ${sym.showLocated} while parsing ${classfile}")

        case tpnme.MethodParametersATTR =>
          val paramCount = in.nextByte
          for i <- 0 until paramCount do
            val name = pool.getName(in.nextChar)
            val flags = in.nextChar
            if (flags & JAVA_ACC_SYNTHETIC) == 0 then
              res.namedParams += (i -> name.name)

        case tpnme.AnnotationDefaultATTR =>
          sym.addAnnotation(Annotation(defn.AnnotationDefaultAnnot, Nil))

        // Java annotations on classes / methods / fields with RetentionPolicy.RUNTIME
        case tpnme.RuntimeVisibleAnnotationATTR
          | tpnme.RuntimeInvisibleAnnotationATTR =>
          parseAnnotations(attrLen)

        // TODO 1: parse runtime visible annotations on parameters
        // case tpnme.RuntimeParamAnnotationATTR

        // TODO 2: also parse RuntimeInvisibleParamAnnotation
        // i.e. java annotations with RetentionPolicy.CLASS?

        case tpnme.ExceptionsATTR =>
          parseExceptions(attrLen)

        case tpnme.CodeATTR =>
          in.skip(attrLen)
          // flag test will trigger completion and cycles, thus have to be lazy
          if (sym.owner.flagsUNSAFE.isAllOf(Flags.JavaInterface)) {
            sym.resetFlag(Flags.Deferred)
            sym.owner.resetFlag(Flags.PureInterface)
            report.log(s"$sym in ${sym.owner} is a java 8+ default method.")
          }

        case _ =>
      }
      in.bp = end
    }

    /**
     * Parse the "Exceptions" attribute which denotes the exceptions
     * thrown by a method.
     */
    def parseExceptions(len: Int): Unit = {
      val nClasses = in.nextChar
      for (n <- 0 until nClasses) {
        // FIXME: this performs an equivalent of getExceptionTypes instead of getGenericExceptionTypes (SI-7065)
        val cls = pool.getClassName(in.nextChar.toInt)
        res.exceptions ::= cls
      }
    }

    /** Parse a sequence of annotations and attaches them to the
     *  current symbol sym, except for the ScalaSignature annotation that it returns, if it is available. */
    def parseAnnotations(len: Int): Unit = {
      val nAttr = in.nextChar
      for (n <- 0 until nAttr)
        parseAnnotation(in.nextChar) match {
          case Some(annot) =>
            sym.addAnnotation(annot)
          case None =>
        }
    }

    // begin parseAttributes
    for (i <- 0 until in.nextChar)
      parseAttribute()

    res
  }

  /** Annotations in Scala are assumed to get all their arguments as constructor
   *  parameters. For Java annotations we need to fake it by making up the constructor.
   */
  def addAnnotationConstructor(classInfo: TempClassInfoType)(using Context): Unit =
    newSymbol(
      owner = classRoot.symbol,
      name = nme.CONSTRUCTOR,
      flags = Flags.Synthetic | Flags.JavaDefined | Flags.Method,
      info = new AnnotConstructorCompleter(classInfo)
    ).entered

  class AnnotConstructorCompleter(classInfo: TempClassInfoType) extends LazyType {
    def complete(denot: SymDenotation)(using Context): Unit = {
      val attrs = classInfo.decls.toList.filter(sym => sym.isTerm && sym != denot.symbol && sym.name != nme.CONSTRUCTOR)
      val paramNames = attrs.map(_.name.asTermName)
      val paramTypes = attrs.map(_.info.resultType)
      denot.info = MethodType(paramNames, paramTypes, classRoot.typeRef)
    }
  }

  /** Enter own inner classes in the right scope. It needs the scopes to be set up,
   *  and implicitly current class' superclasses.
   */
  private def enterOwnInnerClasses()(using Context, DataReader): Unit = {
    def enterClassAndModule(entry: InnerClassEntry, file: AbstractFile, jflags: Int) =
      SymbolLoaders.enterClassAndModule(
          getOwner(jflags),
          entry.originalName,
          new ClassfileLoader(file),
          classTranslation.flags(jflags),
          getScope(jflags))

    for entry <- innerClasses.valuesIterator do
      // create a new class member for immediate inner classes
      if entry.outer.name == currentClassName then
        val file = ctx.platform.classPath.findClassFile(entry.externalName.toString) getOrElse {
          throw new AssertionError(entry.externalName)
        }
        enterClassAndModule(entry, file, entry.jflags)
  }

  // Nothing$ and Null$ were incorrectly emitted with a Scala attribute
  // instead of ScalaSignature before 2.13.0-M2, see https://github.com/scala/scala/pull/5952
  private val scalaUnpickleWhitelist = List(tpnme.nothingClass, tpnme.nullClass)

  /** Parse inner classes. Expects `in.bp` to point to the superclass entry.
   *  Restores the old `bp`.
   *  @return Some(unpickler) iff classfile is from Scala, so no Java info needs to be read.
   */
  def unpickleOrParseInnerClasses()(using ctx: Context, in: DataReader): Option[Embedded] = {
    val oldbp = in.bp
    try {
      skipSuperclasses()
      skipMembers() // fields
      skipMembers() // methods
      val attrs = in.nextChar
      val attrbp = in.bp

      def scan(target: TypeName): Boolean = {
        in.bp = attrbp
        var i = 0
        while (i < attrs && pool.getName(in.nextChar).name.toTypeName != target) {
          val attrLen = in.nextInt
          in.skip(attrLen)
          i += 1
        }
        i < attrs
      }

      def unpickleScala(bytes: Array[Byte]): Some[Embedded] = {
        val allowed = ctx.settings.Yscala2Unpickler.value

        def failUnless(cond: Boolean) =
          assert(cond,
            s"Unpickling ${classRoot.symbol.showLocated} from ${classRoot.symbol.associatedFile} is not allowed with -Yscala2-unpickler $allowed")

        if (allowed != "always") {
          failUnless(allowed != "never")
          val allowedList = allowed.split(java.io.File.pathSeparator).toList
          val file = classRoot.symbol.associatedFile
          // Using `.toString.contains` isn't great, but it's good enough for a debug flag.
          failUnless(file == null || allowedList.exists(path => file.toString.contains(path)))
        }

        val unpickler = new unpickleScala2.Scala2Unpickler(bytes, classRoot, moduleRoot)(ctx)
        withMode(Scala2UnpicklingMode)(unpickler.run())
        Some(unpickler)
      }

      def unpickleTASTY(bytes: Array[Byte]): Some[Embedded]  = {
        val unpickler = new tasty.DottyUnpickler(bytes)
        unpickler.enter(roots = Set(classRoot, moduleRoot, moduleRoot.sourceModule))(using ctx.withSource(util.NoSource))
        Some(unpickler)
      }

      def parseScalaSigBytes: Array[Byte] = {
        val tag = in.nextByte.toChar
        assert(tag == STRING_TAG, tag)
        pool getBytes in.nextChar
      }

      def parseScalaLongSigBytes: Array[Byte] = {
        val tag = in.nextByte.toChar
        assert(tag == ARRAY_TAG, tag)
        val stringCount = in.nextChar
        val entries =
          for (i <- 0 until stringCount) yield {
            val stag = in.nextByte.toChar
            assert(stag == STRING_TAG, stag)
            in.nextChar.toInt
          }
        pool.getBytes(entries.toList)
      }

      if (scan(tpnme.TASTYATTR)) {
        val attrLen = in.nextInt
        val bytes = in.nextBytes(attrLen)
        if (attrLen == 16) { // A tasty attribute with that has only a UUID (16 bytes) implies the existence of the .tasty file
          val tastyBytes: Array[Byte] = classfile match { // TODO: simplify when #3552 is fixed
            case classfile: io.ZipArchive#Entry => // We are in a jar
              val path = classfile.parent.lookupName(
                classfile.name.stripSuffix(".class") + ".tasty", directory = false
              )
              if (path != null) {
                val stream = path.input
                try {
                  val tastyOutStream = new ByteArrayOutputStream()
                  val buffer = new Array[Byte](1024)
                  var read = stream.read(buffer, 0, buffer.length)
                  while (read != -1) {
                    tastyOutStream.write(buffer, 0, read)
                    read = stream.read(buffer, 0, buffer.length)
                  }
                  tastyOutStream.flush()
                  tastyOutStream.toByteArray
                } finally {
                  stream.close()
                }
              }
              else {
                report.error(s"Could not find $path in ${classfile.underlyingSource}")
                Array.empty
              }
            case _ =>
              val dir = classfile.container
              val name = classfile.name.stripSuffix(".class") + ".tasty"
              val tastyFileOrNull = dir.lookupName(name, false)
              if (tastyFileOrNull == null) {
                report.error(s"Could not find TASTY file $name under $dir")
                Array.empty
              } else
                tastyFileOrNull.toByteArray
          }
          if (tastyBytes.nonEmpty) {
            val reader = new TastyReader(bytes, 0, 16)
            val expectedUUID = new UUID(reader.readUncompressedLong(), reader.readUncompressedLong())
            val tastyUUID = new TastyHeaderUnpickler(tastyBytes).readHeader()
            if (expectedUUID != tastyUUID)
              report.warning(s"$classfile is out of sync with its TASTy file. Loaded TASTy file. Try cleaning the project to fix this issue", NoSourcePosition)
            return unpickleTASTY(tastyBytes)
          }
        }
        else return unpickleTASTY(bytes)
      }

      if scan(tpnme.ScalaATTR) && !scalaUnpickleWhitelist.contains(classRoot.name)
        && !(classRoot.name.startsWith("Tuple") && classRoot.name.endsWith("$sp"))
        && !(classRoot.name.startsWith("Product") && classRoot.name.endsWith("$sp"))
      then
        // To understand the situation, it's helpful to know that:
        // - Scalac emits the `ScalaSig` attribute for classfiles with pickled information
        // and the `Scala` attribute for everything else.
        // - Dotty emits the `TASTY` attribute for classfiles with pickled information
        // and the `Scala` attribute for _every_ classfile.
        //
        // Therefore, if the `Scala` attribute is present but the `TASTY`
        // attribute isn't, this classfile is a compilation artifact.
        return Some(NoEmbedded)

      if (scan(tpnme.ScalaSignatureATTR) && scan(tpnme.RuntimeVisibleAnnotationATTR)) {
        val attrLen = in.nextInt
        val nAnnots = in.nextChar
        var i = 0
        while (i < nAnnots) {
          val attrClass = pool.getType(in.nextChar).typeSymbol
          val nArgs = in.nextChar
          var j = 0
          while (j < nArgs) {
            val argName = pool.getName(in.nextChar)
            if (argName.name == nme.bytes) {
              if attrClass == defn.ScalaSignatureAnnot then
                return unpickleScala(parseScalaSigBytes)
              else if attrClass == defn.ScalaLongSignatureAnnot then
                return unpickleScala(parseScalaLongSigBytes)
            }
            parseAnnotArg(skip = true)
            j += 1
          }
          i += 1
        }
      }

      if (scan(tpnme.InnerClassesATTR)) {
        val attrLen = in.nextInt
        val entries = in.nextChar.toInt
        for (i <- 0 until entries) {
          val innerIndex = in.nextChar
          val outerIndex = in.nextChar
          val nameIndex = in.nextChar
          val jflags = in.nextChar
          if (innerIndex != 0 && outerIndex != 0 && nameIndex != 0) {
            val inner = pool.getClassName(innerIndex)
            val outer = pool.getClassName(outerIndex)
            val name  = pool.getName(nameIndex)
            val entry = InnerClassEntry(inner, outer, name, jflags)
            innerClasses(inner.value) = entry
          }
        }
      }
      None
    }
    finally in.bp = oldbp
  }

  /** An entry in the InnerClasses attribute of this class file. */
  case class InnerClassEntry(external: NameOrString, outer: NameOrString, name: NameOrString, jflags: Int) {
    def externalName = external.value
    def outerName    = outer.value
    def originalName = name.name

    // The name of the outer class, without its trailing $ if it has one.
    def strippedOuter = outer.name.stripModuleClassSuffix
  }

  private object innerClasses extends util.HashMap[String, InnerClassEntry] {
    /** Return the Symbol of the top level class enclosing `name`,
     *  or 'name's symbol if no entry found for `name`.
     */
    def topLevelClass(name: String)(using Context): Symbol = {
      val tlName = if (contains(name)) {
        var entry = this(name)
        while (contains(entry.outerName))
          entry = this(entry.outerName)
        entry.outerName
      }
      else
        name
      classNameToSymbol(tlName.toTypeName)
    }

    /** Return the class symbol for `entry`. It looks it up in its outer class.
     *  This might force outer class symbols.
     */
    def classSymbol(entry: InnerClassEntry)(using Context): Symbol = {
      def getMember(sym: Symbol, name: Name)(using Context): Symbol =
        if (isStatic(entry.jflags))
          if (sym == classRoot.symbol)
            staticScope.lookup(name)
          else {
            var module = sym.companionModule
            if (!module.exists && sym.isAbsent())
              module = sym.scalacLinkedClass
            module.info.member(name).symbol
          }
        else if (sym == classRoot.symbol)
          instanceScope.lookup(name)
        else if (sym == classRoot.symbol.owner && name == classRoot.name)
          classRoot.symbol
        else
          sym.info.member(name).symbol

      val outerName = entry.strippedOuter
      val innerName = entry.originalName
      val owner = classNameToSymbol(outerName)
      val result = owner.denot.infoOrCompleter match
        case _: StubInfo if hasAnnotation(entry.jflags) =>
          requiredClass(innerName.toTypeName)
            // It's okay for the classfiles of Java annotations to be missing
            // from the classpath. If an annotation is defined as an inner class
            // we need to avoid forcing the outer class symbol here, and instead
            // return a new stub symbol for the inner class. This is tested by
            // `surviveMissingInnerClassAnnot` in AnnotationsTests.scala
        case _ =>
          atPhase(typerPhase)(getMember(owner, innerName.toTypeName))
      assert(result ne NoSymbol,
        i"""failure to resolve inner class:
           |externalName = ${entry.externalName},
           |outerName = $outerName,
           |innerName = $innerName
           |owner.fullName = ${owner.showFullName}
           |while parsing ${classfile}""")
      result
    }
  }

  def skipAttributes()(using in: DataReader): Unit = {
    val attrCount = in.nextChar
    for (i <- 0 until attrCount) {
      in.skip(2); in.skip(in.nextInt)
    }
  }

  def skipMembers()(using in: DataReader): Unit = {
    val memberCount = in.nextChar
    for (i <- 0 until memberCount) {
      in.skip(6); skipAttributes()
    }
  }

  def skipSuperclasses()(using in: DataReader): Unit = {
    in.skip(2) // superclass
    val ifaces = in.nextChar
    in.skip(2 * ifaces)
  }

  protected def getOwner(flags: Int): Symbol =
    if (isStatic(flags)) moduleRoot.symbol else classRoot.symbol

  protected def getScope(flags: Int): MutableScope =
    if (isStatic(flags)) staticScope else instanceScope

  private def getPrivateWithin(jflags: Int)(using Context): Symbol =
    if ((jflags & (JAVA_ACC_PRIVATE | JAVA_ACC_PUBLIC)) == 0)
      classRoot.enclosingPackageClass
    else
      NoSymbol

  private def isPrivate(flags: Int)     = (flags & JAVA_ACC_PRIVATE) != 0
  private def isStatic(flags: Int)      = (flags & JAVA_ACC_STATIC) != 0
  private def hasAnnotation(flags: Int) = (flags & JAVA_ACC_ANNOTATION) != 0

  protected class NameOrString(val value: String) {
    private var _name: SimpleName = null
    def name: SimpleName = {
      if (_name eq null) _name = termName(value)
      _name
    }
  }

  def getClassSymbol(name: SimpleName)(using Context): Symbol =
    if (name.endsWith("$") && (name ne nme.nothingRuntimeClass) && (name ne nme.nullRuntimeClass))
      // Null$ and Nothing$ ARE classes
      requiredModule(name.dropRight(1))
    else classNameToSymbol(name)

  class ConstantPool(using in: DataReader) {
    private val len = in.nextChar
    private val starts = new Array[Int](len)
    private val values = new Array[AnyRef](len)
    private val internalized = new Array[NameOrString](len)

    { var i = 1
      while (i < starts.length) {
        starts(i) = in.bp
        i += 1
        (in.nextByte.toInt: @switch) match {
          case CONSTANT_UTF8 | CONSTANT_UNICODE =>
            in.skip(in.nextChar)
          case CONSTANT_CLASS | CONSTANT_STRING | CONSTANT_METHODTYPE =>
            in.skip(2)
          case CONSTANT_METHODHANDLE =>
            in.skip(3)
          case CONSTANT_FIELDREF | CONSTANT_METHODREF | CONSTANT_INTFMETHODREF
             | CONSTANT_NAMEANDTYPE | CONSTANT_INTEGER | CONSTANT_FLOAT
             | CONSTANT_INVOKEDYNAMIC =>
            in.skip(4)
          case CONSTANT_LONG | CONSTANT_DOUBLE =>
            in.skip(8)
            i += 1
          case _ =>
            errorBadTag(in.bp - 1)
        }
      }
    }

    /** Return the name found at given index. */
    def getName(index: Int)(using in: DataReader): NameOrString = {
      if (index <= 0 || len <= index)
        errorBadIndex(index)

      values(index) match {
        case name: NameOrString => name
        case null   =>
          val start = starts(index)
          if (in.getByte(start).toInt != CONSTANT_UTF8) errorBadTag(start)
          val len   = in.getChar(start + 1).toInt
          val name = new NameOrString(in.getUTF(start + 1, len + 2))
          values(index) = name
          name
      }
    }

    /** Return the name found at given index in the constant pool, with '/' replaced by '.'. */
    def getExternalName(index: Int)(using in: DataReader): NameOrString = {
      if (index <= 0 || len <= index)
        errorBadIndex(index)

      if (internalized(index) == null)
        internalized(index) = new NameOrString(getName(index).value.replace('/', '.'))

      internalized(index)
    }

    def getClassSymbol(index: Int)(using ctx: Context, in: DataReader): Symbol = {
      if (index <= 0 || len <= index) errorBadIndex(index)
      var c = values(index).asInstanceOf[Symbol]
      if (c eq null) {
        val start = starts(index)
        if (in.getByte(start).toInt != CONSTANT_CLASS) errorBadTag(start)
        val name = getExternalName(in.getChar(start + 1))
        c = ClassfileParser.this.getClassSymbol(name.name)
        values(index) = c
      }
      c
    }

    /** Return the external name of the class info structure found at 'index'.
     *  Use 'getClassSymbol' if the class is sure to be a top-level class.
     */
    def getClassName(index: Int)(using in: DataReader): NameOrString = {
      val start = starts(index)
      if (in.getByte(start).toInt != CONSTANT_CLASS) errorBadTag(start)
      getExternalName(in.getChar(start + 1))
    }

    /** Return the type of a class constant entry. Since
     *  arrays are considered to be class types, they might
     *  appear as entries in 'newarray' or 'cast' opcodes.
     */
    def getClassOrArrayType(index: Int)(using ctx: Context, in: DataReader): Type = {
      if (index <= 0 || len <= index) errorBadIndex(index)
      val value = values(index)
      var c: Type = null
      if (value eq null) {
        val start = starts(index)
        if (in.getByte(start).toInt != CONSTANT_CLASS) errorBadTag(start)
        val name = getExternalName(in.getChar(start + 1))
        if (name.value.charAt(0) == ARRAY_TAG) {
          c = sigToType(name.value)
          values(index) = c
        }
        else {
          val sym = classNameToSymbol(name.name)
          values(index) = sym
          c = sym.typeRef
        }
      }
      else c = value match {
          case tp: Type => tp
          case cls: Symbol => cls.typeRef
      }
      c
    }

    def getType(index: Int, isVarargs: Boolean = false)(using Context, DataReader): Type =
      sigToType(getExternalName(index).value, isVarargs = isVarargs)

    def getSuperClass(index: Int)(using Context, DataReader): Symbol = {
      assert(index != 0, "attempt to parse java.lang.Object from classfile")
      getClassSymbol(index)
    }

    def getConstant(index: Int)(using ctx: Context, in: DataReader): Constant = {
      if (index <= 0 || len <= index) errorBadIndex(index)
      var value = values(index)
      if (value eq null) {
        val start = starts(index)
        value = (in.getByte(start).toInt: @switch) match {
          case CONSTANT_STRING =>
            Constant(getName(in.getChar(start + 1).toInt).value)
          case CONSTANT_INTEGER =>
            Constant(in.getInt(start + 1))
          case CONSTANT_FLOAT =>
            Constant(in.getFloat(start + 1))
          case CONSTANT_LONG =>
            Constant(in.getLong(start + 1))
          case CONSTANT_DOUBLE =>
            Constant(in.getDouble(start + 1))
          case CONSTANT_CLASS =>
            getClassOrArrayType(index).typeSymbol
          case _ =>
            errorBadTag(start)
        }
        values(index) = value
      }
      value match {
        case ct: Constant  => ct
        case cls: Symbol   => Constant(cls.typeRef)
        case arr: Type     => Constant(arr)
      }
    }

    private def getSubArray(bytes: Array[Byte]): Array[Byte] = {
      val decodedLength = ByteCodecs.decode(bytes)
      val arr           = new Array[Byte](decodedLength)
      System.arraycopy(bytes, 0, arr, 0, decodedLength)
      arr
    }

    def getBytes(index: Int)(using in: DataReader): Array[Byte] = {
      if (index <= 0 || len <= index) errorBadIndex(index)
      var value = values(index).asInstanceOf[Array[Byte]]
      if (value eq null) {
        val start = starts(index)
        if (in.getByte(start).toInt != CONSTANT_UTF8) errorBadTag(start)
        val len   = in.getChar(start + 1)
        val bytes = new Array[Byte](len)
        in.getBytes(start + 3, bytes)
        value = getSubArray(bytes)
        values(index) = value
      }
      value
    }

    def getBytes(indices: List[Int])(using in: DataReader): Array[Byte] = {
      assert(!indices.isEmpty, indices)
      var value = values(indices.head).asInstanceOf[Array[Byte]]
      if (value eq null) {
        val bytesBuffer = ArrayBuffer.empty[Byte]
        for (index <- indices) {
          if (index <= 0 || ConstantPool.this.len <= index) errorBadIndex(index)
          val start = starts(index)
          if (in.getByte(start).toInt != CONSTANT_UTF8) errorBadTag(start)
          val len = in.getChar(start + 1)
          val buf = new Array[Byte](len)
          in.getBytes(start + 3, buf)
          bytesBuffer ++= buf
        }
        value = getSubArray(bytesBuffer.toArray)
        values(indices.head) = value
      }
      value
    }

    /** Throws an exception signaling a bad constant index. */
    private def errorBadIndex(index: Int)(using in: DataReader) =
      throw new RuntimeException("bad constant pool index: " + index + " at pos: " + in.bp)

    /** Throws an exception signaling a bad tag at given address. */
    private def errorBadTag(start: Int)(using in: DataReader) =
      throw new RuntimeException("bad constant pool tag " + in.getByte(start) + " at byte " + start)
  }
}


text:
/**
 * Module dependencies
 */

var invert = require('burl-invert');
var assert = require('assert');
var burl = require('burl');

/**
 * Prototype.
 */

var hal = Hal.prototype;

/**
 * Exports.
 */

module.exports = Hal;

/**
 * Hal.
 *
 * @param {Object} opts
 * @return {Self}
 * @api public
 */

function Hal(opts) {
  if(!(this instanceof Hal)) return new Hal(opts);

  assert.equal(typeof opts, 'object', 'halster: opts should be an object');

  this._default = opts.default || function(val) {return val};
  this._stash = opts.invert
    ? invert(burl(opts))
    : burl(opts);

  return this;
}

/**
 * Set.
 *
 * @param {object} val
 * @api public
 */

hal.set = function(val) {
  assert.equal(typeof val, 'object', 'halster: val should be an object');

  var links = val.links || val._links;
  if (!links) return;

  var prev = links.previous || links._previous;
  var next = links.next || links._next;

  if (!prev && !next) return;

  if ('object' == typeof prev) prev = prev.url || prev.href;
  if ('object' == typeof next) next = next.url || next.href;

  assert(prev, 'halster: previous could not be extracted from data');
  assert(next, 'halster: next could not be extracted from data');

  this._stash.set({
    previous: prev,
    next: next
  });
};

/**
 * Get.
 *
 * @param {Object} opts
 * @return {String}
 * @api public
 */

hal.get = function(opts) {
  assert(!opts || 'object' == typeof opts, 'halster: opts should be an object');
  opts = opts || {};
  var ln = this._stash.get();

  if (opts.previous) return ln.previous;
  if (opts.next) return ln.next;

  return this._default();
};


text:
<?php
include_once 'faars/misc/util.php';
include_once 'faars/misc/getGameObjectID.php';
include_once 'faars/misc/getGameInstanceID.php';

function checkJSONSecondaryAttribute($gameObject,&$arrayResponse)
{
	$arrayResponse = array();
	$arrayDetails = array();
	$arrayDetails["action"] = "checkJSONSecondaryAttribute";

	$gameObject = json_encode($gameObject);
	$gameObject = json_decode($gameObject,true);
	array_walk_recursive($gameObject, 'trim_value');

	$existsAndNonEmptyArray = array();
	array_push($existsAndNonEmptyArray,"value","active","attributeKey");

	checkJSONByLevel($gameObject, $existsAndNonEmptyArray, $existsAndNonEmptyArray, $arrayResponse);

	if($arrayResponse["status"]!=0)
	{
		return $arrayResponse;
	}

	$arrayResponse = array();
	$arrayResponse["status"] = 0;
	$arrayResponse["details"] = $arrayDetails;
	return $arrayResponse;
}

function addSecondaryAttributeByObjectKey($gameKey,$gameInstanceKey,$gameObjectKey,$gameObject,&$db,&$arrayResponse)
{
	$arrayResponse = array();
	//$gameInstance_ID = 0;
	$arrayDetails = array();
	$arrayDetails["action"] = "addSecondaryAttributeByObjectKey";
	$arrayDetails["objectKey"] = $gameObjectKey;
	$arrayDetails["gameKey"] = $gameKey;
	$arrayDetails["gameInstanceKey"] = $gameInstanceKey;
	$arrayDetails["attributeKey"] = $gameObject->attributeKey;
	try{
	//perform all the checks here...
		checkJSONSecondaryAttribute($gameObject,$arrayResponse);//if all checks were successful
		if($arrayResponse["status"]!=0){
			return $arrayResponse;
		}

		getGameInstanceID($gameInstanceKey,$gameKey,$db,$arrayResponse);

		if($arrayResponse["status"]!=0){
			return $arrayResponse;
		}

		$gameInstance_ID = $arrayResponse["gameInstance_ID"];

		$arrayResponse = array();
		getGameObjectID($gameObjectKey,$gameInstance_ID,$db,$arrayResponse);

		if($arrayResponse["status"]!=0){
			return $arrayResponse;
		}

		$gameObject_ID = $arrayResponse["gameObject_ID"];

		$sql = "INSERT INTO `faars-rocketfuel`.objectAttribute(object_ID,attributeKey,value,active) VALUES(:object_ID,:attributeKey,:value,:active)";
		$stmt = $db->prepare($sql);

		$stmt->bindParam(":object_ID", $gameObject_ID);
		$stmt->bindParam(":attributeKey", $gameObject->attributeKey);
		$stmt->bindParam(":value", $gameObject->value);
		$stmt->bindParam(":active", $gameObject->active);
		$stmt->execute();

		if($stmt->rowCount()!=1)
		{
			$arrayResponse = array();
			$arrayResponse["status"] = 4;
			$arrayResponse["message"] = "Error inserting game object attributes into the database";
			$arrayResponse["details"] = $arrayDetails;
		    return $arrayResponse;
		}

		$arrayResponse = array();
	    $arrayResponse["status"] = 0;
		$arrayResponse["details"] = $arrayDetails;
		return $arrayResponse;

	}catch(PDOException $e) {
		$arrayResponse = array();
		$arrayResponse["status"] = 1;
		$arrayResponse["message"] = $e->getMessage();
		$arrayResponse["details"] = $arrayDetails;
	    return $arrayResponse;
    }

}
?>


text:
class Sprite:

    def reverse_y(self, image_height):
        self.y = str(image_height - int(self.y) - int(self.height))

    def __init__(self, name, x, y, width, height):
        self.name = name
        self.x = x
        self.y = y
        self.width = width
        self.height = height


text:
require 'torch'
require 'cutorch'
require 'cunn'

function table2set(l)
    local a = {}
	local set = {}
    for _, v in ipairs(l) do a[v] = true end
	for key, value in pairs(a) do table.insert(set,key) end

    return set
end

function load_gene2id(gene2id_file)

    local rfile = io.open(gene2id_file, "r")

    gene2id = {}
    feature_dim = 0
	root_id = 0

    for line in rfile:lines() do
        string_array = string_split(line)

		if feature_dim == 0 then
			root_id = tonumber(string_array[2])
		else
        	gene2id[string_array[1]] = tonumber(string_array[2])
        end

		feature_dim = feature_dim + 1
    end

    return gene2id, feature_dim-1, root_id
end

function cal_gene2id(gene_list)
    local gene2id = {}
    for id, gene in ipairs(gene_list) do gene2id[gene] = id end
    return gene2id
end

function list2torch(genotype_list, phenotype_list, gene2id, max_KO)

    local genotype_th = torch.ones(#genotype_list,max_KO+1) * -1
    local phenotype_th = torch.zeros(#genotype_list)

    for i, genotype in ipairs(genotype_list) do

		genotype_th[i][1] = #genotype

		for j, gene in ipairs(genotype) do
			if gene2id[gene] == nil then print('Gene',gene,'does not have index...') os.exit() end
			genotype_th[i][j+1] = gene2id[gene]
        end

        phenotype_th[i] = phenotype_list[i]
    end

    return genotype_th, phenotype_th
end

function pearson(x, y)
    local xx = x - x:mean()
    local yy = y - y:mean()
    return xx:dot(yy) / (xx:norm() * yy:norm())
end

function expand_KO(phenotype_th,feature_num,gene2id)

    local feature = torch.zeros(phenotype_th:size(1),feature_num)

    for i = 1, phenotype_th:size(1) do
		for j = 1, phenotype_th[i][1] do feature[i][phenotype_th[i][j+1]] = 1 end
    end

    return feature:cuda()
end

function string_split(str)

    string_array = {}
    index = 1
    for value in string.gmatch(str,"[^%s]+") do
        string_array[index] = value
        index = index + 1
    end

    return string_array
end

function load_GI_file(GI_file)

    local rfile = io.open(GI_file, "r")
    assert(rfile)

    genotype_list = {}
    phenotype_list = {}
	max_KO_num = -1

    for line in rfile:lines() do

		string_array = string_split(line)

		KO_num = tonumber(string_array[1])

		if KO_num > max_KO_num then max_KO_num = KO_num end

		genotype = {}
		for i = 1,KO_num do genotype[i] = string_array[i+1] end

		table.insert(genotype_list, genotype)

		if #string_array > KO_num + 1 then table.insert(phenotype_list, tonumber(string_array[2+KO_num])) end

    end

    rfile:close()

    return genotype_list, phenotype_list, max_KO_num
end

function load_ontology_file(topo_file)

    local rfile = io.open(topo_file, "r")
    assert(rfile)

    local children_term_map = {};local children_gene_map = {};local term_size_map = {};local term_list = {};local gene_list = {}

    while true do

        local line = rfile:read()

        if line == nil then break end

        string_array = string_split(line)

        local term_name = string_array[2]
		local gene_num = string_array[3]

        table.insert(term_list,term_name)

        line = rfile:read()

        string_array = string_split(line)

        children_gene_list = {}
        for i = 2,#string_array do
            children_gene_list[i-1] = string_array[i]
			table.insert(gene_list, string_array[i])
        end

        line = rfile:read()
        string_array = string_split(line)

        children_term_list = {}
        for i = 2,#string_array do
            children_term_list[i-1] = string_array[i]
        end

        children_term_map[term_name] = children_term_list
        children_gene_map[term_name] = children_gene_list
        term_size_map[term_name] = tonumber(gene_num)
    end

	rfile:close()

	gene_list = table2set(gene_list)

    return term_list, gene_list, children_term_map, children_gene_map, term_size_map
end


text:
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <cmath>
#include <tinythread.h>

using namespace std;
using namespace tthread;

// Mandelbrot fractal settings
#define MAND_MID_RE -0.69795
#define MAND_MID_IM -0.34865
#define MAND_SIZE 0.003
#define MAND_MAX_ITER 4000
#define MAND_RESOLUTION 1024

/// BGR pixel class.
class Pixel {
  public:
    Pixel() : b(0), g(0), r(0) {}

    Pixel(unsigned char red, unsigned char green, unsigned char blue)
    {
      b = blue;
      g = green;
      r = red;
    }

    unsigned char b, g, r;
};

/// Simple 2D BGR image class.
class Image {
  public:
    /// Create a new image with the dimensions aWidth x aHeight.
    Image(int aWidth, int aHeight)
    {
      mData = new Pixel[aWidth * aHeight];
      mWidth = aWidth;
      mHeight = aHeight;
    }

    ~Image()
    {
      delete mData;
    }

    /// Write the image to a TGA file.
    void WriteToTGAFile(const char * aFileName)
    {
      // Prepare TGA file header
      unsigned char header[18] = {0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0};
      header[12] = mWidth & 255;         // Image width (16 bits)
      header[13] = (mWidth >> 8) & 255;  // -"-
      header[14] = mHeight & 255;        // Image width (16 bits)
      header[15] = (mHeight >> 8) & 255; // -"-

      // Write output file
      ofstream f(aFileName, ios_base::out | ios_base::binary);
      f.write((const char *) header, 18);
      f.write((const char *) mData, (mWidth * mHeight) * 3);
    }

    Pixel& operator[](const int idx)
    {
      return mData[idx];
    }

    inline int Width() const
    {
      return mWidth;
    }

    inline int Height() const
    {
      return mHeight;
    }

  private:
    int mWidth;    ///< Image width.
    int mHeight;   ///< Image height.
    Pixel * mData; ///< Data pointer.
};

/// The RowDispatcher class manages the "job pool" for the fractal
/// calculation threads.
class RowDispatcher {
  public:
    RowDispatcher(Image * aImage) : mNextRow(0)
    {
      mImage = aImage;
    }

    Image * GetImage()
    {
      return mImage;
    }

    int NextRow()
    {
      lock_guard<mutex> guard(mMutex);
      if(mNextRow >= mImage->Height())
        return -1;
      int result = mNextRow;
      ++ mNextRow;
      return result;
    }

  private:
    mutex mMutex;
    int mNextRow;
    Image * mImage;
};

// Core iteration function
Pixel Iterate(const double &cre, const double &cim, int aIterMax)
{
  double zre = 0.0;
  double zim = 0.0;
  int n = 0;
  double absZSqr = 0.0;
  while((absZSqr < 4.0) && (n < aIterMax))
  {
    double tmp = zre * zre - zim * zim + cre;
    zim = 2.0 * zre * zim + cim;
    zre = tmp;
    absZSqr = zre * zre + zim * zim;
    ++ n;
  }
  if(n >= aIterMax)
    return Pixel(0,0,0);
  else
  {
    double nSmooth = n + 1 - log(log(sqrt(absZSqr))) / log(2.0);
    return Pixel(
             (unsigned char)(128.0 - 127.0 * cos(0.02 * nSmooth + 0.3)),
             (unsigned char)(128.0 - 127.0 * cos(0.016 * nSmooth + 1.2)),
             (unsigned char)(128.0 - 127.0 * cos(0.013 * nSmooth + 2.6))
           );
  }
}

// Calculation thread
void CalcThread(void * arg)
{
  RowDispatcher * dispatcher = (RowDispatcher *) arg;
  Image * img = dispatcher->GetImage();

  // Set min/max interval for the fractal set
  double xMin = MAND_MID_RE - MAND_SIZE * 0.5;
  double yMin = MAND_MID_IM - MAND_SIZE * 0.5;
  double xMax = MAND_MID_RE + MAND_SIZE * 0.5;
  double yMax = MAND_MID_IM + MAND_SIZE * 0.5;

  // Set step size (distance between two adjacent pixels)
  double xStep = (xMax - xMin) / img->Width();
  double yStep = (yMax - yMin) / img->Height();

  // Until no more rows to process...
  while(true)
  {
    // Get the next row to calculate
    int y = dispatcher->NextRow();

    // Done?
    if(y < 0)
      break;

    // Generate one row of the image
    Pixel * line = &(*img)[y * img->Width()];
    double cim = y * yStep + yMin;
    double cre = xMin;
    for(int x = 0; x < img->Width(); ++ x)
    {
      *line ++ = Iterate(cre, cim, MAND_MAX_ITER);
      cre += xStep;
    }
  }
}

int main(int argc, char **argv)
{
  // Show some information about this program...
  cout << "This is a small multi threaded Mandelbrot fractal generator." << endl;
  cout << endl;
  cout << "The program will generate a " << MAND_RESOLUTION << "x" << MAND_RESOLUTION << " image, using one calculation thread per" << endl;
  cout << "processor core. The result is written to a TGA format image, \"fractal.tga\"." << endl;
  cout << endl;
  cout << "Type \"" << argv[0] << " -st\" to force single threaded operation." << endl;
  cout << endl;

  // Check arguments
  bool singleThreaded = false;
  if((argc >= 2) && (string(argv[1]) == string("-st")))
    singleThreaded = true;

  // Init image and row dispatcher
  Image img(MAND_RESOLUTION, MAND_RESOLUTION);
  RowDispatcher dispatcher(&img);

  // Determine the number of calculation threads to use
  int numThreads;
  if(!singleThreaded)
  {
    numThreads = thread::hardware_concurrency();
    if(numThreads < 1)
      numThreads = 1;
  }
  else
    numThreads = 1;

  // Start calculation threads (we run one thread on each processor core)
  cout << "Running " << numThreads << " calculation thread(s)..." << flush;
  list<thread *> threadList;
  for(int i = 0; i < numThreads; ++ i)
  {
    thread * t = new thread(CalcThread, (void *) &dispatcher);
    threadList.push_back(t);
  }

  // Wait for the threads to complete...
  for(list<thread *>::iterator i = threadList.begin(); i != threadList.end(); ++ i)
  {
    thread * t = *i;
    t->join();
    delete t;
  }
  cout << "done!" << endl;

  // Write the final image to a file
  cout << "Writing final image..." << flush;
  img.WriteToTGAFile("fractal.tga");
  cout << "done!" << endl;
}


text:
from jinja2 import Template

def replace_template_properties(template, **kargs):
    """This method replaces all *kargs parameters (key=value) in the given template
    :param template: Temaplate to be rendered (String)
    :return: It will return the rendered template as unicode string.
    """
    template_obj = Template(template)
    return template_obj.render(kargs)


text:
using UnityEngine;
using System.Collections;

public class Movement_Circling : MonoBehaviour
{
	float walkDuration = 1.0f;
	float timeLeft = 1.0f ;
	bool goright=true;

	// Update is called once per frame
	void Update ()
	{
		Movement();
	}

	void Movement() {

		if(timeLeft > 0 && goright)
		{
			transform.Translate( Vector2.right * 4f * Time.deltaTime*Mathf.Sin(Time.time));
			transform.Translate( Vector2.up * 4f * Time.deltaTime*Mathf.Cos(Time.time));
			transform.eulerAngles = new Vector2(0,0);
			timeLeft -= Time.deltaTime;
		}
		else if(timeLeft <= 0 && goright)
			{
			timeLeft = -walkDuration;
			goright=false;
		}
		else if( timeLeft <=0 && !goright)
		{
			transform.Translate(-Vector2.right * 4f * Time.deltaTime*Mathf.Sin(Time.time));
			transform.Translate( -Vector2.up * 4f * Time.deltaTime*Mathf.Cos(Time.time));
			transform.eulerAngles = new Vector2(0,0);
			timeLeft += Time.deltaTime;
		}
		else if(timeLeft > 0 && !goright)
		{
			timeLeft = walkDuration;
			goright=true;
		}

	}

}


text:
using Aspose.Diagram;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Aspose.Diagram.Examples.CSharp.Working_Shapes
{
    public class SaveVisioShapeInOtherFormats
    {
        public static void Run()
        {
            // ExStart:SaveVisioShapeInOtherFormats
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Shapes();

            // Call a Diagram class constructor to load the VSDX diagram
            Diagram srcVisio = new Diagram(dataDir + "Drawing1.vsdx");

            double shapeWidth = 0;
            double shapeHeight = 0;

            // Get Visio page
            Aspose.Diagram.Page srcPage = srcVisio.Pages.GetPage("Page-3");
            // Remove background page
            srcPage.BackPage = null;

            // Get hash table of shapes, it holds id and name
            Hashtable remShapes = new Hashtable();
            // Hashtable<Long, String> remShapes = new Hashtable<Long, String>();
            foreach (Aspose.Diagram.Shape shape in srcPage.Shapes)
                // For the normal shape
                remShapes.Add(shape.ID, shape.Name);

            // Iterate through the hash table
            foreach (DictionaryEntry shapeEntry in remShapes)
            {
                long key = (long)shapeEntry.Key;
                string val = (string)shapeEntry.Value;
                Aspose.Diagram.Shape shape = srcPage.Shapes.GetShape(key);
                // Check of the shape name
                if (val.Equals("GroupShape1"))
                {
                    // Move shape to the origin corner
                    shapeWidth = shape.XForm.Width.Value;
                    shapeHeight = shape.XForm.Height.Value;
                    shape.MoveTo(shapeWidth * 0.5, shapeHeight * 0.5);
                    // Trim page size
                    srcPage.PageSheet.PageProps.PageWidth.Value = shapeWidth;
                    srcPage.PageSheet.PageProps.PageHeight.Value = shapeHeight;
                }
                else
                {
                    // Remove shape from the Visio page and hash table
                    srcPage.Shapes.Remove(shape);
                }
            }
            remShapes.Clear();

            // Specify saving options
            Aspose.Diagram.Saving.PdfSaveOptions opts = new Aspose.Diagram.Saving.PdfSaveOptions();
            // Set page count to save
            opts.PageCount = 1;
            // Set starting index of the page
            opts.PageIndex = 1;
            // Save it
            srcVisio.Save(dataDir + "SaveVisioShapeInOtherFormats_out.pdf", opts);
            // ExEnd:SaveVisioShapeInOtherFormats
        }
    }
}