text:
page_title: Automated Builds on Docker.io
page_description: Docker.io Automated Builds
page_keywords: Docker, docker, registry, accounts, plans, Dockerfile, Docker.io, docs, documentation, trusted, builds, trusted builds, automated, automated builds
# Automated Builds on Docker.io

## Automated Builds

*Automated Builds* is a special feature allowing you to specify a source
repository with a `Dockerfile` to be built by the
[Docker.io](https://index.docker.io) build clusters. The system will
clone your repository and build the `Dockerfile` using the repository as
the context. The resulting image will then be uploaded to the registry
and marked as an *Automated Build*.

Automated Builds have a number of advantages. For example, users of
*your* Automated Build can be certain that the resulting image was built
exactly how it claims to be.

Furthermore, the `Dockerfile` will be available to anyone browsing your repository
on the registry. Another advantage of the Automated Builds feature is the automated
builds. This makes sure that your repository is always up to date.

Automated Builds are supported for both public and private repositories
on both [GitHub](http://github.com) and
[BitBucket](https://bitbucket.org/).

### Setting up Automated Builds with GitHub

In order to setup an Automated Build, you need to first link your [Docker.io](
https://index.docker.io) account with a GitHub one. This will allow the registry
to see your repositories.

> *Note:* We currently request access for *read* and *write* since [Docker.io](
> https://index.docker.io) needs to setup a GitHub service hook. Although nothing
> else is done with your account, this is how GitHub manages permissions, sorry!

Click on the [Automated Builds tab](https://index.docker.io/builds/) to
get started and then select [+ Add
New](https://index.docker.io/builds/add/).

Select the [GitHub
service](https://index.docker.io/associate/github/).

Then follow the instructions to authorize and link your GitHub account
to Docker.io.

#### Creating an Automated Build

You can [create an Automated Build](https://index.docker.io/builds/github/select/)
from any of your public or private GitHub repositories with a `Dockerfile`.

#### GitHub organizations

GitHub organizations appear once your membership to that organization is
made public on GitHub. To verify, you can look at the members tab for your
organization on GitHub.

#### GitHub service hooks

You can follow the below steps to configure the GitHub service hooks for your
Automated Build:

      Step
      Screenshot
      Description

      1.

      Login to Github.com, and visit your Repository page. Click on the repository "Settings" link. You will need admin rights to the repository in order to do this. So if you don't have admin rights, you will need to ask someone who does.

      2.

      Click on the "Service Hooks" link

3.		Find the service hook labeled "Docker" and click on it.

4.
      Click on the "Active" checkbox and then the "Update settings" button, to save changes.

### Setting up Automated Builds with BitBucket

In order to setup an Automated Build, you need to first link your
[Docker.io]( https://index.docker.io) account with a BitBucket one. This
will allow the registry to see your repositories.

Click on the [Automated Builds tab](https://index.docker.io/builds/) to
get started and then select [+ Add
New](https://index.docker.io/builds/add/).

Select the [BitBucket
service](https://index.docker.io/associate/bitbucket/).

Then follow the instructions to authorize and link your BitBucket account
to Docker.io.

#### Creating an Automated Build

You can [create an Automated
Build](https://index.docker.io/builds/bitbucket/select/) from any of
your public or private BitBucket repositories with a `Dockerfile`.

### The Dockerfile and Automated Builds

During the build process, we copy the contents of your `Dockerfile`. We also
add it to the [Docker.io](https://index.docker.io) for the Docker community
to see on the repository page.

### README.md

If you have a `README.md` file in your repository, we will use that as the
repository's full description.

> **Warning:**
> If you change the full description after a build, it will be
> rewritten the next time the Automated Build has been built. To make changes,
> modify the README.md from the Git repository. We will look for a README.md
> in the same directory as your `Dockerfile`.

### Build triggers

If you need another way to trigger your Automated Builds outside of GitHub
or BitBucket, you can setup a build trigger. When you turn on the build
trigger for an Automated Build, it will give you a URL to which you can
send POST requests. This will trigger the Automated Build process, which
is similar to GitHub webhooks.

Build Triggers are available under the Settings tab of each Automated Build.

> **Note:**
> You can only trigger one build at a time and no more than one
> every five minutes. If you have a build already pending, or if you already
> recently submitted a build request, those requests *will be ignored*.
> You can find the logs of last 10 triggers on the settings page to verify
> if everything is working correctly.

### Webhooks

Also available for Automated Builds are Webhooks. Webhooks can be called
after a successful repository push is made.

The webhook call will generate a HTTP POST with the following JSON
payload:

```
{
   "push_data":{
      "pushed_at":1385141110,
      "images":[
         "imagehash1",
         "imagehash2",
         "imagehash3"
      ],
      "pusher":"username"
   },
   "repository":{
      "status":"Active",
      "description":"my docker repo that does cool things",
      "is_automated":false,
      "full_description":"This is my full description",
      "repo_url":"https://index.docker.io/u/username/reponame/",
      "owner":"username",
      "is_official":false,
      "is_private":false,
      "name":"reponame",
      "namespace":"username",
      "star_count":1,
      "comment_count":1,
      "date_created":1370174400,
      "dockerfile":"my full dockerfile is listed here",
      "repo_name":"username/reponame"
   }
}
```

Webhooks are available under the Settings tab of each Automated
Build.

> **Note:** If you want to test your webhook out then we recommend using
> a tool like [requestb.in](http://requestb.in/).

### Repository links

Repository links are a way to associate one Automated Build with another. If one
gets updated, linking system also triggers a build for the other Automated Build.
This makes it easy to keep your Automated Builds up to date.

To add a link, go to the settings page of an Automated Build and click on
*Repository Links*. Then enter the name of the repository that you want have
linked.

> **Warning:**
> You can add more than one repository link, however, you should
> be very careful. Creating a two way relationship between Automated Builds will
> cause a never ending build loop.


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('crowdsourcing', '0100_remove_task_relaunch'),
    ]

    operations = [
        migrations.AlterField(
            model_name='task',
            name='row_number',
            field=models.IntegerField(db_index=True, null=True),
        ),
        migrations.AlterField(
            model_name='taskworker',
            name='status',
            field=models.IntegerField(choices=[(1, b'In Progress'), (2, b'Submitted'), (3, b'Accepted'), (4, b'Rejected'), (5, b'Returned'), (6, b'Skipped'), (7, b'Expired')], db_index=True, default=1),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-6ba12569-f19d-48eb-8e5c-42454d2837bd" version="1.1.1" timestamp="2013-02-12T19:08:11+00:00">
    <stix:Incidents>
        <stix:Incident id="example:incident-504e38eb-eb27-4894-8f15-e1f42bda99d3" timestamp="2014-05-10T00:58:19+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>Details of an Essex council's entire workforce were released online in a "serious security breach", it has said.  Names, dates of birth, sickness information and work contact numbers for Basildon Council's staff of "about 1,000" were published on the internet.  A council worker spotted the breach on Monday and the details were removed by Tuesday, the council said.  The council believes data held by a contractor was put out by a third party. Police are investigating.  The authority said the breach is believed to have been one of several within the private and public sector and that it had advised staff to report suspicious or unusual phone calls.</incident:Title>
            <incident:External_ID source="VERIS">261517D9-6951-4CB9-9595-5A019C4FF1E1</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="year">2012-01-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">swidup</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Basildon Council</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>GB</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Disk media</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                            <incident:Description_Of_Effect>Medical: 1000, Personal: 1000</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-fa9a1b88-d3fd-41fe-bbf1-ab946d7bad4f" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://www.bbc.co.uk/news/uk-england-essex-16853109</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-fa9a1b88-d3fd-41fe-bbf1-ab946d7bad4f" timestamp="2014-12-22T16:23:24.011000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>Unknown</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Motivation timestamp="2014-12-22T16:23:24.011000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Motivation>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
package render

import (
	"github.com/weaveworks/scope/report"
)

// PropagateSingleMetrics puts metrics from one of the children onto the parent
// iff there is only one child of that type.
func PropagateSingleMetrics(topology string) MapFunc {
	return func(n report.Node, _ report.Networks) report.Nodes {
		var found []report.Node
		n.Children.ForEach(func(child report.Node) {
			if child.Topology == topology {
				if _, ok := child.Latest.Lookup(report.DoesNotMakeConnections); !ok {
					found = append(found, child)
				}
			}
		})
		if len(found) == 1 {
			n = n.WithMetrics(found[0].Metrics)
		}
		return report.Nodes{n.ID: n}
	}
}


text:
#ifndef PG_AM_D_H
#define PG_AM_D_H

#define AccessMethodRelationId 2601

#define Anum_pg_am_oid 1
#define Anum_pg_am_amname 2
#define Anum_pg_am_amhandler 3
#define Anum_pg_am_amtype 4

#define Natts_pg_am 4

/*
 * Allowed values for amtype
 */
#define AMTYPE_INDEX					'i' /* index access method */
#define AMTYPE_TABLE					't' /* table access method */

#define HEAP_TABLE_AM_OID 2
#define BTREE_AM_OID 403
#define HASH_AM_OID 405
#define GIST_AM_OID 783
#define GIN_AM_OID 2742
#define SPGIST_AM_OID 4000
#define BRIN_AM_OID 3580

#endif							/* PG_AM_D_H */


text:
/*
Labview API for the functionality in QueuedTracker.h
*/
#include "std_incl.h"
#include "utils.h"
#include "labview.h"
#include "QueuedTracker.h"
#include "threads.h"

#include "lv_qtrk_api.h"

#include "ResultManager.h"
#include "FisherMatrix.h"
#include "BeadFinder.h"

static Threads::Mutex trackerListMutex;
static std::vector<QueuedTracker*> trackerList;

CDLL_EXPORT void DLL_CALLCONV qtrk_free_all()
{
	trackerListMutex.lock();
	DeleteAllElems(trackerList);
	trackerListMutex.unlock();
}

void SetLVString (LStrHandle str, const char *text)
{
	int msglen = strlen(text);
	MgErr err = NumericArrayResize(uB, 1, (UHandle*)&str, msglen);
	if (!err)
	{
		MoveBlock(text, LStrBuf(*str), msglen);
		LStrLen(*str) = msglen;
	}
}

std::vector<std::string> LVGetStringArray(int count, LStrHandle *str)
{
	std::vector<std::string> result(count);

	for (int x=0;x<count;x++) {
		uChar *val = LHStrBuf(str[x]);
		int len = LHStrLen (str[x]);
		result[x]=std::string((const char*)val, (size_t)len );
	}
	return result;
}

MgErr FillErrorCluster(MgErr err, const char *message, ErrorCluster *error)
{
	if (err)
	{
		error->status = LVBooleanTrue;
		error->code = err;
		SetLVString ( error->message, message );
	}
	return err;
}

void ArgumentErrorMsg(ErrorCluster* e, const std::string& msg) {
	FillErrorCluster(mgArgErr, msg.c_str(), e);
}

bool ValidateTracker(QueuedTracker* tracker, ErrorCluster* e, const char *funcname)
{
	if (std::find(trackerList.begin(), trackerList.end(), tracker)==trackerList.end()) {
		ArgumentErrorMsg(e, SPrintf("QTrk C++ function %s called with invalid tracker pointer: %p", funcname, tracker));
		return false;
	}
	return true;
}

CDLL_EXPORT int qtrk_get_debug_image(QueuedTracker* qtrk, int id, LVArray2D<float>** data, ErrorCluster* e)
{
	int w,h;
	if (ValidateTracker(qtrk, e, "qtrk_get_debug_image")) {
		float* img;
		if (qtrk->GetDebugImage(id, &w,&h, &img)) {
			ResizeLVArray2D(data, h, w);
			for (int i=0;i<w*h;i++) (*data)->elem[i]=img[i];
			delete[] img;
			return 1;
		}
	}
	return 0;
}

CDLL_EXPORT void DLL_CALLCONV qtrk_set_logfile_path(const char* path)
{
	dbgsetlogfile(path);
}

CDLL_EXPORT void DLL_CALLCONV qtrk_get_computed_config(QueuedTracker* qtrk, QTrkComputedConfig* cc, ErrorCluster *err)
{
	if (ValidateTracker(qtrk, err, "get computed config"))
		*cc = qtrk->cfg;
}

CDLL_EXPORT void DLL_CALLCONV qtrk_set_ZLUT(QueuedTracker* tracker, LVArray3D<float>** pZlut, LVArray<float>** zcmpWindow, int normalize, ErrorCluster* e)
{
	LVArray3D<float>* zlut = *pZlut;

	if (ValidateTracker(tracker,e, "set ZLUT")) {

		int numLUTs = zlut->dimSizes[0];
		int planes = zlut->dimSizes[1];
		int res = zlut->dimSizes[2];

		dbgprintf("Setting ZLUT size: %d beads, %d planes, %d radialsteps\n", numLUTs, planes, res);

		float* zcmp = 0;
		if (zcmpWindow && (*zcmpWindow)->dimSize > 0) {
			if ( (*zcmpWindow)->dimSize != res)
				ArgumentErrorMsg(e, SPrintf("Z Compare window should have the same resolution as the ZLUT (%d elements)", res));
			else
				zcmp = (*zcmpWindow)->elem;
		}

		if (numLUTs * planes * res == 0) {
			tracker->SetRadialZLUT(0, 0, 0);
		} else {
			if (res != tracker->cfg.zlut_radialsteps)
				ArgumentErrorMsg(e, SPrintf("set_ZLUT: 3rd dimension should have size of zlut_radialsteps (%d instead of %d)", tracker->cfg.zlut_radialsteps, res));
			else {

				if (normalize) {
					NormalizeZLUT( zlut->elem, numLUTs, planes, res );
				}

				tracker->SetRadialZLUT(zlut->elem, numLUTs, planes);
				tracker->SetRadialWeights(zcmp);
			}
		}
	}
}

CDLL_EXPORT void DLL_CALLCONV qtrk_get_ZLUT(QueuedTracker* tracker, LVArray3D<float>** pzlut, ErrorCluster* e)
{
	if (ValidateTracker(tracker, e, "get ZLUT")) {
		int dims[3];

		tracker->GetRadialZLUTSize(dims[0], dims[1], dims[2]);
		if(dims[0]*dims[1]*dims[2]>0) {
			ResizeLVArray3D(pzlut, dims[0], dims[1], dims[2]);
			tracker->GetRadialZLUT( (*pzlut)->elem );
		}
	}
}

CDLL_EXPORT void DLL_CALLCONV qtrk_get_image_lut(QueuedTracker* qtrk, LVArrayND<float, 4>** imageLUT, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "get_image_lut")) {

		int dims[4];
		qtrk->GetImageZLUTSize(dims);
		ResizeLVArray(imageLUT, dims);

		if ( (*imageLUT)->numElem () > 0 ){
			qtrk->GetImageZLUT( (*imageLUT)->elem );
		}
	}
}

CDLL_EXPORT void DLL_CALLCONV qtrk_set_image_lut(QueuedTracker* qtrk, LVArrayND<float,4>** imageLUT,  LVArray3D<float>** radialZLUT, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "set_image_lut")) {
		if ( (*imageLUT)->numElem () == 0 ){
			qtrk->SetImageZLUT (0, 0, 0);
		}
		else {
			qtrk->SetImageZLUT( (*imageLUT)->elem, (*radialZLUT)->elem, (*imageLUT)->dimSizes );
		}
	}
}

CDLL_EXPORT void DLL_CALLCONV qtrk_set_pixel_calib_factors(QueuedTracker* qtrk, float offsetFactor, float gainFactor, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "set pixel calib factors")) {
		qtrk->SetPixelCalibrationFactors(offsetFactor, gainFactor);
	}
}

CDLL_EXPORT void DLL_CALLCONV qtrk_set_pixel_calib(QueuedTracker* qtrk, LVArray3D<float>** offset, LVArray3D<float>** gain, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "set pixel calibration images")) {
		int count, planes, radialSteps;
		qtrk->GetRadialZLUTSize(count, planes, radialSteps);

		float *offset_data = 0, *gain_data = 0;

		if((*offset)->dimSizes[0] != 0) {
			if (qtrk->cfg.width != (*offset)->dimSizes[2] || qtrk->cfg.height != (*offset)->dimSizes[1]) {
				ArgumentErrorMsg(e, SPrintf("set_pixel_calib: Offset images passed with invalid dimension (%d,%d)", (*offset)->dimSizes[2], (*offset)->dimSizes[1]));
				return;
			}
			if (count != (*offset)->dimSizes[0]) {
				ArgumentErrorMsg(e, SPrintf("set_pixel_calib: Expecting offset to have %d images (same as ZLUT). %d given", count, (*offset)->dimSizes[0]));
				return;
			}
			offset_data = (*offset)->elem;
		}

		if((*gain)->dimSizes[0] != 0) {
			if (qtrk->cfg.width != (*gain)->dimSizes[2] || qtrk->cfg.height != (*gain)->dimSizes[1]) {
				ArgumentErrorMsg(e, SPrintf("set_pixel_calib: Gain images passed with invalid dimension (%d,%d)", (*gain)->dimSizes[2], (*gain)->dimSizes[1]));
				return;
			}
			if (count != (*gain)->dimSizes[0]) {
				ArgumentErrorMsg(e, SPrintf("set_pixel_calib: Expecting gain to have %d images (same as ZLUT). %d given", count, (*gain)->dimSizes[0]));
				return;
			}
			gain_data = (*gain)->elem;
		}

		qtrk->SetPixelCalibrationImages(offset_data, gain_data);
	}
}

CDLL_EXPORT QueuedTracker* qtrk_create(QTrkSettings* settings, LStrHandle warnings, ErrorCluster* e)
{
	QueuedTracker* tracker = 0;
	try {
		QTrkComputedConfig cc(*settings);
		cc.WriteToLog();

		tracker = CreateQueuedTracker(cc);

		std::string w = tracker->GetWarnings();
		if (!w.empty()) SetLVString(warnings, w.c_str());

		trackerListMutex.lock();
		trackerList.push_back(tracker);
		trackerListMutex.unlock();
	} catch(const std::runtime_error &exc) {
		FillErrorCluster(kAppErrorBase, exc.what(), e );
	}
	return tracker;
}

CDLL_EXPORT void qtrk_destroy(QueuedTracker* qtrk, ErrorCluster* error)
{
	trackerListMutex.lock();

	auto pos = std::find(trackerList.begin(),trackerList.end(),qtrk);
	if (pos == trackerList.end()) {
		ArgumentErrorMsg(error, SPrintf( "Trying to call qtrk_destroy with invalid qtrk pointer %p", qtrk));
		qtrk = 0;
	}
	else
		trackerList.erase(pos);

	trackerListMutex.unlock();

	if(qtrk) delete qtrk;
}

template<typename T>
bool CheckImageInput(QueuedTracker* qtrk, LVArray2D<T> **data, ErrorCluster  *error)
{
	if (!data) {
		ArgumentErrorMsg(error, "Image data array is empty");
		return false;
	} else if( (*data)->dimSizes[1] != qtrk->cfg.width || (*data)->dimSizes[0] != qtrk->cfg.height ) {
		ArgumentErrorMsg(error, SPrintf( "Image data array has wrong size (%d,%d). Should be: (%d,%d)", (*data)->dimSizes[1], (*data)->dimSizes[0], qtrk->cfg.width, qtrk->cfg.height));
		return false;
	}
	return true;
}

CDLL_EXPORT void qtrk_queue_u16(QueuedTracker* qtrk, ErrorCluster* error, LVArray2D<ushort>** data, const LocalizationJob *jobInfo)
{
	if (CheckImageInput(qtrk, data, error))
	{
		qtrk->ScheduleLocalization( (uchar*)(*data)->elem, sizeof(ushort)*(*data)->dimSizes[1], QTrkU16, jobInfo);
	}
}

CDLL_EXPORT void qtrk_queue_u8(QueuedTracker* qtrk, ErrorCluster* error, LVArray2D<uchar>** data, const LocalizationJob *jobInfo)
{
	if (CheckImageInput(qtrk, data, error))
	{
#ifdef _DEBUG
	dbgprintf("Job: 8bit image, frame %d, bead %d\n", jobInfo->frame, jobInfo->zlutIndex);
#endif

		qtrk->ScheduleLocalization( (*data)->elem, sizeof(uchar)*(*data)->dimSizes[1], QTrkU8, jobInfo);
	}
}

CDLL_EXPORT void qtrk_queue_float(QueuedTracker* qtrk, ErrorCluster* error, LVArray2D<float>** data, const LocalizationJob *jobInfo)
{
	if (CheckImageInput(qtrk, data, error))
	{
		qtrk->ScheduleLocalization( (uchar*) (*data)->elem, sizeof(float)*(*data)->dimSizes[1], QTrkFloat, jobInfo);
	}
}

CDLL_EXPORT void qtrk_queue_pitchedmem(QueuedTracker* qtrk, uchar* data, int pitch, uint pdt, const LocalizationJob *jobInfo)
{
	qtrk->ScheduleLocalization(data, pitch, (QTRK_PixelDataType)pdt, jobInfo);
}

CDLL_EXPORT void qtrk_queue_array(QueuedTracker* qtrk,  ErrorCluster* error,LVArray2D<uchar>** data,uint pdt, const LocalizationJob *jobInfo)
{
	uint pitch;

	if (pdt == QTrkFloat)
		pitch = sizeof(float);
	else if(pdt == QTrkU16)
		pitch = 2;
	else pitch = 1;

	if (!CheckImageInput(qtrk, data, error))
		return;

	pitch *= (*data)->dimSizes[1]; // LVArray2D<uchar> type works for ushort and float as well
//	dbgprintf("zlutindex: %d, zlutplane: %d\n", zlutIndex,zlutPlane);
	qtrk_queue_pitchedmem(qtrk, (*data)->elem, pitch, pdt, jobInfo);
}

CDLL_EXPORT uint qtrk_read_timestamp(uchar* image, int w, int h)
{
	if (w*h<4) return 0;

	uint ts;
	uchar *timestamp = (uchar*)&ts;
	// Assume little endian only
	for (int i=0;i<4;i++)
		timestamp[i] = image[i];
	return ts;
}

CDLL_EXPORT uint qtrk_queue_frame(QueuedTracker* qtrk, uchar* image, int pitch, int w,int h,
	uint pdt, ROIPosition* pos, int numROI, const LocalizationJob *pJobInfo, QueueFrameFlags flags, ErrorCluster* e)
{
	LocalizationJob jobInfo = *pJobInfo;
	int nQueued;
	if ( (nQueued=qtrk->ScheduleFrame(image, pitch, w,h, pos, numROI, (QTRK_PixelDataType)pdt, &jobInfo)) != numROI) {
		ArgumentErrorMsg(e, SPrintf( "Not all ROIs (%d out of %d) where queued. Check image borders vs ROIs.", nQueued, numROI));
	}
	return jobInfo.timestamp;
}

CDLL_EXPORT void qtrk_clear_results(QueuedTracker* qtrk, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "clear results")) {
		qtrk->ClearResults();
	}
}

// Accepts data as 3D image [numbeads]*[width]*[height]
CDLL_EXPORT void qtrk_build_lut_plane(QueuedTracker* qtrk, LVArray3D<float> **data, uint flags, int plane,ErrorCluster* err)
{
	if (ValidateTracker(qtrk, err, "build_lut_plane")) {
		if ((*data)->dimSizes[2] != qtrk->cfg.width || (*data)->dimSizes[1] != qtrk->cfg.height) {
			ArgumentErrorMsg(err, SPrintf("Invalid size: %dx%d. Expecting %dx%d\n", (*data)->dimSizes[2], (*data)->dimSizes[1], qtrk->cfg.width, qtrk->cfg.height));
			return;
		}

		int cnt,planes,rsteps;
		qtrk->GetRadialZLUTSize(cnt, planes, rsteps);

		if ((*data)->dimSizes[0] != cnt) {
			ArgumentErrorMsg(err, SPrintf("Invalid number of images given (%d). Expecting %d", (*data)->dimSizes[0], cnt));
			return;
		}

		qtrk->BuildLUT( (*data)->elem, sizeof(float*) * qtrk->cfg.width, QTrkFloat, plane);
	}
}

CDLL_EXPORT void qtrk_finalize_lut(QueuedTracker* qtrk, ErrorCluster *e)
{
	if (ValidateTracker(qtrk, e, "finalize_lut"))
		qtrk->FinalizeLUT();
}

CDLL_EXPORT int qtrk_get_queue_len(QueuedTracker* qtrk, int* maxQueueLen, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "fullqueue"))
		return qtrk->GetQueueLength(maxQueueLen);
	return 0;
}

CDLL_EXPORT int qtrk_resultcount(QueuedTracker* qtrk, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "resultcount")) {
		return qtrk->GetResultCount();
	}
	return 0;
}

CDLL_EXPORT void qtrk_flush(QueuedTracker* qtrk, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "flush")) {
		qtrk->Flush();
	}
}

CDLL_EXPORT int qtrk_get_results(QueuedTracker* qtrk, LocalizationResult* results, int maxResults, int sortByID, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "get_results")) {
		int resultCount = qtrk->FetchResults(results, maxResults);

		if (sortByID) {
			std::sort(results, results+resultCount, [](decltype(*results) a, decltype(*results) b) { return a.job.frame<b.job.frame; } );
		}

		return resultCount;
	}
	return 0;
}

CDLL_EXPORT void qtrk_get_zlut_cmpprof(QueuedTracker* qtrk, LVArray2D<float> ** output, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "get zlut compare profiles"))
	{
		int cnt,planes,rsteps;
		qtrk->GetRadialZLUTSize(cnt,planes,rsteps);
		ResizeLVArray2D(output, cnt, planes);

		qtrk->GetRadialZLUTCompareProfile((*output)->elem);
	}
}

CDLL_EXPORT void qtrk_enable_zlut_cmpprof(QueuedTracker* qtrk, bool enable, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "enable zlut cmpprof"))
		qtrk->EnableRadialZLUTCompareProfile(enable);
}

CDLL_EXPORT void qtrk_set_localization_mode(QueuedTracker* qtrk, uint locType, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "set_localization_mode")) {
		qtrk->SetLocalizationMode( (LocMode_t)locType );
	}
}

CDLL_EXPORT int qtrk_idle(QueuedTracker* qtrk, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "is_idle"))
		return qtrk->IsIdle() ? 1 : 0;
	return 0;
}

CDLL_EXPORT void qtrk_compute_zlut_bias_table(QueuedTracker* qtrk, int bias_planes, LVArray2D<float>** lvresult, int smpPerPixel, int useSplineInterp,ErrorCluster* e)
{
	if(ValidateTracker(qtrk, e,"compute_zlut_bias_table")) {
		CImageData result;
		qtrk->ComputeZBiasCorrection(bias_planes, &result, smpPerPixel, useSplineInterp!=0);

		ResizeLVArray2D(lvresult, result.h, result.w);
		result.copyTo ( (*lvresult)->elem );
	}
}

CDLL_EXPORT void qtrk_set_zlut_bias_table(QueuedTracker* qtrk, LVArray2D<float>** biastbl, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e,"set zlut bias table")) {
		int numbeads,planes,radialsteps;
		qtrk->GetRadialZLUTSize(numbeads, planes, radialsteps);

		if ((*biastbl)->dimSizes[1] != numbeads) {
			ArgumentErrorMsg(e, SPrintf( "Bias table should be [numbeads] high and [biasplanes] wide. Expected #beads=%d", numbeads) );
		}
		else {
			qtrk->SetZLUTBiasCorrection( ImageData( (*biastbl)->elem, (*biastbl)->dimSizes[0], (*biastbl)->dimSizes[1] ) );
		}
	}
}

CDLL_EXPORT void DLL_CALLCONV qtrk_generate_gaussian_spot(LVArray2D<float>** image, vector2f* pos, float sigma, float I0, float Ibg, int applyNoise)
{
	ImageData img((*image)->elem, (*image)->dimSizes[1], (*image)->dimSizes[0]);

	GenerateGaussianSpotImage(&img, *pos, sigma, I0, Ibg);

	if (applyNoise)
		ApplyPoissonNoise(img,1);
}

CDLL_EXPORT void DLL_CALLCONV qtrk_generate_image_from_lut(LVArray2D<float>** image, LVArray2D<float>** lut,
					float *LUTradii, vector2f* position, float z, float M, float sigma_noise)
{
	ImageData img((*image)->elem, (*image)->dimSizes[1], (*image)->dimSizes[0]);
	ImageData zlut((*lut)->elem, (*lut)->dimSizes[1], (*lut)->dimSizes[0]);

	vector3f pos (position->x, position->y, z);
	GenerateImageFromLUT(&img, &zlut, LUTradii[0], LUTradii[1], pos);
	//img.normalize();
	if(sigma_noise>0)
		ApplyGaussianNoise(img, sigma_noise);
}

CDLL_EXPORT void qtrk_dump_memleaks()
{
#ifdef USE_MEMDBG
	_CrtDumpMemoryLeaks();
#endif
}

CDLL_EXPORT void qtrk_get_profile_report(QueuedTracker* qtrk, LStrHandle str)
{
	SetLVString(str, qtrk->GetProfileReport().c_str());
}

CDLL_EXPORT void qtrk_compute_fisher(LVArray2D<float> **lut, QTrkSettings* cfg, vector3f* pos, LVArray2D<float> ** fisherMatrix,
		LVArray2D<float> ** inverseMatrix, vector3f* xyzVariance, int Nsamples, float maxPixelValue)
{
	QTrkComputedConfig cc (*cfg);
	ImageData lutImg( (*lut)->elem, (*lut)->dimSizes[1], (*lut)->dimSizes[0] );
	SampleFisherMatrix fm(maxPixelValue);
	Matrix3X3 mat = fm.ComputeAverageFisher(*pos, Nsamples, vector3f(1,1,1), vector3f(1,1,1)*0.001f, cfg->width, cfg->height, [&](ImageData&out, vector3f pos) {
		GenerateImageFromLUT(&out, &lutImg, cc.zlut_minradius,cc.zlut_maxradius, pos);
	});

	if (fisherMatrix) {
		ResizeLVArray2D( fisherMatrix, 3, 3);
		for (int i=0;i<9;i++)
			(*fisherMatrix)->elem[i] = mat[i];
	}

	if (inverseMatrix) {
		Matrix3X3 inv = mat.Inverse();
		ResizeLVArray2D( inverseMatrix, 3, 3);
		for (int i=0;i<9;i++)
			(*inverseMatrix)->elem[i] = inv[i];
	}

	if (xyzVariance)
		*xyzVariance = mat.Inverse().diag();
}

CDLL_EXPORT void qtrk_find_beads(uint8_t* image, int pitch, int w,int h, int* smpCornerPos, int roi, float imgRelDist, float acceptance, LVArray2D<uint32_t> **output)
{
	BeadFinder::Config cfg;
	cfg.img_distance = imgRelDist;
	cfg.roi = roi;
	cfg.similarity = acceptance;
	auto results = BeadFinder::Find(image, pitch, w,h, smpCornerPos[0], smpCornerPos[1], &cfg);

	ResizeLVArray2D(output, results.size(), 2);
	for (int i=0;i<results.size();i++)
	{
		(*output)->get(i, 0) = results[i].x;
		(*output)->get(i, 1) = results[i].y;
	}
}

CDLL_EXPORT void test_array_passing(int n, LVArray<float>** flt1D, LVArray2D<float>** flt2D, LVArray<int>** int1D, LVArray2D<int>** int2D)
{
	for (int i=0;i<(*int2D)->dimSizes[0];i++)
	{
		for (int j=0;j<(*int2D)->dimSizes[1];j++)
		{
			dbgprintf("%d\t", (*int2D)->get(i, j));
		}
		dbgprintf("\n");
	}

	ResizeLVArray(flt1D, n);
	ResizeLVArray(int1D, n);
	ResizeLVArray2D(flt2D, n/2,n);
	ResizeLVArray2D(int2D, n/2,n);
	for (int i=0;i<n;i++) {
		(*int1D)->elem[i]=(i+1)*i;
		(*flt1D)->elem[i]=sqrtf(i);
		for (int j=0;j<n/2;j++) {
			(*int2D)->get(j, i) = j*2+i;
			(*flt2D)->get(j, i) = j*2+i;
		}
	}
}

CDLL_EXPORT void qtrk_simulate_tracking(QueuedTracker* qtrk, int nsmp, int beadIndex, vector3f* centerPos, vector3f* range, vector3f *outBias, vector3f* outScatter, float photonsPerWell, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "qtrk_simulate_tracking")) {

		int nZLUT, nPlanes, nRadialSteps;
		qtrk->GetRadialZLUTSize(nZLUT, nPlanes, nRadialSteps);

		float* lut = new float[nZLUT*nPlanes*nRadialSteps];
		qtrk->GetRadialZLUT(lut);

		ImageData img = ImageData::alloc(qtrk->cfg.width,qtrk->cfg.height);
		ImageData zlut;
		zlut.data = & lut [nRadialSteps*nPlanes*beadIndex];
		zlut.w = nRadialSteps;
		zlut.h = nPlanes;

		// Generate images
		std::vector<vector3f> positions(nsmp);
		for (int i=0;i<nsmp;i++) {
			vector3f pos = *centerPos + *range * vector3f(rand_uniform<float>(), rand_uniform<float>(), rand_uniform<float>());
			positions[i]=pos;
			GenerateImageFromLUT( &img, &zlut, qtrk->cfg.zlut_minradius, qtrk->cfg.zlut_maxradius, pos);
			ApplyPoissonNoise(img, photonsPerWell);
			qtrk->ScheduleLocalization((uchar*)img.data, sizeof(float)*img.w, QTrkFloat,i,i,0,beadIndex);
		}

		img.free();

		qtrk->Flush();
		while (!qtrk->IsIdle());

		LocalizationResult* results=new LocalizationResult[nsmp];
		qtrk->FetchResults(results, nsmp);
		vector3f sumBias, sumScatter;
		for (int i=0;i<nsmp;i++) {
			vector3f truepos = positions [ results[i].job.frame ];
			vector3f diff = results[i].pos - truepos;
			sumBias += diff;
		}
		vector3f meanBias = sumBias / nsmp;
		for (int i=0;i<nsmp;i++) {
			vector3f truepos = positions [ results[i].job.frame ];
			vector3f diff = results[i].pos - truepos;
			diff -= meanBias;
			sumScatter += diff*diff;
		}
		*outScatter = sqrt (sumScatter / nsmp);
		*outBias = sumBias;
	}
}

#ifdef CUDA_TRACK

#include "cuda_runtime.h"

CDLL_EXPORT void qtrkcuda_set_device_list(LVArray<int>** devices)
{
	SetCUDADevices( (*devices)->elem, (*devices)->dimSize );
}

static bool CheckCUDAErrorLV(cudaError err, ErrorCluster* e)
{
	if (err != cudaSuccess) {
		const char* errstr = cudaGetErrorString(err);
		FillErrorCluster(kAppErrorBase, SPrintf("CUDA error: %s", errstr).c_str(), e);
		return false;
	}
	return true;
}

CDLL_EXPORT int qtrkcuda_device_count(ErrorCluster* e) {
	int c;
	if (CheckCUDAErrorLV(cudaGetDeviceCount(&c), e)) {
		return c;
	}
	return 0;
}

CDLL_EXPORT void qtrkcuda_get_device(int device, CUDADeviceInfo *info, ErrorCluster* e)
{
	cudaDeviceProp prop;
	if (CheckCUDAErrorLV(cudaGetDeviceProperties(&prop, device), e)) {
		info->multiProcCount = prop.multiProcessorCount;
		info->clockRate = prop.clockRate;
		info->major = prop.major;
		info->minor = prop.minor;
		SetLVString(info->name, prop.name);
	}
}

CDLL_EXPORT void qtrkcuda_enable_texture_cache(QueuedTracker* qtrk, int enable, ErrorCluster* e)
{
	if (ValidateTracker(qtrk, e, "enable_texture_cache")) {
		qtrk->SetConfigValue("use_texturecache", enable?"1":"0");
	}
}

#else

CDLL_EXPORT int qtrkcuda_device_count(ErrorCluster* e) { return 0; }
CDLL_EXPORT void qtrkcuda_get_device(int device, void *info, ErrorCluster* e) {}

#endif


text:
using namespace Imath;
using namespace IECore;
using namespace Gaffer;
using namespace GafferImage;

IE_CORE_DEFINERUNTIMETYPED( Crop );

size_t Crop::g_firstPlugIndex = 0;

Crop::Crop( const std::string &name )
	:   ImageProcessor( name )
{
	storeIndexOfNextChild( g_firstPlugIndex );
	addChild( new IntPlug( "areaSource", Gaffer::Plug::In, Crop::Area, Crop::Area, Crop::Format ) );
	addChild( new Box2iPlug( "area" ) );
	addChild( new FormatPlug( "format" ) );
	addChild( new BoolPlug( "formatCenter" ) );
	addChild( new BoolPlug( "affectDataWindow", Gaffer::Plug::In, true ) );
	addChild( new BoolPlug( "affectDisplayWindow", Gaffer::Plug::In, true ) );
	addChild( new BoolPlug( "resetOrigin", Gaffer::Plug::In, true ) );

	addChild( new AtomicBox2iPlug( "__cropWindow", Gaffer::Plug::Out ) );
	addChild( new V2iPlug( "__offset", Gaffer::Plug::Out ) );

	OffsetPtr offset = new Offset( "__offset" );
	addChild( offset );
	offset->inPlug()->setInput( inPlug() );
	offset->enabledPlug()->setInput( enabledPlug() );
	offset->offsetPlug()->setInput( offsetPlug() );
	outPlug()->channelDataPlug()->setInput( offset->outPlug()->channelDataPlug() );

	// We don't ever want to change these, so we make pass-through connections.
	outPlug()->metadataPlug()->setInput( inPlug()->metadataPlug() );
	outPlug()->channelNamesPlug()->setInput( inPlug()->channelNamesPlug() );
}

Crop::~Crop()
{
}

Gaffer::IntPlug *Crop::areaSourcePlug()
{
	return getChild<IntPlug>( g_firstPlugIndex );
}

const Gaffer::IntPlug *Crop::areaSourcePlug() const
{
	return getChild<IntPlug>( g_firstPlugIndex );
}

Gaffer::Box2iPlug *Crop::areaPlug()
{
	return getChild<Box2iPlug>( g_firstPlugIndex + 1 );
}

const Gaffer::Box2iPlug *Crop::areaPlug() const
{
	return getChild<Box2iPlug>( g_firstPlugIndex + 1 );
}

GafferImage::FormatPlug *Crop::formatPlug()
{
	return getChild<FormatPlug>( g_firstPlugIndex + 2 );
}

const GafferImage::FormatPlug *Crop::formatPlug() const
{
	return getChild<FormatPlug>( g_firstPlugIndex + 2 );
}

Gaffer::BoolPlug *Crop::formatCenterPlug()
{
	return getChild<BoolPlug>( g_firstPlugIndex + 3 );
}

const Gaffer::BoolPlug *Crop::formatCenterPlug() const
{
	return getChild<BoolPlug>( g_firstPlugIndex + 3 );
}

Gaffer::BoolPlug *Crop::affectDataWindowPlug()
{
	return getChild<BoolPlug>( g_firstPlugIndex + 4 );
}

const Gaffer::BoolPlug *Crop::affectDataWindowPlug() const
{
	return getChild<BoolPlug>( g_firstPlugIndex + 4 );
}

Gaffer::BoolPlug *Crop::affectDisplayWindowPlug()
{
	return getChild<BoolPlug>( g_firstPlugIndex + 5 );
}

const Gaffer::BoolPlug *Crop::affectDisplayWindowPlug() const
{
	return getChild<BoolPlug>( g_firstPlugIndex + 5 );
}

Gaffer::BoolPlug *Crop::resetOriginPlug()
{
	return getChild<BoolPlug>( g_firstPlugIndex + 6 );
}

const Gaffer::BoolPlug *Crop::resetOriginPlug() const
{
	return getChild<BoolPlug>( g_firstPlugIndex + 6 );
}

Gaffer::AtomicBox2iPlug *Crop::cropWindowPlug()
{
	return getChild<AtomicBox2iPlug>( g_firstPlugIndex + 7 );
}

const Gaffer::AtomicBox2iPlug *Crop::cropWindowPlug() const
{
	return getChild<AtomicBox2iPlug>( g_firstPlugIndex + 7 );
}

Gaffer::V2iPlug *Crop::offsetPlug()
{
	return getChild<V2iPlug>( g_firstPlugIndex + 8 );
}

const Gaffer::V2iPlug *Crop::offsetPlug() const
{
	return getChild<V2iPlug>( g_firstPlugIndex + 8 );
}

void Crop::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
	ImageProcessor::affects( input, outputs );

	if(
		input == areaSourcePlug() ||
		areaPlug()->isAncestorOf( input ) ||
		formatPlug()->isAncestorOf( input ) ||
		input == formatCenterPlug() ||
		input == inPlug()->dataWindowPlug() ||
		input == inPlug()->formatPlug()
	)
	{
		outputs.push_back( cropWindowPlug() );
	}

	if(
		input == cropWindowPlug() ||
		input == affectDisplayWindowPlug() ||
		offsetPlug()->isAncestorOf( input ) ||
		input == inPlug()->formatPlug()
	)
	{
		outputs.push_back( outPlug()->formatPlug() );
	}

	if(
		input == cropWindowPlug() ||
		input == affectDisplayWindowPlug() ||
		input == affectDataWindowPlug() ||
		offsetPlug()->isAncestorOf( input ) ||
		input == inPlug()->dataWindowPlug()
	)
	{
		outputs.push_back( outPlug()->dataWindowPlug() );
	}

	if(
		input == affectDisplayWindowPlug() ||
		input == areaSourcePlug() ||
		input == formatCenterPlug() ||
		input == resetOriginPlug() ||
		input == cropWindowPlug()
	)
	{
		outputs.push_back( offsetPlug()->getChild( 0 ) );
		outputs.push_back( offsetPlug()->getChild( 1 ) );
	}

}

void Crop::hashFormat( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	if ( ! affectDisplayWindowPlug()->getValue() )
	{
		// No-op because we are not applying this
		// crop to the display window
		h = inPlug()->formatPlug()->hash();
		return;
	}

	ImageProcessor::hashFormat( parent, context, h );

	inPlug()->formatPlug()->hash( h );
	cropWindowPlug()->hash( h );
	offsetPlug()->hash( h );
}

GafferImage::Format Crop::computeFormat( const Gaffer::Context *context, const ImagePlug *parent ) const
{
	if ( ! affectDisplayWindowPlug()->getValue() )
	{
		// No-op because we are not applying this
		// crop to the display window
		return inPlug()->formatPlug()->getValue();
	}

	Imath::Box2i displayWindow = cropWindowPlug()->getValue();
	const Imath::V2i offset = offsetPlug()->getValue();

	displayWindow.max += offset;
	displayWindow.min += offset;

	return GafferImage::Format( displayWindow, inPlug()->formatPlug()->getValue().getPixelAspect() );
}

void Crop::hashDataWindow( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	ImageProcessor::hashDataWindow( parent, context, h );

	inPlug()->dataWindowPlug()->hash( h );
	cropWindowPlug()->hash( h );
	affectDataWindowPlug()->hash( h );
	affectDisplayWindowPlug()->hash( h );
	offsetPlug()->hash( h );
}

Imath::Box2i Crop::computeDataWindow( const Gaffer::Context *context, const ImagePlug *parent ) const
{
	Box2i result = inPlug()->dataWindowPlug()->getValue();
	const Box2i cropWindow = cropWindowPlug()->getValue();
	const V2i offset = offsetPlug()->getValue();
	if( affectDataWindowPlug()->getValue() )
	{
		result = BufferAlgo::intersection( result, cropWindow );
	}

	if( !BufferAlgo::empty( result ) )
	{
		result.min += offset;
		result.max += offset;
	}

	return result;
}

void Crop::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	ImageProcessor::hash( output, context, h );

	if ( output == cropWindowPlug() )
	{
		int areaSource = areaSourcePlug()->getValue();

		switch ( areaSource )
		{
			case Crop::DataWindow:
			{
				inPlug()->dataWindowPlug()->hash( h );
				break;
			}
			case Crop::DisplayWindow:
			{
				inPlug()->formatPlug()->hash( h );
				break;
			}
			case Crop::Format:
			{
				formatPlug()->hash( h );
				if( formatCenterPlug()->getValue() )
				{
					inPlug()->formatPlug()->hash( h );
				}
				break;
			}
			default:
			{
				areaPlug()->hash( h );
				break;
			}
		}
	}
	else if( output->parent<Plug>() == offsetPlug() )
	{
		ImagePlug::GlobalScope c( context );
		affectDisplayWindowPlug()->hash( h );
		resetOriginPlug()->hash( h );
		cropWindowPlug()->hash( h );
		if( areaSourcePlug()->getValue() == Crop::Format && formatCenterPlug()->getValue() )
		{
			inPlug()->formatPlug()->hash( h );
		}
	}
}

void Crop::compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const
{
	if ( output == cropWindowPlug() )
	{
		int areaSource = areaSourcePlug()->getValue();
		Imath::Box2i cropWindow;

		switch ( areaSource )
		{
			case Crop::DataWindow:
			{
				cropWindow = inPlug()->dataWindowPlug()->getValue();
				break;
			}
			case Crop::DisplayWindow:
			{
				cropWindow = inPlug()->formatPlug()->getValue().getDisplayWindow();
				break;
			}
			case Crop::Format:
			{
				cropWindow = formatPlug()->getValue().getDisplayWindow();
				if( formatCenterPlug()->getValue() )
				{
					const Imath::Box2i displayWindow = inPlug()->formatPlug()->getValue().getDisplayWindow();
					Imath::V2i centerOffset( cropWindow.center() - displayWindow.center() );

					cropWindow.min -= centerOffset;
					cropWindow.max -= centerOffset;
				}
				break;
			}
			default:
			{
				cropWindow = areaPlug()->getValue();
				break;
			}
		}

		static_cast<Gaffer::AtomicBox2iPlug *>( output )->setValue( cropWindow );
	}
	else if( output->parent<Plug>() == offsetPlug() )
	{
		ImagePlug::GlobalScope c( context );
		V2i offset( 0 );
		if( affectDisplayWindowPlug()->getValue() )
		{
			if( resetOriginPlug()->getValue() )
			{
				offset -= cropWindowPlug()->getValue().min;
			}
			else if( areaSourcePlug()->getValue() == Crop::Format && formatCenterPlug()->getValue() )
			{
				offset -= cropWindowPlug()->getValue().min - formatPlug()->getValue().getDisplayWindow().min;
			}
		}
		static_cast<IntPlug *>( output )->setValue(
			output == offsetPlug()->getChild( 0 ) ? offset[0] : offset[1]
		);
	}
	else
	{
		ImageProcessor::compute( output, context );
	}
}


text:
void test03()
{
  using namespace std;
  bool test __attribute__((unused)) = true;

  // Check time_get works with other iterators besides streambuf
  // input iterators.
  typedef string::const_iterator iter_type;
  typedef time_get<char, iter_type> time_get_type;
  const ios_base::iostate goodbit = ios_base::goodbit;
  ios_base::iostate err = goodbit;
  const locale loc_c = locale::classic();

  // Create "C" time objects
  const tm time_sanity = __gnu_test::test_tm(0, 0, 12, 26, 5, 97, 2, 0, 0);
  tm tm1;

  istringstream iss;
  iss.imbue(locale(loc_c, new time_get_type));

  // Iterator advanced, state, output.
  const time_get_type& tg = use_facet<time_get_type>(iss.getloc());

  // Cindy Sherman's Untitled Film Stills
  // June 26-September 2, 1997
  const string str = "1997 Cindy Sherman";

  // 05 get_year
  string res5;
  err = goodbit;
  // White space is not eaten, so manually increment past it.
  iter_type end5 = tg.get_year(str.begin(), str.end(), iss, err, &tm1);
  string rem5(end5, str.end());
  VERIFY( err == goodbit );
  VERIFY( tm1.tm_year == time_sanity.tm_year );
  VERIFY( rem5 ==  " Cindy Sherman" );
}

int main()
{
  test03();
  return 0;
}


text:
package com.amazonaws.services.chimesdkmessaging.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.chimesdkmessaging.model.*;

import com.amazonaws.util.IdempotentUtils;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CreateChannelRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateChannelRequestMarshaller {

    private static final MarshallingInfo<String> APPINSTANCEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AppInstanceArn").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<String> MODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Mode").build();
    private static final MarshallingInfo<String> PRIVACY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Privacy").build();
    private static final MarshallingInfo<String> METADATA_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Metadata").build();
    private static final MarshallingInfo<String> CLIENTREQUESTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ClientRequestToken")
            .defaultValueSupplier(com.amazonaws.util.IdempotentUtils.getGenerator()).build();
    private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Tags").build();
    private static final MarshallingInfo<String> CHIMEBEARER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.HEADER).marshallLocationName("x-amz-chime-bearer").build();
    private static final MarshallingInfo<String> CHANNELID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ChannelId").build();
    private static final MarshallingInfo<List> MEMBERARNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("MemberArns").build();
    private static final MarshallingInfo<List> MODERATORARNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ModeratorArns").build();
    private static final MarshallingInfo<StructuredPojo> ELASTICCHANNELCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ElasticChannelConfiguration").build();

    private static final CreateChannelRequestMarshaller instance = new CreateChannelRequestMarshaller();

    public static CreateChannelRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CreateChannelRequest createChannelRequest, ProtocolMarshaller protocolMarshaller) {

        if (createChannelRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(createChannelRequest.getAppInstanceArn(), APPINSTANCEARN_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getName(), NAME_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getMode(), MODE_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getPrivacy(), PRIVACY_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getMetadata(), METADATA_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getChimeBearer(), CHIMEBEARER_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getChannelId(), CHANNELID_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getMemberArns(), MEMBERARNS_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getModeratorArns(), MODERATORARNS_BINDING);
            protocolMarshaller.marshall(createChannelRequest.getElasticChannelConfiguration(), ELASTICCHANNELCONFIGURATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
@import Cocoa;

@class EVTEvent;

@interface EVTEventsViewController : NSViewController

- (void)playLiveEvent:(EVTEvent *)event;
- (void)playOnDemandEvent:(EVTEvent *)event;
- (void)showEvent:(EVTEvent *)event;

@end


text:
package cognitivej.core;

import org.jetbrains.annotations.NotNull;

public abstract class CognitiveResult {

    @NotNull
    public final Class resultType() {
        return getClass();
    }
}


text:
<?php

namespace Nette\Web;

use Nette;

/**
 * HTTP-specific tasks.
 *
 * @copyright  Copyright (c) 2004, 2010 David Grudl
 * @package    Nette\Web
 */
class HttpContext extends Nette\Object
{

	/**
	 * Attempts to cache the sent entity by its last modification date
	 * @param  string|int|DateTime  last modified time
	 * @param  string  strong entity tag validator
	 * @return bool
	 */
	public function isModified($lastModified = NULL, $etag = NULL)
	{
		$response = $this->getResponse();
		$request = $this->getRequest();

		if ($lastModified) {
			$response->setHeader('Last-Modified', $response->date($lastModified));
		}
		if ($etag) {
			$response->setHeader('ETag', '"' . addslashes($etag) . '"');
		}

		$ifNoneMatch = $request->getHeader('If-None-Match');
		if ($ifNoneMatch === '*') {
			$match = TRUE; // match, check if-modified-since

		} elseif ($ifNoneMatch !== NULL) {
			$etag = $response->getHeader('ETag');

			if ($etag == NULL || strpos(' ' . strtr($ifNoneMatch, ",\t", '  '), ' ' . $etag) === FALSE) {
				return TRUE;

			} else {
				$match = TRUE; // match, check if-modified-since
			}
		}

		$ifModifiedSince = $request->getHeader('If-Modified-Since');
		if ($ifModifiedSince !== NULL) {
			$lastModified = $response->getHeader('Last-Modified');
			if ($lastModified != NULL && strtotime($lastModified) <= strtotime($ifModifiedSince)) {
				$match = TRUE;

			} else {
				return TRUE;
			}
		}

		if (empty($match)) {
			return TRUE;
		}

		$response->setCode(IHttpResponse::S304_NOT_MODIFIED);
		return FALSE;
	}

	/********************* backend ****************d*g**/

	/**
	 * @return Nette\Web\IHttpRequest
	 */
	public function getRequest()
	{
		return Nette\Environment::getHttpRequest();
	}

	/**
	 * @return Nette\Web\IHttpResponse
	 */
	public function getResponse()
	{
		return Nette\Environment::getHttpResponse();
	}

}


text: Interview Questions


text:
namespace Lost.Rust.Cargo
{
	using System;
	using System.Text.RegularExpressions;

	public class MailAddress
	{
		public MailAddress(string address, string displayName = null)
		{
			var match = GetAddressMatch(address);
			if (match.Index != 0 || match.Length != address.Length)
				throw new FormatException(address + " is not a valid email address");

			this.Address = address;
			this.DisplayName = displayName;
		}
		public string Address { get; private set; }
		public string DisplayName { get; private set; }

		public override string ToString()
		{
			return this.DisplayName != null
				? this.DisplayName + " <" + this.Address + ">"
				: this.Address;
		}

		static readonly Regex mailRegex = new Regex(
			@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
			RegexOptions.IgnoreCase);
		public static MailAddress Parse(string address)
		{
			var addressMatch = GetAddressMatch(address);

			if (addressMatch.Index == 0)
				return new MailAddress(address);

			var tail = address.Substring(addressMatch.Index + addressMatch.Length).Trim();
			if (tail != "" && tail != ">")
				throw new FormatException(address + " is not a valid email address");

			int nameEnd = address.LastIndexOf('<', addressMatch.Index, addressMatch.Index - 1);
			if (nameEnd < 0)
				throw new FormatException( address + " is not a valid email address");
			if (nameEnd == 0)
				return new MailAddress(addressMatch.Value);

			var name = address.Substring(0, nameEnd - 1).Trim();
			return new MailAddress(addressMatch.Value, name == "" ? null: name);
		}

		static Match GetAddressMatch(string address)
		{
			if (address == null)
				throw new ArgumentNullException("address");

			if (address.Length > 2048)
				throw new ArgumentException("Value is too long", "address");

			var addressMatch = mailRegex.Match(address);
			if (!addressMatch.Success)
				throw new FormatException(address + " does not contain a valid email address");

			return addressMatch;
		}

		public override bool Equals(object obj)
		{
			var otherMail = obj as MailAddress;
			if (otherMail == null)
				return false;
			return this.Address == otherMail.Address;
		}

		public override int GetHashCode()
		{
			return this.Address.GetHashCode() ^ 0x563a;
		}
	}
}


text:
// Aleth: Ethereum C++ client, tools and libraries.
// Copyright 2014-2019 Aleth Authors.
// Licensed under the GNU General Public License, Version 3.

#pragma once

#include <string>
#include <libdevcore/FixedHash.h>
#include <libethcore/Common.h>

namespace dev
{
namespace eth
{

/// The network id.
enum class Network
{
    qtumNetwork = 1
};

std::string const& genesisInfo(Network _n);
h256 const& genesisStateRoot(Network _n);

/// Set the improvements activation blocks for Qtum
struct EVMConsensus
{
    EVMConsensus() {}
    EVMConsensus(int nHeight) :
        QIP6Height(nHeight),
        QIP7Height(nHeight),
        nMuirGlacierHeight(nHeight),
        nLondonHeight(nHeight)
    {}

    int QIP6Height = 0x7fffffff;
    int QIP7Height = 0x7fffffff;
    int nMuirGlacierHeight = 0x7fffffff;
    int nLondonHeight = 0x7fffffff;
};

/**
 * @brief genesisInfoQtum Get the genesis information for EVM
 * @param _n Network type
 * @param _consensus Qtum network consensus parameters (mainnet, testnet, signet or regtest parameters)
 * @return Genesis information for EVM
 */
std::string genesisInfoQtum(Network _n, EVMConsensus _consensus);

}
}


text:
package net.codebox.homoglyph;

import java.io.*;
import java.util.*;

/**
 * Helper class providing methods that supply populated Homoglyph objects.
 *
 * @author Rob Dawson
 */
public class HomoglyphBuilder {
    private static final String CHAR_CODES_FILE = "/char_codes.txt";

    /**
     * Parses the bundled char_codes.txt file, and uses it to construct a populated Homoglyph object.
     *
     * @return a Homoglyph object populated using the contents of the char_codes.txt file
     *
     * @throws MissingResourceException if the char_codes.txt file is missing
     * @throws IOException if the char_codes.txt exists but cannot be read
     */
    public static Homoglyph build() throws IOException {
        final InputStream is = HomoglyphBuilder.class.getResourceAsStream(CHAR_CODES_FILE);
        if (is == null){
            throw new MissingResourceException("Unable to read " + CHAR_CODES_FILE,
                    HomoglyphBuilder.class.getName(), CHAR_CODES_FILE);
        }

        return build(new InputStreamReader(is));
    }

    /**
     * Parses the specified file and uses it to construct a populated Homoglyph object.
     *
     * @param path the path to a file containing a list of homoglyphs (see the bundled char_codes.txt
     *             file for an example of the required format)
     *
     * @return a Homoglyph object populated using the contents of the specified file
     *
     * @throws IOException if the specified file cannot be read
     */
    public static Homoglyph build(final String path) throws IOException {
        return build(new FileReader(path));
    }

    /**
     * Consumes the supplied Reader and uses it to construct a populated Homoglyph object.
     *
     * @param reader a Reader object that provides access to homoglyph data (see the bundled
     *               char_codes.txt file for an example of the required format)
     *
     * @return a Homoglyph object populated using the data returned by the Reader object
     *
     * @throws IOException if the specified Reader cannot be read
     */
    public static Homoglyph build(final Reader reader) throws IOException {
        final List<Set<Integer>> homoglyphs = new ArrayList<>();

        try (final BufferedReader bufferedReader = new BufferedReader(reader)) {
            String line;
            while((line = bufferedReader.readLine()) != null){
                line = line.trim();
                if (line.startsWith("#") || line.length() == 0){
                    continue;
                }
                final Set<Integer> set = new HashSet<>();
                for (String charCode : line.split(",")) {
                    try {
                        set.add(Integer.parseInt(charCode, 16));
                    } catch (NumberFormatException ex){
                        // ignore badly formatted lines
                    }
                }
                homoglyphs.add(set);
            }
        }

        return new Homoglyph(homoglyphs);
    }

}


text:
Dotfiles
========

System configuration files.


text:
using GgcmsCSharp.Models;
using GgcmsCSharp.Utils;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;

namespace GgcmsCSharp.ApiCtrls
{
    public class GgcmsTopicsController : ApiBaseController
    {

        // GET: api/GgcmsCategories
        [HttpGet]
        public IHttpActionResult GetList(string query)
        {
            string json = HttpUtility.UrlDecode(query);
            SearchParams sParams = Tools.JsonDeserialize<SearchParams>(json);

            return Ok(GetRecords<GgcmsTopics>(sParams));
        }

        // GET: api/GgcmsCategories/5
        public IHttpActionResult GetInfo(int id)
        {
            return Ok(Dbctx.GgcmsTopics.Find(id));
        }

        // PUT: api/GgcmsCategories/5
        public IHttpActionResult Edit(GgcmsTopics info)
        {
            if (Dbctx.GgcmsTopics.Where(x => x.Id == info.Id).Count() == 0)
            {
                return BadRequest("信息不存在");
            }
            //Dbctx.GgcmsTopics.Attach(info);
            //Dbctx.Entry(info).Property("goods_name").IsModified = true;
            var ent = Dbctx.Entry(info);
            ent.State = EntityState.Modified;
            Dbctx.SaveChanges();
            ClearCache();
            return Ok(info);
        }

        // POST: api/GgcmsCategories
        public IHttpActionResult Add(GgcmsTopics info)
        {
            var result = Dbctx.GgcmsTopics.Add(info);
            Dbctx.SaveChanges();
            ClearCache();
            return Ok(result);
        }

        // DELETE: api/GgcmsCategories/5
        public IHttpActionResult Delete(int id)
        {
            GgcmsTopics oldinfo = Dbctx.GgcmsTopics.Find(id);
            if (oldinfo == null)
            {
                return BadRequest("信息不存在");
            }

            //List<int> idlist = GetDeleteIds(oldinfo.ticket_key);

            //var query = Dbctx.ticket_information.Where(x => idlist.Contains(x.id));
            Dbctx.GgcmsTopics.Remove(oldinfo);
            Dbctx.SaveChanges();
            ClearCache();
            return Ok(oldinfo);
        }
        [HttpPost]
        public IHttpActionResult MultDelete(int[] ids)
        {
            var query = Dbctx.GgcmsTopics.Where(x => ids.Contains(x.Id));

            Dbctx.GgcmsTopics.RemoveRange(query);
            int c = Dbctx.SaveChanges();
            ClearCache();
            return Ok(c);
        }

        public IHttpActionResult Exists(int id)
        {
            return Ok(Dbctx.GgcmsTopics.Where(x => x.Id == id).Count() > 0);
        }
    }
}


text: Bonke abantu bazalwa bekhululekile belingana ngesithunzi nangamalungelo. Bahlanganiswe wumcabango nangunembeza futhi kufanele baphathane ngomoya wobunye.


text:
/*
 * @author max
 */
package com.intellij.psi;

import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubElement;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public interface StubBasedPsiElement<Stub extends StubElement> extends PsiElement {
  @Nonnull
  IStubElementType getElementType();

  @Nullable
  Stub getStub();

  /**
   * Like {@link #getStub()}, but can return a non-null value after the element has been switched to AST. Can be used
   * to retrieve the information which is cheaper to get from a stub than by tree traversal.
   */
  @Nullable
  default Stub getGreenStub() {
    return getStub();
  }
}


text:
const EventEmitter = require('events');

/**
 * An interface class for volume transformation.
 * @extends {EventEmitter}
 */
class VolumeInterface extends EventEmitter {
  constructor({ volume = 0 } = {}) {
    super();
    this.setVolume(volume || 1);
  }

  /**
   * The current volume of the broadcast
   * @readonly
   * @type {number}
   */
  get volume() {
    return this._volume;
  }

  /**
   * The current volume of the broadcast in decibels
   * @readonly
   * @type {number}
   */
  get volumeDecibels() {
    return Math.log10(this._volume) * 20;
  }

  /**
   * The current volume of the broadcast from a logarithmic scale
   * @readonly
   * @type {number}
   */
  get volumeLogarithmic() {
    return Math.pow(this._volume, 1 / 1.660964);
  }

  applyVolume(buffer, volume) {
    volume = volume || this._volume;
    if (volume === 1) return buffer;

    const out = Buffer.alloc(buffer.length);
    for (let i = 0; i < buffer.length; i += 2) {
      if (i >= buffer.length - 1) break;
      const uint = Math.min(32767, Math.max(-32767, Math.floor(volume * buffer.readInt16LE(i))));
      out.writeInt16LE(uint, i);
    }

    return out;
  }

  /**
   * Sets the volume relative to the input stream - i.e. 1 is normal, 0.5 is half, 2 is double.
   * @param {number} volume The volume that you want to set
   */
  setVolume(volume) {
    /**
     * Emitted when the volume of this interface changes.
     * @event VolumeInterface#volumeChange
     * @param {number} oldVolume The old volume of this interface
     * @param {number} newVolume The new volume of this interface
     */
    this.emit('volumeChange', this._volume, volume);
    this._volume = volume;
  }

  /**
   * Set the volume in decibels.
   * @param {number} db The decibels
   */
  setVolumeDecibels(db) {
    this.setVolume(Math.pow(10, db / 20));
  }

  /**
   * Set the volume so that a perceived value of 0.5 is half the perceived volume etc.
   * @param {number} value The value for the volume
   */
  setVolumeLogarithmic(value) {
    this.setVolume(Math.pow(value, 1.660964));
  }
}

module.exports = VolumeInterface;


text:
<!doctype html>

    <title>Code coverage report for ./src/client/app/blocks/logger/logger.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../../../prettify.css">
    <link rel="stylesheet" href="../../../../../base.css">

Code coverage report for ./src/client/app/blocks/logger/logger.js

        Statements: 55.56% (10 / 18)
        Branches: 100% (0 / 0)
        Functions: 33.33% (2 / 6)
        Lines: 55.56% (10 / 18)
        Ignored: none

All files » ./src/client/app/blocks/logger/ » logger.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48	1

1

1

1
8

8

1

1

1

1

(function() {
    'use strict';

    angular
        .module('blocks.logger')
        .factory('logger', logger);

    logger.$inject = ['$log', 'toastr'];

    /* @ngInject */
    function logger($log, toastr) {
        var service = {
            showToasts: true,

            error   : error,
            info    : info,
            success : success,
            warning : warning,

            // straight to console; bypass toastr
            log     : $log.log
        };

        return service;
        /////////////////////

        function error(message, data, title) {
            toastr.error(message, title);
            $log.error('Error: ' + message, data);
        }

        function info(message, data, title) {
            toastr.info(message, title);
            $log.info('Info: ' + message, data);
        }

        function success(message, data, title) {
            toastr.success(message, title);
            $log.info('Success: ' + message, data);
        }

        function warning(message, data, title) {
            toastr.warning(message, title);
            $log.warn('Warning: ' + message, data);
        }
    }
}());

Generated by istanbul at Thu Dec 17 2015 20:57:37 GMT+0000 (Greenwich Standard Time)


text:
using Renci.SshNet.Common;
using System;

namespace Renci.SshNet
{
    /// <summary>
    /// Provides additional information for asynchronous command execution
    /// </summary>
    public class ExpectAsyncResult : AsyncResult<string>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ExpectAsyncResult" /> class.
        /// </summary>
        /// <param name="asyncCallback">The async callback.</param>
        /// <param name="state">The state.</param>
        internal ExpectAsyncResult(AsyncCallback asyncCallback, Object state)
            : base(asyncCallback, state)
        {
        }
    }
}


text:
package org.docksidestage.db2.dbflute.vendor;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

import org.docksidestage.db2.dbflute.bsentity.dbmeta.PurchaseDbm;
import org.docksidestage.db2.unit.UnitContainerTestCase;

/**
 * @author jflute
 * @since 0.6.1 (2008/01/23 Wednesday)
 */
public class VendorMetaDataTest extends UnitContainerTestCase {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    private Connection _conn;

    // ===================================================================================
    //                                                                            Settings
    //                                                                            ========
    @Override
    public void setUp() throws Exception {
        super.setUp();
        _conn = getDataSource().getConnection();
    }

    @Override
    public void tearDown() throws Exception {
        if (_conn != null) {
            _conn.close();
            _conn = null;
        }
        super.tearDown();
    }

    // ===================================================================================
    //                                                                    DatabaseMetaData
    //                                                                    ================
    // -----------------------------------------------------
    //                                             DBMS Info
    //                                             ---------
    public void test_DatabaseMetaData_databaseInfo() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        log("getDatabaseProductName(): " + metaData.getDatabaseProductName());
        log("getDatabaseProductVersion(): " + metaData.getDatabaseProductVersion());
        log("getDatabaseMajorVersion(): " + metaData.getDatabaseMajorVersion());
        log("getDatabaseMinorVersion(): " + metaData.getDatabaseMinorVersion());
    }

    // -----------------------------------------------------
    //                                             JDBC Info
    //                                             ---------
    public void test_DatabaseMetaData_jdbcInfo() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        log("getDriverName(): " + metaData.getDriverName());
        log("getDriverVersion(): " + metaData.getDriverVersion());
        log("getJDBCMajorVersion(): " + metaData.getJDBCMajorVersion());
        log("getJDBCMinorVersion(): " + metaData.getJDBCMinorVersion());
    }

    // -----------------------------------------------------
    //                                             Max Thing
    //                                             ---------
    public void test_DatabaseMetaData_maxThing() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        log("getMaxStatementLength(): " + metaData.getMaxStatementLength());
        log("getMaxTableNameLength(): " + metaData.getMaxTableNameLength());
    }

    // -----------------------------------------------------
    //                                                  Term
    //                                                  ----
    public void test_DatabaseMetaData_term() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        log("getCatalogTerm(): " + metaData.getCatalogTerm()); // null
        log("getSchemaTerm(): " + metaData.getSchemaTerm());
        log("getProcedureTerm(): " + metaData.getProcedureTerm());
    }

    // -----------------------------------------------------
    //                                           getTables()
    //                                           -----------
    public void test_DatabaseMetaData_getTables_basic() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        // if it sets valid catalog, returns empty
        ResultSet rs = metaData.getTables(null, "DFEXDB", "%", new String[] { "TABLE", "VIEW" });
        log("[Table]");
        boolean exists = false;
        while (rs.next()) {
            exists = true;
            String catalog = rs.getString("TABLE_CAT"); // null
            String schema = rs.getString("TABLE_SCHEM");
            String name = rs.getString("TABLE_NAME");
            String comment = rs.getString("REMARKS");
            log("catalog=" + catalog + ", schema=" + schema + ", table=" + name + ", comment=" + comment);
            assertNull(catalog);
            assertNotNull(schema);
            assertNotNull(name);
        }
        assertTrue(exists);
    }

    // -----------------------------------------------------
    //                                     getImportedKeys()
    //                                     -----------------
    public void test_DatabaseMetaData_getImportedKeys_basic() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        String tableDbName = PurchaseDbm.getInstance().getTableDbName();
        ResultSet rs = metaData.getImportedKeys(null, "DFEXDB", tableDbName);
        boolean exists = false;
        int count = 0;
        Set<String> fkSet = new HashSet<String>();
        while (rs.next()) {
            exists = true;
            String catalog = rs.getString(1); // null
            String schema = rs.getString(2);
            String foreignTable = rs.getString(3);
            String foreignColumn = rs.getString(4);
            String fkName = rs.getString(12);

            ++count;
            fkSet.add(fkName);

            log("[" + fkName + "]");
            log("  catalog=" + catalog + ", schema=" + schema);
            log("  foreignTable=" + foreignTable + ", foreignColumn=" + foreignColumn);
            assertNotNull(fkName);
            assertNull(catalog);
            assertNotNull(schema);
            assertNotNull(foreignTable);
            assertNotNull(foreignColumn);
        }
        assertTrue(exists);
        // DB2 returns to-ALIAS foreign key as same FK name
        assertNotSame(count, fkSet.size());
    }

    // -----------------------------------------------------
    //                                       getProcedures()
    //                                       ---------------
    public void test_DatabaseMetaData_getProcedures_mainSchema() throws SQLException {
        DatabaseMetaData metaData = _conn.getMetaData();
        ResultSet rs = metaData.getProcedures(null, "DFEXDB", null);
        boolean exists = false;
        log("[Procedure]");
        while (rs.next()) {
            exists = true;
            String catalog = rs.getString("PROCEDURE_CAT"); // null
            String schema = rs.getString("PROCEDURE_SCHEM");
            String procedure = rs.getString("PROCEDURE_NAME");
            log("catalog=" + catalog + ", schema=" + schema + ", procedure=" + procedure);
            assertNull(catalog);
            assertNotNull(schema);
            assertNotNull(procedure);
        }
        assertTrue(exists);
    }

    // ===================================================================================
    //                                                                        SYSCAT Table
    //                                                                        ============
    public void test_SYSCAT_ROUTINES_procedure_source() throws Exception {
        // ## Arrange ##
        Statement st = null;
        ResultSet rs = null;
        try {
            st = _conn.createStatement();

            // ## Act ##
            rs = st.executeQuery("select * from SYSCAT.ROUTINES where ROUTINESCHEMA ='DFEXDB'");

            // ## Assert ##
            while (rs.next()) {
                String name = rs.getString("ROUTINENAME");
                String text = rs.getString("TEXT");
                log(name + ":" + ln() + text);
            }
        } finally {
            if (st != null) {
                st.close();
            }
            if (rs != null) {
                rs.close();
            }
        }
    }
}


text:
<?php

use Cekurte\Environment\Environment;
use Cekurte\Silex\Manager\Provider\ManagerServiceProvider;
use Cekurte\TwitterLike\Application;
use Cekurte\TwitterLike\ControllerProvider\ApiControllerProvider;
use Cekurte\TwitterLike\ControllerProvider\PageControllerProvider;
use Symfony\Component\HttpFoundation\Request;

$app = new Application();

$app['debug']       = Environment::get('APP_DEBUG');
$app['projectName'] = Environment::get('APP_PROJECT_NAME');

$app['cekurte.manager.providers'] = require CONFIG_PATH . DS . 'manager.php';

$app->register(new ManagerServiceProvider());

Request::enableHttpMethodParameterOverride();

require CONFIG_PATH . DS . 'error.php';

$app->mount('/', new PageControllerProvider());

$app->mount('/api', new ApiControllerProvider());

$app->after($app["cors"]);

return $app;


text:
#include <catch.hpp>

#include <lorina/verilog.hpp>
#include <mockturtle/algorithms/simulation.hpp>
#include <mockturtle/algorithms/xag_optimization.hpp>
#include <mockturtle/io/verilog_reader.hpp>
#include <mockturtle/networks/xag.hpp>

#include <algorithm>
#include <vector>

using namespace mockturtle;

TEST_CASE( "Edge cases for linear resynthesis", "[xag_optimization]" )
{
  {
    xag_network xag;
    std::vector<xag_network::signal> pis( 4u );
    std::generate( pis.begin(), pis.end(), [&]() { return xag.create_pi(); } );
    xag.create_po( xag.create_nary_and( pis ) );

    const auto opt = exact_linear_resynthesis_optimization( xag );
    CHECK( simulate<kitty::static_truth_table<4>>( xag ) == simulate<kitty::static_truth_table<4u>>( opt ) );
  }

  {
    xag_network xag;
    std::vector<xag_network::signal> pis( 4u );
    std::generate( pis.begin(), pis.end(), [&]() { return xag.create_pi(); } );
    xag.create_po( xag.create_xor( xag.create_and( pis[0u], pis[1u] ), xag.create_and( pis[2u], pis[3u] ) ) );

    const auto opt = exact_linear_resynthesis_optimization( xag );
    CHECK( simulate<kitty::static_truth_table<4>>( xag ) == simulate<kitty::static_truth_table<4u>>( opt ) );
  }
}

TEST_CASE( "Test XAG constant fanin optimization", "[xag_optimization]" )
{
  /* regression test that leads to a segmentation violation */
  std::string const test_case =
      "module top( x0 , x1 , y0 );\n"
      "  input x0 , x1 ;\n"
      "  output y0 ;\n"
      "  wire n2 , n3 , n4 , n5 , n6 , n7 ;\n"
      "  assign n2 = x1 ^ x0 ;\n"
      "  assign n3 = n2 ^ x1 ;\n"
      "  assign n4 = n3 ^ n2 ;\n"
      "  assign n5 = n2 & n4 ;\n"
      "  assign n6 = n5 ^ n2 ;\n"
      "  assign n7 = n6 ^ n2 ;\n"
      "  assign y0 = n7 ;\n"
      "endmodule\n";

  std::stringstream ss( test_case );
  mockturtle::xag_network xag;
  CHECK( lorina::read_verilog( ss, mockturtle::verilog_reader( xag ) ) == lorina::return_code::success );
  xag_constant_fanin_optimization( xag );
}


text:
import os

# Stupid and useless code that could be changed with something more serious to compare
# the tablemaps from sqlalchemy... Consider it deprecated:
class File:
	def __init__(self, file_path, mode):
		self.file = open(file_path, mode)
		self.content = self.file.readlines()
		self.file.close()
	def __eq__(self, other):
		return isinstance(other, self.__class__) and self.content == other.content
	def __hash__(self):
		return hash(self.content)


text:
package com.google.appengine.api.search.dev;

/**
 * Thrown to indicate that a search service failure occurred while performing
 * a search request.
 */
public class SearchException extends RuntimeException {
  private static final long serialVersionUID = -4578358065034269369L;

  public SearchException(String message) {
    super(message);
  }

}


text:
'use strict';

const models = require('./index');

/**
 * Response for list BGP peer status API service call
 *
 */
class BgpPeerStatusListResult {
  /**
   * Create a BgpPeerStatusListResult.
   * @member {array} [value] List of BGP peers
   */
  constructor() {
  }

  /**
   * Defines the metadata of BgpPeerStatusListResult
   *
   * @returns {object} metadata of BgpPeerStatusListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'BgpPeerStatusListResult',
      type: {
        name: 'Composite',
        className: 'BgpPeerStatusListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: 'value',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'BgpPeerStatusElementType',
                  type: {
                    name: 'Composite',
                    className: 'BgpPeerStatus'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = BgpPeerStatusListResult;


text:
.container{
text-align: center;
vertical-align: center;
}

.countText{
	font-size: 15em;
    font-weight: bold;
}

.resetButton, .incrementButton{
	font-size: 3em;
	width: 100%;
	height: 20%;
    border: none;
	height: 100px;
	border-radius: 10px;
	margin-top: 10px;
}

.resetButton{
	color: white;
	background-color: #FF3333;
}

.incrementButton{
	color: white;
	background-color: #3399FF;
}


text:
<hgroup id="main-title" class="thin">

Resizing events

</hgroup>

Window resize event

Listening to window.resize events can be cumbersome, because it is trigerred many times when resizing the window, which results in a huge work load for the website. Some older browsers even trigger this event multiple times for each resizing...

To make working with this event easier, the template does all the work of listening and smoothing the event, and send 2 custom events:

normalized-preresize

This is mostly an internal event, designed for respond.js. It fires before the template does all the work required in case of window resizing.

normalized-resize

This is the event you should use when listening to window.resize. It is sent once every 40ms each time the window is resized, and only once media queries have been applied.

These events are also trigerred when the user tilts a mobile device (event 'orientationchange').

To use them, listen on the window element:

$(window).on('normalized-resize', function(event) { ... });

Element resize event

Aside from window resizing, the template also provides a way to watch an element and send custom events when its size changes. Several element size events are available:

sizechange

This event is fired each time one or both dimensions of an element change

widthchange

This event is fired each time the width of an element changes

heightchange

This event is fired each time the height of an element changes

scrollsizechange

This event is fired each time one or both scroll sizes of an element change (listen to scrollWidth and scrollHeight)

To use them, you may either use jQuery bind methods:

$(selector).on('sizechange', function(event) { ... });

Or use the helper methods (there is one for each event type):

$(selector).sizechange(function(event) { ... });


text:
@interface LjsGoogleManagerInitTests : LjsTestCase {}
@end

@implementation LjsGoogleManagerInitTests

- (BOOL)shouldRunOnMainThread {
  // By default NO, but if you have a UI test or test dependent on running on the main thread return YES
  return NO;
}

- (void) setUpClass {
  [super setUpClass];
  // Run at start of all tests in the class
}

- (void) tearDownClass {
  // Run at end of all tests in the class
  [super tearDownClass];
}

- (void) setUp {
  [super setUp];
  // Run before each test method
}

- (void) tearDown {
  // Run after each test method
  [super tearDown];
}

@end