text:
import { HomeComponent } from './pages/home/home.component';
import { ContainerOptionsComponent } from './pages/container-options/container-options.component';
import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'

import { ContainersComponent } from './pages/containers/containers.component'
import { ContainerLogsComponent } from './pages/container-logs/container-logs.component'
import { ImagesComponent } from './pages/images/images.component';

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'containers', component: ContainersComponent },
    { path: 'containerOptions', component: ContainerOptionsComponent },
    { path: 'containerLogs/:id', component: ContainerLogsComponent },
    { path: 'images', component: ImagesComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

redpajama_set_name: RedPajamaGithub


text:
package uk.ac.soton.ecs.jsh2.makeitdigital.vision;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.openimaj.content.slideshow.PictureSlide;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.content.slideshow.VideoSlide;
import org.openimaj.video.VideoDisplay.EndAction;

/**
 * BBC Make It Digital: Computer Vision Talk
 */
public class App {
	private static BufferedImage background = null;
	static int SLIDE_WIDTH;
	static int SLIDE_HEIGHT;

	static {
		final GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
		final Dimension size = device.getDefaultConfiguration().getBounds().getSize();

		SLIDE_WIDTH = size.width;
		SLIDE_HEIGHT = SLIDE_WIDTH * 9 / 16;
	}

	/**
	 * Main method
	 *
	 * @param args
	 *            ignored
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		final List<Slide> slides = new ArrayList<Slide>();

		slides.add(new PictureSlide(App.class.getResource("slides/slides.001.jpg")));
		slides.add(new PictureSlide(App.class.getResource("slides/slides.002.jpg")));
		slides.add(new PictureSlide(App.class.getResource("slides/slides.003.jpg")));
		slides.add(new BadTomatoDemo(App.class.getResource("slides/slides.004.jpg")));
		slides.add(new VideoSlide(App.class.getResource("tomato.mp4"), App.class.getResource("slides/slides.005.jpg"),
				EndAction.PAUSE_AT_END));
		slides.add(new PictureSlide(App.class.getResource("slides/slides.006.jpg")));
		slides.add(new VideoSlide(App.class.getResource("car.mp4"), App.class.getResource("slides/slides.007.jpg"),
				EndAction.PAUSE_AT_END));
		slides.add(new InmoovDemo(App.class.getResource("slides/slides.008.jpg")));

		slides.add(new PictureSlide(App.class.getResource("slides/slides.009.jpg")));
		slides.add(new ArtARDemo(App.class.getResource("slides/slides.010.jpg")));
		slides.add(new StickyFeaturesDemo(App.class.getResource("slides/slides.011.jpg")));
		slides.add(new PictureSlide(App.class.getResource("slides/slides.012.jpg")));
		slides.add(new PictureSlide(App.class.getResource("slides/slides.013.jpg")));
		slides.add(new CLMDemo(App.class.getResource("slides/slides.014.jpg")));
		slides.add(new PuppeteerDemo(App.class.getResource("slides/slides.015.jpg"))); // TODO
																						// someone
																						// other
																						// than
																						// Mark
		slides.add(new PictureSlide(App.class.getResource("slides/slides.016.jpg")));

		new SlideshowApplication(slides, SLIDE_WIDTH, SLIDE_HEIGHT, getBackground());
	}

	/**
	 * @return the generic slide background
	 */
	public synchronized static BufferedImage getBackground() {
		if (background == null) {
			background = new BufferedImage(SLIDE_WIDTH, SLIDE_HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
			final Graphics2D g = background.createGraphics();
			g.setColor(Color.WHITE);
			g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			g.fillRect(0, 0, background.getWidth(), background.getHeight());

			final URL bgImageUrl = App.class.getResource("background.jpg");
			try {
				final BufferedImage b = ImageIO.read(bgImageUrl);
				g.drawImage(b, 0, 0, SLIDE_WIDTH, SLIDE_HEIGHT, null);
			} catch (final IOException e) {
			}
		}
		return background;
	}

	public static int getVideoWidth(int remainder) {
		final int avail = SLIDE_WIDTH - remainder;
		if (avail > 1280)
			return 1280;
		if (avail > 960)
			return 960;
		if (avail > 640)
			return 640;
		return 320;
	}

	public static int getVideoHeight(int remainder) {
		final int width = getVideoWidth(remainder);
		switch (width) {
		case 1280:
			return 720;
		case 960:
			return 540;
		case 640:
			return 480;
		}
		return 240;
	}
}


text:
package controller;

import data.Article;
import java.net.URL;
import java.util.ResourceBundle;

import animations.FadeInUpTransition;
import util.CustomButtonCell;
import util.CustomImageCell;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import javafx.util.Callback;
import manager.DataManager;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

public class ArticleTable implements Initializable {

	@FXML
	private AnchorPane mainPane;

	@FXML
	private TableColumn<Article, String> col_brand;

	@FXML
	private TableColumn<Article, String> col_name;

	@FXML
	private TableColumn<Article, String> col_artNr;

	@FXML
	private TableColumn<Article, Boolean> col_found;

	@FXML
	private TableColumn<Article, Boolean> col_preview;

	@FXML
	private TableView<Article> tableView;

	@FXML
	private ProgressBar bar;

	@Override
	public void initialize(URL location, ResourceBundle resources) {

		Platform.runLater(() -> {
			selectWithService();
		});

	}

	private void setCellValueFactories() {
		col_brand.setCellValueFactory(new PropertyValueFactory("art_nr"));
		col_artNr.setCellValueFactory(new PropertyValueFactory("art_nr"));
		col_name.setCellValueFactory(new PropertyValueFactory("art_name_de"));
		col_found.setCellValueFactory(new PropertyValueFactory("found"));
		col_preview.setCellValueFactory(new PropertyValueFactory("found"));
	}

	private void load() {
		// changed to multiple selection mode
		tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
		// set cell value factories
		setCellValueFactories();

		// set Dummy Data for the TableView
		tableView.setItems(getData());

		// set the Row Factory of the table
		setRowFactory();

		// Set row selection as default
		setRowSelection();
	}

	/**
	 * Change the cell selection boolean value of TableView
	 */
	public void setRowSelection() {
		tableView.getSelectionModel().clearSelection();
		tableView.getSelectionModel().setCellSelectionEnabled(false);
	}

	/**
	 * Change the cell selection boolean value of TableView
	 */
	public void setCellSelection() {
		tableView.getSelectionModel().clearSelection();
		tableView.getSelectionModel().setCellSelectionEnabled(true);

	}

	/**
	 * Set Row Factory for the TableView
	 */
	public void setRowFactory() {

		col_preview.setCellFactory(new Callback<TableColumn<Article, Boolean>, TableCell<Article, Boolean>>() {

			@Override
			public TableCell<Article, Boolean> call(TableColumn<Article, Boolean> param) {

				TableCell<Article, Boolean> cell = new CustomButtonCell();

				return cell;
			}
		});

		col_found.setCellFactory(new Callback<TableColumn<Article, Boolean>, TableCell<Article, Boolean>>() {

			@Override
			public TableCell<Article, Boolean> call(TableColumn<Article, Boolean> param) {

				TableCell<Article, Boolean> cell = new CustomImageCell();

				return cell;
			}
		});
	}

	/**
	 * Provides the dummy Person data.
	 *
	 * @return
	 */
	public ObservableList<Article> getData() {

		return DataManager.getData();
	}

	private void selectWithService() {
		Service<Integer> service = new Service<Integer>() {
			@Override
			protected Task<Integer> createTask() {
				load();
		        mainPane.setOpacity(0);
				return new Task<Integer>() {
					@Override
					protected Integer call() throws Exception {
						Integer max = 500;
						if (max > 35) {
							max = 30;
						}
						updateProgress(0, max);
						for (int k = 0; k < max; k++) {
							Thread.sleep(40);
							updateProgress(k + 1, max);
						}
						return max;
					}
				};
			}
		};
		service.start();
		bar.progressProperty().bind(service.progressProperty());
		service.setOnRunning((WorkerStateEvent event) -> {
			// imgLoad.setVisible(true);
		});
		service.setOnSucceeded((WorkerStateEvent event) -> {
			// imgLoad.setVisible(false);
			new FadeInUpTransition(mainPane).play();
		});
	}
}


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for Batch.

---

## Getting Started

To build the SDK for Batch, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`

---

## Configuration

### Basic Information

These are the global settings for the Batch API.

``` yaml
openapi-type: arm
tag: package-2021-01
```

### Tag: package-2021-01

These settings apply only when `--tag=package-2021-01` is specified on the command line.

```yaml $(tag) == 'package-2021-01'
input-file:
  - Microsoft.Batch/stable/2021-01-01/BatchManagement.json
```

### Tag: package-2020-09

These settings apply only when `--tag=package-2020-09` is specified on the command line.

```yaml $(tag) == 'package-2020-09'
input-file:
  - Microsoft.Batch/stable/2020-09-01/BatchManagement.json
```

### Tag: package-2020-05

These settings apply only when `--tag=package-2020-05` is specified on the command line.

```yaml $(tag) == 'package-2020-05'
input-file:
  - Microsoft.Batch/stable/2020-05-01/BatchManagement.json
```

### Tag: package-2020-03

These settings apply only when `--tag=package-2020-03` is specified on the command line.

``` yaml $(tag) == 'package-2020-03'
input-file:
  - Microsoft.Batch/stable/2020-03-01/BatchManagement.json
```

### Tag: package-2019-08

These settings apply only when `--tag=package-2019-08` is specified on the command line.

``` yaml $(tag) == 'package-2019-08'
input-file:
  - Microsoft.Batch/stable/2019-08-01/BatchManagement.json
```

### Tag: package-2019-04

These settings apply only when `--tag=package-2019-04` is specified on the command line.

``` yaml $(tag) == 'package-2019-04'
input-file:
  - Microsoft.Batch/stable/2019-04-01/BatchManagement.json
```

### Tag: package-2018-12

These settings apply only when `--tag=package-2018-12` is specified on the command line.

``` yaml $(tag) == 'package-2018-12'
input-file:
  - Microsoft.Batch/stable/2018-12-01/BatchManagement.json
```

### Tag: package-2017-09

These settings apply only when `--tag=package-2017-09` is specified on the command line.

``` yaml $(tag) == 'package-2017-09'
input-file:
- Microsoft.Batch/stable/2017-09-01/BatchManagement.json
```

## Suppression

Note that this setting should be removed once [this GitHub bug](https://github.com/Azure/azure-openapi-validator/issues/68) is fixed.

``` yaml
directive:
  - suppress: R2063
    from: BatchManagement.json
    reason: Bug in linter
  - from:
      - 2017-09-01/BatchManagement.json
      - 2017-05-01/BatchManagement.json
      - 2017-01-01/BatchManagement.json
      - 2015-12-01/BatchManagement.json
    where:
      - $.definitions.Application
      - $.definitions.ApplicationPackage
    suppress:
      - R2020
    reason: Proxy resource written prior to ARM guidelines update and would require breaking changes to fix. The shape of the entity will be corrected in future next API versions.
  - from:
      - 2017-09-01/BatchManagement.json
      - 2017-05-01/BatchManagement.json
      - 2017-01-01/BatchManagement.json
      - 2015-12-01/BatchManagement.json
    where:
      - $.definitions.Application.properties
      - $.definitions.ApplicationPackage.properties
    suppress:
      - R3006
    reason: Proxy resource written prior to ARM guidelines update and would require breaking changes to fix. The shape of the entity will be corrected in future API versions.
  - suppress: OBJECT_MISSING_REQUIRED_PROPERTY
    from: BatchManagement.json
    where: $.definitions.UserAccount
    reason: This field contains a secret (password) and is not returned on a get (but is required on a PUT/PATCH). Previous discussions with the modelling team had said that this was the correct way to model this type of field.
```

### Tag: package-2017-05

These settings apply only when `--tag=package-2017-05` is specified on the command line.

``` yaml $(tag) == 'package-2017-05'
input-file:
- Microsoft.Batch/stable/2017-05-01/BatchManagement.json
```

### Tag: package-2017-01

These settings apply only when `--tag=package-2017-01` is specified on the command line.

``` yaml $(tag) == 'package-2017-01'
input-file:
- Microsoft.Batch/stable/2017-01-01/BatchManagement.json
```

### Tag: package-2015-12

These settings apply only when `--tag=package-2015-12` is specified on the command line.

``` yaml $(tag) == 'package-2015-12'
input-file:
- Microsoft.Batch/stable/2015-12-01/BatchManagement.json
```

---

# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-net
  - repo: azure-sdk-for-python
  - repo: azure-sdk-for-python-track2
  - repo: azure-sdk-for-java
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-node
  - repo: azure-sdk-for-js
  - repo: azure-sdk-for-ruby
    after_scripts:
      - bundle install && rake arm:regen_all_profiles['azure_mgmt_batch']
  - repo: azure-resource-manager-schemas
    after_scripts:
      - node sdkauto_afterscript.js batch/resource-manager
```

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  # last generated with AutoRest.1.0.0-Nightly20170129 from commit 19f63015ea5a8a0fc64b9d7e2cdfeac447d93eaf
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.Azure.Management.Batch
  payload-flattening-threshold: 1
  output-folder: $(csharp-sdks-folder)/batch/Microsoft.Azure.Management.Batch/src/Generated
  clear-output-folder: true
```

## Go

See configuration in [readme.go.md](./readme.go.md)

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.

``` yaml $(java)
azure-arm: true
fluent: true
namespace: com.microsoft.azure.management.batch
license-header: MICROSOFT_MIT_NO_CODEGEN
payload-flattening-threshold: 1
output-folder: $(azure-libraries-for-java-folder)/azure-mgmt-batch
```

### Java multi-api

``` yaml $(java) && $(multiapi)
batch:
  - tag: package-2015-12
  - tag: package-2017-09
  - tag: package-2017-01
  - tag: package-2017-05
```

### Tag: package-2015-12 and java

These settings apply only when `--tag=package-2015-12 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2015-12' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2015_12_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2015_12_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-09 and java

These settings apply only when `--tag=package-2017-09 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-09' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2017_09_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2017_09_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-01 and java

These settings apply only when `--tag=package-2017-01 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-01' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2017_01_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2017_01_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-05 and java

These settings apply only when `--tag=package-2017-05 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-05' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2017_05_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2017_05_01
regenerate-manager: true
generate-interface: true
```

`

## AzureResourceSchema

See configuration in [readme.azureresourceschema.md](./readme.azureresourceschema.md)


text:
package se.culvertsoft.mgen.javapack.generator.impl

import scala.collection.JavaConversions.asScalaBuffer

import Alias.fieldMetadata
import Alias.get
import Alias.isSetName
import Alias.setFieldSet
import se.culvertsoft.mgen.api.model.ClassType
import se.culvertsoft.mgen.api.model.Module
import se.culvertsoft.mgen.compiler.internal.BuiltInGeneratorUtil.endl
import se.culvertsoft.mgen.compiler.internal.BuiltInGeneratorUtil.ln
import se.culvertsoft.mgen.compiler.util.SourceCodeBuffer
import se.culvertsoft.mgen.javapack.generator.JavaConstants.fieldSetDepthClsString
import se.culvertsoft.mgen.javapack.generator.JavaConstants.setFieldSetClsString
import se.culvertsoft.mgen.javapack.generator.JavaGenerator

object MkMarkFieldsSet {

  def apply(t: ClassType, module: Module)(implicit txtBuffer: SourceCodeBuffer) {

    implicit val m = module

    val fields = t.fields()
    val allFields = t.fieldsInclSuper()

    for (field <- fields) {
      ln(1, s"public ${t.shortName()} ${setFieldSet(field, s"final boolean state, final ${fieldSetDepthClsString} depth")} {")

      if (JavaGenerator.canBeNull(field)) {
        ln(2, "if (state)")
        ln(3, s"m_${field.name} = m_${field.name} != null ? m_${field.name} : ${MkDefaultValue(field, true)};")
        ln(2, "else")
        ln(3, s"m_${field.name} = null;")
      } else {
        ln(2, "if (!state)")
        ln(3, s"m_${field.name} = ${MkDefaultValue(field, false)};")
        ln(2, s"${isSetName(field)} = state;")
      }

      if (field.typ.containsUserDefinedType) {
        ln(2, s"if (depth == ${fieldSetDepthClsString}.DEEP)")
        ln(3, s"${setFieldSetClsString}.setFieldSetDeep(${get(field)}, ${fieldMetadata(field)}.typ());")
      }

      ln(2, s"return this;")
      ln(1, s"}")
      endl()
    }

    ln(1, s"public ${t.shortName()} _setAllFieldsSet(final boolean state, final ${fieldSetDepthClsString} depth) { ")
    for (field <- allFields)
      ln(2, s"${setFieldSet(field, "state, depth")};")
    ln(2, s"return this;")
    ln(1, s"}")
    endl()

  }
}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>

description("Ensure correct behavior of drawImage with ImageBitmaps.");
window.jsTestIsAsync = true;

function jsWrapperClass(node)
{
    // returns the ClassName of node
    if (!node)
        return "[null]";
    var string = Object.prototype.toString.apply(node);

    // string will be of the form [object ClassName]
    return string.substr(8, string.length - 9);
}

function shouldBeType(expression, className)
{
    shouldBe("jsWrapperClass(" + expression + ")", "'" + className + "'");
}

function shouldNotBeCalled() {
    testFailed("createImageBitmap promise rejected.");
    finishJSTest();
}

function shouldBeRed(x, y) {
    d = ctx.getImageData(x, y, 1, 1).data;
    shouldBe("d[0]", "255");
    shouldBe("d[1]", "0");
    shouldBe("d[2]", "0");
    shouldBe("d[3]", "255");
}

function shouldBeGreen(x, y) {
    d = ctx.getImageData(x, y, 1, 1).data;
    shouldBe("d[0]", "0");
    shouldBe("d[1]", "255");
    shouldBe("d[2]", "0");
    shouldBe("d[3]", "255");
}

function shouldBeBlue(x, y) {
    d = ctx.getImageData(x, y, 1, 1).data;
    shouldBe("d[0]", "0");
    shouldBe("d[1]", "0");
    shouldBe("d[2]", "255");
    shouldBe("d[3]", "255");
}

function shouldBeBlack(x, y) {
    d = ctx.getImageData(x, y, 1, 1).data;
    shouldBe("d[0]", "0");
    shouldBe("d[1]", "0");
    shouldBe("d[2]", "0");
    shouldBe("d[3]", "255");
}

function shouldBeClear(x, y) {
    // should be transparent black pixels
    d = ctx.getImageData(x, y, 1, 1).data;
    shouldBe("d[0]", "0");
    shouldBe("d[1]", "0");
    shouldBe("d[2]", "0");
    shouldBe("d[3]", "0");
}

function drawPattern(ctx) {
    // Draw a four-color pattern
    ctx.beginPath();
    ctx.fillStyle = "rgb(255, 0, 0)";
    ctx.fillRect(0, 0, 10, 10);
    ctx.fillStyle = "rgb(0, 255, 0)";
    ctx.fillRect(10, 0, 10, 10);
    ctx.fillStyle = "rgb(0, 0, 255)";
    ctx.fillRect(0, 10, 10, 10);
    ctx.fillStyle = "rgb(0, 0, 0)";
    ctx.fillRect(10, 10, 10, 10);
}

function clearContext(context) {
    context.clearRect(0, 0, 50, 50);
}

var bitmap;
var image;
var testBitmap; // this is an ImageBitmap that is uncropped. We use this to test createImageBitmap(testBitmap)
var d;          // image.imageData
var elements;

var imageWidth = 20;
var imageHeight = 20;

// Draw to an auxillary canvas.
var aCanvas = document.createElement("canvas");
aCanvas.width = imageWidth;
aCanvas.height = imageHeight;
var aCtx = aCanvas.getContext("2d");
drawPattern(aCtx);

var canvas = document.createElement("canvas");
canvas.setAttribute("width", "50");
canvas.setAttribute("height", "50");
var ctx = canvas.getContext("2d");

image = new Image();
image.onload = imageLoaded;
image.src = aCanvas.toDataURL();

var imageLoaded = false;
var imageBitmapLoaded = false;
var blobLoaded = false;

function imageLoaded() {
    createImageBitmap(image).then(imageBitmapLoadedCallback, shouldNotBeCalled);
    d = aCtx.getImageData(0, 0, 20, 20);
    imageLoaded = true;
    loaded();
}

function imageBitmapLoadedCallback(imageBitmap) {
    testBitmap = imageBitmap;

    shouldBe("testBitmap.width", "imageWidth");
    shouldBe("testBitmap.height", "imageHeight");

    // width and height are readonly
    testBitmap.width = 42;
    testBitmap.height = 42;
    shouldBe("testBitmap.width", "imageWidth");
    shouldBe("testBitmap.height", "imageHeight");

    imageBitmapLoaded = true;
    loaded();
}

var xhr = new XMLHttpRequest();
xhr.open("GET", 'resources/pattern.png');
xhr.responseType = 'blob';
xhr.send();
xhr.onload = function() {
    blob = xhr.response;
    blobLoaded = true;
    loaded();
}

function loaded() {
    if (imageLoaded && imageBitmapLoaded && blobLoaded) {
        // check all of these elements
        elements = [image, aCanvas, d, testBitmap, blob];
        // wait for callback to finish before each check to ensure synchronous behavior
        nextCheck(0);
    }
}

function nextCheck(elementIndex) {
    if (elementIndex == elements.length) {
        finishJSTest();
        return;
    }
    var element = elements[elementIndex];
    imageBitmaps = {};
    debug("Checking " + jsWrapperClass(element) + ".");
    var p1 = createImageBitmap(element).then(function (image) { imageBitmaps.noCrop = image });
    var p2 = createImageBitmap(element, 0, 0, 10, 10).then(function (image) { imageBitmaps.crop = image });
    var p3 = createImageBitmap(element, 5, 5, 10, 10).then(function (image) { imageBitmaps.cropCenter = image });
    var p4 = createImageBitmap(element, 10, 10, 10, 10).then(function (image) { imageBitmaps.cropRight = image });
    var p5 = createImageBitmap(element, -10, -10, 60, 60).then(function (image) { imageBitmaps.overCrop = image });
    var p6 = createImageBitmap(element, 10, 10, 50, 50).then(function (image) { imageBitmaps.overCropRight = image });
    var p7 = createImageBitmap(element, 10, 10, -10, -10).then(function (image) { imageBitmaps.negativeCrop = image });
    var p8 = createImageBitmap(element, -30, -30, 30, 30).then(function (image) { imageBitmaps.empty = image });
    var p9 = createImageBitmap(element, 40, 30, 30, 30).then(function (image) { imageBitmaps.emptyTwo = image });
    Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9]).then(function() {
        checkNoCrop(imageBitmaps.noCrop);
        checkCrop(imageBitmaps.crop);
        checkCropCenter(imageBitmaps.cropCenter);
        checkCropRight(imageBitmaps.cropRight);
        checkOverCrop(imageBitmaps.overCrop);
        checkOverCropRight(imageBitmaps.overCropRight);
        checkCrop(imageBitmaps.negativeCrop);
        checkEmpty(imageBitmaps.empty);
        checkEmpty(imageBitmaps.emptyTwo);
        createImageBitmap(element, 0, 0, Math.pow(10, 6), Math.pow(10, 6)).then(function() {
            testFailed('Creating a huge ImageBitmap is resolved unexpectedly.');
            finishJSTest();
        }, function() {
            testPassed('Creating a huge ImageBitmap is rejected as expected.');
            nextCheck(elementIndex + 1);
        });
    }, shouldNotBeCalled);
}

function checkNoCrop(imageBitmap) {
    debug("Check no crop.");
    bitmap = imageBitmap;
    shouldBeType("bitmap", "ImageBitmap");
    shouldBe("bitmap.width", "imageWidth");
    shouldBe("bitmap.height", "imageHeight");

    // should be drawn to (0, 0), (20, 20)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeRed(9, 9);
    shouldBeGreen(11, 9);
    shouldBeBlue(9, 11);
    shouldBeBlack(11, 11);
    shouldBeBlack(19, 19);
    shouldBeClear(1, 21);
    shouldBeClear(21, 1);
    shouldBeClear(21, 21);

    // shrunk to (0, 0), (10, 10)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0, 10, 10);
    shouldBeRed(4, 4);
    shouldBeGreen(6, 4);
    shouldBeBlue(4, 6);
    shouldBeBlack(6, 6);
    shouldBeBlack(9, 9);
    shouldBeClear(1, 11);
    shouldBeClear(11, 1);
    shouldBeClear(11, 11);

    // shrunk to (10, 10), (20, 20)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 10, 10, 10, 10);
    shouldBeRed(14, 14);
    shouldBeGreen(16, 14);
    shouldBeBlue(14, 16);
    shouldBeBlack(16, 16);
    shouldBeBlack(19, 19);
    shouldBeClear(11, 21);
    shouldBeClear(21, 11);
    shouldBeClear(21, 21);

    // black should be drawn to (10, 10), (20, 20)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 10, 10, 10, 10, 10, 10, 10, 10);
    shouldBeClear(9, 9);
    shouldBeBlack(11, 11);
    shouldBeBlack(19, 19);
    shouldBeClear(1, 21);
    shouldBeClear(21, 1);
    shouldBeClear(21, 21);
}

function checkCrop(imageBitmap) {
    debug("Check crop.");
    bitmap = imageBitmap;
    shouldBeType("bitmap", "ImageBitmap");
    shouldBe("bitmap.width", "10");
    shouldBe("bitmap.height", "10");

    // red should be drawn to (0, 0), (10, 10)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeRed(1, 1);
    shouldBeRed(9, 9);
    shouldBeClear(12, 12);
    shouldBeClear(1, 12);
    shouldBeClear(12, 1);

    // red should be drawn to (0, 0), (20, 20)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0, 20, 20);
    shouldBeRed(1, 1);
    shouldBeRed(18, 18);
    shouldBeClear(22, 22);
    shouldBeClear(1, 22);
    shouldBeClear(22, 1);
}

function checkCropCenter(imageBitmap) {
    debug("Check crop center.");
    bitmap = imageBitmap;
    shouldBeType("bitmap", "ImageBitmap");
    shouldBe("bitmap.width", "10");
    shouldBe("bitmap.height", "10");

    // should be drawn to (0, 0), (10, 10) with all four colors
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeRed(4, 4);
    shouldBeGreen(6, 4);
    shouldBeBlue(4, 6);
    shouldBeBlack(6, 6);
    shouldBeBlack(9, 9);
    shouldBeClear(11, 11);
    shouldBeClear(1, 11);
    shouldBeClear(11, 1);

    // should be drawn to (0, 0), (20, 20) with all four colors
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0, 20, 20);
    shouldBeRed(8, 8);
    shouldBeGreen(11, 8);
    shouldBeBlue(8, 11);
    shouldBeBlack(11, 11);
    shouldBeBlack(18, 18);
    shouldBeClear(22, 22);
    shouldBeClear(1, 21);
    shouldBeClear(21, 1);
}

function checkCropRight(imageBitmap) {
    debug("Check crop right.");
    bitmap = imageBitmap;
    shouldBeType("bitmap", "ImageBitmap");
    shouldBe("bitmap.width", "10");
    shouldBe("bitmap.height", "10");

    // black should be drawn to (0, 0), (10, 10)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeBlack(1, 1);
    shouldBeBlack(9, 9);
    shouldBeClear(11, 11);
    shouldBeClear(1, 11);
    shouldBeClear(11, 1);
}

function checkOverCrop(imageBitmap) {
    debug("Check over crop.");
    bitmap = imageBitmap;
    shouldBeType("bitmap", "ImageBitmap");
    shouldBe("bitmap.width", "60");
    shouldBe("bitmap.height", "60");

    // should be drawn to (10, 10), (30, 30)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeClear(1, 1);
    shouldBeClear(9, 9);
    shouldBeRed(11, 11);
    shouldBeRed(19, 19);
    shouldBeGreen(21, 19);
    shouldBeBlue(19, 21);
    shouldBeBlack(21, 21);
    shouldBeBlack(29, 29);
    shouldBeClear(32, 1);
    shouldBeClear(1, 32);
    shouldBeClear(32, 32);

    // should be drawn to (5, 5), (15, 15)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0, 30, 30);
    shouldBeClear(1, 1);
    shouldBeClear(4, 4);
    shouldBeRed(6, 6);
    shouldBeRed(9, 9);
    shouldBeGreen(11, 9);
    shouldBeBlue(9, 11);
    shouldBeBlack(11, 11);
    shouldBeBlack(14, 14);
    shouldBeClear(16, 1);
    shouldBeClear(1, 16);
    shouldBeClear(16, 16);
}

function checkOverCropRight(imageBitmap) {
    debug("Check over crop right.");
    bitmap = imageBitmap;
    shouldBe("bitmap.width", "50");
    shouldBe("bitmap.height", "50");

    // black should be drawn to (0, 0), (10, 10)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeBlack(1, 1);
    shouldBeBlack(9, 9);
    shouldBeClear(11, 11);
    shouldBeClear(1, 11);
    shouldBeClear(11, 1);

    // black should be drawn to (0, 0), (4, 4)
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0, 20, 20);
    shouldBeBlack(1, 1);
    shouldBeBlack(3, 3);
    shouldBeClear(5, 5);
    shouldBeClear(1, 5);
    shouldBeClear(5, 1);

    // nothing should be drawn
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 10, 10, 20, 20, 0, 0, 20, 20);
    shouldBeClear(1, 1);
    shouldBeClear(3, 3);
    shouldBeClear(5, 5);
    shouldBeClear(1, 5);
    shouldBeClear(5, 1);
}

function checkEmpty(imageBitmap) {
    debug("Check empty.");
    bitmap = imageBitmap;
    shouldBeType("bitmap", "ImageBitmap");
    shouldBe("bitmap.width", "30");
    shouldBe("bitmap.height", "30");

    // nothing should be drawn
    clearContext(ctx);
    ctx.drawImage(imageBitmap, 0, 0);
    shouldBeClear(1, 1);
    shouldBeClear(9, 9);
    shouldBeClear(11, 11);
    shouldBeClear(22, 22);
}

</script>
</body>
</html>


text:
using System;
using System.Linq;

namespace Microsoft.Azure.Insights.Legacy.Models
{
    /// <summary>
    /// Aggregation type.
    /// </summary>
    public enum AggregationType
    {
        /// <summary>
        /// No aggregation.
        /// </summary>
        None = 0,

        /// <summary>
        /// Average value in the time range.
        /// </summary>
        Average = 1,

        /// <summary>
        /// Least value in the time range.
        /// </summary>
        Minimum = 2,

        /// <summary>
        /// Greatest value in the time range.
        /// </summary>
        Maximum = 3,

        /// <summary>
        /// Sum of all of the values in the time range.
        /// </summary>
        Total = 4,

        /// <summary>
        /// Last sample in the time range.
        /// </summary>
        Last = 5,
    }
}


text:
M2N
===
The experiments are divided in two steps. The first is related to the base-level and the second to the meta-level performance. To run the measures we need some R packages and the DCoL library.

## Technical Requirements

R version 3.1.2 -- "Pumpkin Helmet"

DCoL Library: http://dcol.sourceforge.net/

Packages: CORElearn, e1071, FNN, foreign, infotheo, rpart, R.utils, rrcov and mvpart.

## Set the experiments

Before start to run the measures we need the binary of the DCoL library. Download the code of DCoL Library at http://dcol.sourceforge.net/ and follow the instructions to compile the code in the README file. After that, put the executable (binary file) inside the m2n folder with the name "dcol".

Open the R inside the m2n folder.

Install the packages:

```

install.packages(c("CORElearn", "e1071", "FNN", "foreign", "infotheo",
"rpart", "R.utils", "rrcov", "mvpart"))

```

## Base-level

In the base-level folder we have the datasets used in this work, the measures to characterize the datasets and some complementary information about the base-level.

### How to load the datasets?

The easiest way to load the datasets (arff files) is with the packages RWeka or foreign:

```
# load the iris dataset
require("foreign")
data = read.arff("base-level/database/iris.arff");

```

### How to run the measures?

Load the source codes:

```
# load the complexity measures
source("base-level/measures/complexity.r")

```

```
# load the characterization measures
source("base-level/measures/characterization.r")

```

Run the functions with the data set as parameter:

```
# characterization measures
characterization(iris);

# complexity measures
complexity(iris);
```

## Meta-level

In the meta-level folder we have the meta-datasets in the rand and pairwise folder and some complementary information about the base-level.

### How to load the datasets?

The easiest way to load the datasets (.RData files) is with the dget function:

```
# load the iris dataset with random noise
data = dget("meta-level/database/rand/iris.RData");

```

### Contact

Luis Paulo Faina Garcia - lpfgarcia [at] gmail.com

University of São Paulo - Campus São Carlos

### References

[1] K. Bache, M. Lichman, UCI machine learning repository, http://archive.ics.uci.edu/ml (2013).

[2] A. Orriols-Puig, N. Maciá, T. K. Ho, Documentation for the data complexity library in C++, Tech. rep., La Salle - Universitat Ramon Llull (2010).

[3] M. Reif, A comprehensive dataset for evaluating approaches of various meta-learning tasks, in: First International Conference on Pattern Recognition and Methods (ICPRAM), 2012.

[4] R Core Team, R: A Language and Environment for Statistical Computing, R Foundation for Statistical Computing, Vienna, Austria (2014). URL http://www.r-project.org/


text:
var numCPUs = require('os').cpus().length;
var cluster = require('cluster');
var EE      = require('events').EventEmitter;

var isProduction = process.env.NODE_ENV == 'production';

/**
 * Creates a load balancer
 * @param file          {String} path to the module that defines the server
 * @param opt           {Object} options
 * @param opt.workers   {Number} number of active workers
 * @param opt.timeout   {Number} kill timeout for old workers after reload (sec)
 * @param opt.respawn   {Number} min time between respawns when workers die
 * @param opt.backoff   {Number} max time between respawns when workers die
 * @param opt.readyWhen {String} when does the worker become ready? 'listening' or 'started'
 * @param opt.log       {Object} log to stdout (default: {respawns: true})
 * @return - the balancer. To run, use balancer.run() reload, balancer.reload()
 */
module.exports = function(file, opt) {

    opt = opt || {};
    opt.workers = opt.workers || numCPUs;
    opt.timeout = opt.timeout || (isProduction ? 3600 : 1);
    opt.readyWhen = opt.readyWhen || 'listening';
    opt.log = opt.log || {respawns: true};

    var optrespawn =  opt.respawn || 1;
    var backoffTimer;

    var self = new EE();
    var channel = new EE();

    self.workers = [];

    function emit() {
        channel.emit.apply(self, arguments);
        self.emit.apply(channel, arguments);
    }

    var readyEvent = opt.readyWhen == 'started' ? 'online' :
                     opt.readyWhen == 'listening' ? 'listening' :
                     'message';

    var readyCommand = 'ready';
    var disconnectCommand = 'disconnect';

    var respawners = (function() {
        var items = [];
        var self = {};
        self.cancel = function() {
            items.forEach(function(item) {
                clearTimeout(item);
            });
            items = [];
        };
        self.add = function(t) {
            items.push(t);
        };
        self.done = function(t) {
            items.splice(items.indexOf(t), 1);
        };
        return self;
    }());

    var lastSpawn = Date.now();

    function delayedDecreaseBackoff() {
        if (backoffTimer) clearTimeout(backoffTimer);
        backoffTimer = setTimeout(function() {
            backoffTimer = null;
            optrespawn = optrespawn / 2;
            if (optrespawn <= opt.respawn)
                optrespawn = opt.respawn;
            else
                delayedDecreaseBackoff();
        }, opt.backoff * 1000);
    }

    // Fork a new worker. Give it a recluster ID and
    // also redirect all its messages to the cluster.
    function fork(wid) {
        var w = cluster.fork({WORKER_ID: wid});
        w._rc_wid = wid;
        w._rc_isReplaced = false;
        w.on('message', function(message) {
            emit('message', w, message);
        });
        w.process.on('exit', function() {
            var windex = self.workers.indexOf(w);
            if (windex >= 0)
                self.workers.splice(windex, 1);
        });
        self.workers.push(w);
        return w;
    }

    // Replace a dysfunctional worker
    function workerReplace(worker) {
        if (worker._rc_isReplaced) return;
        worker._rc_isReplaced = true;

        var now = Date.now();

        if (opt.backoff)
            optrespawn = Math.min(optrespawn, opt.backoff);

        var nextSpawn = Math.max(now, lastSpawn + optrespawn * 1000),
            time = nextSpawn - now;
            lastSpawn = nextSpawn;

        // Exponential backoff.
        if (opt.backoff) {
            optrespawn *= 2;
            delayedDecreaseBackoff();
        }

        if (opt.log.respawns)
            console.log('worker #' + worker._rc_wid
                        + ' (' + worker.id + ') died, respawning in', time);
        var respawner = setTimeout(function() {
            respawners.done(respawner);
            fork(worker._rc_wid);
        }, time);

        respawners.add(respawner);

    }

    // Replace a worker that has closed the IPC channel
    // or signaled that its dysfunctional. Will also
    // terminate the worker after the specified time has
    // passed.
    function workerReplaceTimeoutTerminate(w) {
        workerReplace(w);
        killTimeout(w);
    }

    // Sets up a kill timeout for a worker. Closes the
    // IPC channel immediately.
    function killTimeout(worker) {
        var trykillfn =function() {
            try {
                if (worker.kill) {
                    worker.kill();
                } else {
                    worker.destroy();
                }
            } catch(e) {}
        }

        if (opt.timeout > 0) {
            var timeout = setTimeout(trykillfn, opt.timeout * 1000);
            worker.on('exit', clearTimeout.bind(this, timeout));
            // possible leftover worker that has no channel
            // estabilished will throw. Ignore.
            try {
                worker.send({cmd: 'disconnect'});
                worker.disconnect();
            } catch (e) { }
        } else {
            process.nextTick(trykillfn);
        }

    }

    // Redirect most events
    function workerListening(w, adr) { emit('listening', w, adr); }
    function workerOnline(w) { emit('online', w); }
    function workerDisconnect(w) { emit('disconnect', w); }
    function workerEmitExit(w) { emit('exit', w); }

    self.run = function() {
        if (!cluster.isMaster) return;
        cluster.setupMaster({exec: file});
        for (var i = 0; i < opt.workers; i++) fork(i);

        cluster.on('exit', workerEmitExit);
        cluster.on('disconnect', workerDisconnect);
        cluster.on('listening', workerListening);
        cluster.on('online', workerOnline);

        channel.on(readyEvent, function workerReady(w, arg) {
            // ignore unrelated messages when readyEvent = message
            if (readyEvent === 'message'
                && (!arg || arg.cmd != readyCommand)) return;
            emit('ready', w, arg);
        });
        // When a worker exits, try to replace it
        channel.on('exit', workerReplace);
        // When it closes the IPC channel or signals that it can no longer
        // do any processing, replace it and then set up a termination timeout
        channel.on('disconnect', workerReplaceTimeoutTerminate);
        channel.on('message', function workerDisconnectMsg(w, arg) {
            if (arg && arg.cmd === 'disconnect')
                workerReplaceTimeoutTerminate(w);
        });

    }

    self.reload = function() {
        if (!cluster.isMaster) return;
        respawners.cancel();

        self.workers.forEach(function(worker) {
            var id = worker.id;

           function allReady(cb) {
               var listenCount = opt.workers;
               var self = this;
               return function(w, arg) {
                   if (!--listenCount) cb.apply(self, arguments);
               };
           }
           var stopOld = allReady(function() {
                // dont respawn this worker. It has already been replaced.
                worker._rc_isReplaced = true;

                // Kill the worker after the appropriate timeout has passed
                killTimeout(worker);
                channel.removeListener('ready', stopOld);
            });

            channel.on('ready', stopOld);
        });
        for (var i = 0; i < opt.workers; ++i) fork(i);
    };

    self.terminate = function() {
        if (!cluster.isMaster) return;
        cluster.removeListener('exit', workerEmitExit);
        cluster.removeListener('disconnect', workerDisconnect);
        cluster.removeListener('listening', workerListening);
        cluster.removeListener('online', workerOnline);
        respawners.cancel();
        self.workers.forEach(function (worker) {
            if (worker.kill)
                worker.kill('SIGKILL');
            else
                worker.destroy();
        });
        channel.removeAllListeners();
    }

    return self;
};


text:
/** \file     TDecGop.h
    \brief    GOP decoder class (header)
*/

#ifndef __TDECGOP__
#define __TDECGOP__

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "TLibCommon/CommonDef.h"
#include "TLibCommon/TComBitStream.h"
#include "TLibCommon/TComList.h"
#include "TLibCommon/TComPicYuv.h"
#include "TLibCommon/TComPic.h"
#include "TLibCommon/TComLoopFilter.h"
#include "TLibCommon/TComAdaptiveLoopFilter.h"

#include "TDecEntropy.h"
#include "TDecSlice.h"
#include "TDecBinCoder.h"
#include "TDecBinCoderCABAC.h"

//! \ingroup TLibDecoder
//! \{

// ====================================================================================================================
// Class definition
// ====================================================================================================================

/// GOP decoder class
class TDecGop
{
private:
  Int                   m_iGopSize;
  TComList<TComPic*>    m_cListPic;         //  Dynamic buffer

  //  Access channel
  TDecEntropy*          m_pcEntropyDecoder;
  TDecSbac*             m_pcSbacDecoder;
  TDecBinCABAC*         m_pcBinCABAC;
  TDecCavlc*            m_pcCavlcDecoder;
  TDecSlice*            m_pcSliceDecoder;
  TComLoopFilter*       m_pcLoopFilter;

  // Adaptive Loop filter
  TComAdaptiveLoopFilter*       m_pcAdaptiveLoopFilter;
#if MTK_SAO
  TComSampleAdaptiveOffset*              m_pcSAO;
  SAOParam              m_cSaoParam;
#endif
  ALFParam              m_cAlfParam;
  Double                m_dDecTime;

  bool m_pictureDigestEnabled; ///< if true, handle picture_digest SEI messages

public:
  TDecGop();
  virtual ~TDecGop();

  Void  init    ( TDecEntropy*            pcEntropyDecoder,
                 TDecSbac*               pcSbacDecoder,
                 TDecBinCABAC*           pcBinCABAC,
                 TDecCavlc*              pcCavlcDecoder,
                 TDecSlice*              pcSliceDecoder,
                 TComLoopFilter*         pcLoopFilter,
                 TComAdaptiveLoopFilter* pcAdaptiveLoopFilter
#if MTK_SAO
                 ,TComSampleAdaptiveOffset*                pcSAO
#endif
                 );
  Void  create  ();
  Void  destroy ();
#if REF_SETTING_FOR_LD
  Void  decompressGop(TComInputBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf, TComList<TComPic*>& rcListPic );
#else
  Void  decompressGop(TComInputBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf );
#endif
  Void  setGopSize( Int i) { m_iGopSize = i; }

  void setPictureDigestEnabled(bool enabled) { m_pictureDigestEnabled = enabled; }

#if E045_SLICE_COMMON_INFO_SHARING
private:
  /// copy shared ALF parameters from PPS
  Void copySharedAlfParamFromPPS(ALFParam* pAlfDst, ALFParam* pAlfSrc);
#endif

};

//! \}

#endif // !defined(AFX_TDECGOP_H__29440B7A_7CC0_48C7_8DD5_1A531D3CED45__INCLUDED_)


text:
#ifndef CQChartsBoxDataEdit_H
#define CQChartsBoxDataEdit_H

#include <CQChartsData.h>
#include <CQChartsLineEditBase.h>

class CQChartsBoxDataEdit;
class CQChartsMarginEdit;
class CQChartsView;
class CQChartsPlot;

/*!
 * \brief Box data line edit
 * \ingroup Charts
 */
class CQChartsBoxDataLineEdit : public CQChartsLineEditBase {
  Q_OBJECT

  Q_PROPERTY(CQChartsBoxData boxData READ boxData WRITE setBoxData)

 public:
  CQChartsBoxDataLineEdit(QWidget *parent=nullptr);

  const CQChartsBoxData &boxData() const;
  void setBoxData(const CQChartsBoxData &c);

  void drawPreview(QPainter *painter, const QRect &rect) override;

 Q_SIGNALS:
  void boxDataChanged();

 private Q_SLOTS:
  void menuEditChanged();

 private:
  void textChanged() override;

  void updateBoxData(const CQChartsBoxData &c, bool updateText);

  void boxDataToWidgets();

  void connectSlots(bool b);

 private:
  CQChartsBoxDataEdit* dataEdit_ { nullptr };
};

//---

#include <CQChartsEditBase.h>

class CQChartsShapeDataEdit;
class CQChartsSidesEdit;
class CQChartsBoxDataEditPreview;
class CQRealSpin;
class CQGroupBox;

/*!
 * \brief Box data edit
 * \ingroup Charts
 */
class CQChartsBoxDataEdit : public CQChartsEditBase {
  Q_OBJECT

  Q_PROPERTY(CQChartsBoxData data READ data WRITE setData)

 public:
  using View = CQChartsView;
  using Plot = CQChartsPlot;

 public:
  CQChartsBoxDataEdit(QWidget *parent=nullptr);

  const CQChartsBoxData &data() const { return data_; }
  void setData(const CQChartsBoxData &d);

  void setPlot(Plot *plot) override;
  void setView(View *view) override;

  void setTitle(const QString &title);

  void setPreview(bool b);

 Q_SIGNALS:
  void boxDataChanged();

 private:
  void dataToWidgets();

  void connectSlots(bool b);

 private Q_SLOTS:
  void widgetsToData();

 private:
  CQChartsBoxData             data_;                    //!< box data
  CQGroupBox*                 groupBox_    { nullptr }; //!< group box
  CQChartsMarginEdit*         marginEdit_  { nullptr }; //!< outer margin edit
  CQChartsMarginEdit*         paddingEdit_ { nullptr }; //!< inner padding edit
  CQChartsShapeDataEdit*      shapeEdit_   { nullptr }; //!< shape edit
  CQChartsSidesEdit*          sidesEdit_   { nullptr }; //!< sides edit
  CQChartsBoxDataEditPreview* preview_     { nullptr }; //!< preview widget
  bool                        connected_   { false };   //!< is connected
};

//---

/*!
 * \brief Box data edit preview
 * \ingroup Charts
 */
class CQChartsBoxDataEditPreview : public CQChartsEditPreview {
  Q_OBJECT

 public:
  CQChartsBoxDataEditPreview(CQChartsBoxDataEdit *edit);

  void draw(QPainter *painter) override;

  static void draw(QPainter *painter, const CQChartsBoxData &data, const QRect &rect,
                   Plot *plot, View *view);

 private:
  CQChartsBoxDataEdit *edit_ { nullptr };
};

//------

#include <CQChartsPropertyViewEditor.h>

/*!
 * \brief type for CQChartsBoxData
 * \ingroup Charts
 */
class CQChartsBoxDataPropertyViewType : public CQChartsPropertyViewType {
 public:
  using View = CQChartsView;
  using Plot = CQChartsPlot;

 public:
  CQPropertyViewEditorFactory *getEditor() const override;

  void drawPreview(QPainter *painter, const QRect &rect, const QVariant &value,
                   Plot *plot, View *view) override;

  QString tip(const QVariant &value) const override;

  QString userName() const override { return "box_data"; }
};

//---

#include <CQPropertyViewEditor.h>

/*!
 * \brief editor factory for CQChartsBoxData
 * \ingroup Charts
 */
class CQChartsBoxDataPropertyViewEditor : public CQChartsPropertyViewEditorFactory {
 public:
  CQChartsLineEditBase *createPropertyEdit(QWidget *parent);

  void connect(QWidget *w, QObject *obj, const char *method);

  QVariant getValue(QWidget *w);

  void setValue(QWidget *w, const QVariant &var);
};

#endif


text:
#include "Vector2D.h"

//
// Vector2DZero
// Purpose: Zeros the x_ and y_ data members of a vector
//
void Vector2DZero( VECTOR2D *vector )
{
	vector->x_ = 0;
	vector->y_ = 0;
}

//
// Vector2DSet
// Purpose: Sets the x_ and y_ data members of a vector to
//          provided values x and y
//
void Vector2DSet( VECTOR2D *vector, float x, float y )
{
	vector->x_ = x;
	vector->y_ = y;
}

//
// Vector2DNeg
// Purpose: Sets a vector to the opposite of another vector
//
void Vector2DNeg( VECTOR2D *vector, VECTOR2D *opposite )
{
	vector->x_ = opposite->x_ * -1;
	vector->y_ = opposite->y_ * -1;
}

//
// Vector2DAdd
// Purpose: Sets a vector to the sum of two vectors
//
void Vector2DAdd( VECTOR2D *vector, VECTOR2D *addend1, VECTOR2D *addend2)
{
	vector->x_ = addend1->x_ + addend2->x_;
	vector->y_ = addend1->y_ + addend2->y_;
}

//
// Vector2DSub
// Purpose: Sets a vector to the difference of two vectors
//
void Vector2DSub( VECTOR2D *vector, VECTOR2D *addend1, VECTOR2D *addend2)
{
	vector->x_ = addend1->x_ - addend2->x_;
	vector->y_ = addend1->y_ - addend2->y_;
}

//
// Vector2DNormalize
// Purpose: Sets a vector to the unit vector of another vector
// Notes  : This function should be used mainly to initialize values; since
//          it uses the sqrt function, calling it each game cycle will be
//          rather costly.
//
void Vector2DNormalize( VECTOR2D *vector, VECTOR2D *toNorm )
{
	VECTOR2D temp;
  float sqrtVal = (float)sqrt((toNorm->x_ * toNorm->x_) + (toNorm->y_ * toNorm->y_));
	temp.x_ = toNorm->x_ / sqrtVal;
	temp.y_ = toNorm->y_ / sqrtVal;

	vector->x_ = temp.x_;
	vector->y_ = temp.y_;
}

//
// Vector2DScale
// Purpose: Scales vector toScale by value c and stores the result in vector
//
void Vector2DScale( VECTOR2D *vector, VECTOR2D *toScale, float c )
{
  vector->x_ = toScale->x_ * c;
  vector->y_ = toScale->y_ * c;
}

//
// Vector2DLength
// Purpose: Returns the absolute length of a vector
// Notes  : Due to the use of sqrt, this function can be much
//          more innefficient than Vector2DSquareLength.
//
float	Vector2DLength( const VECTOR2D *vector )
{
  return sqrtf( (vector->x_ * vector->x_) + (vector->y_ * vector->y_) );
}

//
// Vector2DSquareLength
// Purpose: Returns the length of a vector squared
// Notes  : This function should be used as an optimization to
//          the Vector2DLength function to avoid the use of the
//          sqrt function.
//
float Vector2DSquareLength( const VECTOR2D *vector )
{
	return (vector->x_ * vector->x_) + (vector->y_ * vector->y_);
}

//
// Vector2DDistance
// Purpose: Returns the absolute distance between two points
// Notes  : This function can be highly innefficient compared to
//          Vector2DSquareDistance due to the use of the sqrt
//          function.
//
float Vector2DDistance( const VECTOR2D *pointA, const VECTOR2D *pointB )
{
  return sqrtf( (pointA->x_ - pointB->x_) * (pointA->x_ - pointB->x_) +
                (pointA->y_ - pointB->y_) * (pointA->y_ - pointB->y_) );
}

//
// Vector2DSquareDistance
// Purpose: Returns the absolute distance between two points squared
// Notes  : This function can be highly efficient compared to
//          Vector2DSquareDistance due to the use of the sqrt
//          function in its counterpart.
//
float Vector2DSquareDistance( const VECTOR2D *pointA, const VECTOR2D *pointB )
{
  return (pointA->x_ - pointB->x_) * (pointA->x_ - pointB->x_) +
         (pointA->y_ - pointB->y_) * (pointA->y_ - pointB->y_);
}

//
// Vector2DDotProduct
// Purpose: Returns the dot product of two vectors.
//
float Vector2DDotProduct( const VECTOR2D *vectorA, const VECTOR2D *vectorB )
{
  return vectorA->x_ * vectorB->x_ + vectorA->y_ * vectorB->y_;
}

//
// Vector2DCrossProduct
// Purpose: Returns the dot product of two vectors.
//
float Vector2DCrossProduct( const VECTOR2D *vectorA, const VECTOR2D *vectorB )
{
	return vectorA->x_ * vectorB->y_ - vectorA->y_ * vectorB->x_;
}

//
// Vector2DFromAngle
// Purpose: Returns a normal vector in the direction of an angle (radians)
//
void Vector2DFromAngle( VECTOR2D *vector, float angle)
{
  vector->x_ = cosf(angle);
  vector->y_ = sinf(angle);
}

//
// VelocityClamp
// Purpose: Clamps a velocity vector within a maximum speed
//
void SpeedClamp( float *vel, float maxSpeed )
{
  if(*vel > maxSpeed)
  {
    *vel = maxSpeed;
  }
  else if(*vel < -maxSpeed)
  {
    *vel = -maxSpeed;
  }
}


text:
// Module dependencies.
var _ = require('underscore');

var azureutil = require('../../../util/util');
var HeaderConstants = require('../../../util/constants').HeaderConstants;
var HmacSha256Sign = require('../../core/hmacsha256sign');

/**
* Creates a new SharedKey object.
*
* @constructor
* @param {string} storageAccount    The storage account.
* @param {string} storageAccessKey  The storage account's access key.
* @param {bool}   usePathStyleUri   Boolean value indicating if the path, or the hostname, should include the storage account.
*/
function SharedKey(storageAccount, storageAccessKey, usePathStyleUri) {
  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
  this.usePathStyleUri = usePathStyleUri;
  this.signer = new HmacSha256Sign(storageAccessKey);
}

/**
* Signs a request with the Authentication header.
*
* @param {WebResource} The webresource to be signed.
* @param {function(error)}  callback  The callback function.
* @return {undefined}
*/
SharedKey.prototype.signRequest = function (webResource, callback) {
  var getvalueToAppend = function (value) {
    if (azureutil.objectIsNull(value)) {
      return '\n';
    } else {
      return value + '\n';
    }
  };

  var stringToSign =
    webResource.httpVerb + '\n' +
    getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_ENCODING]) +
    getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_LANGUAGE]) +
    getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_LENGTH]) +
    getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_MD5]) +
    getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_TYPE]) +
    getvalueToAppend(webResource.headers[HeaderConstants.DATE]) +
    getvalueToAppend(webResource.headers[HeaderConstants.IF_MODIFIED_SINCE]) +
    getvalueToAppend(webResource.headers[HeaderConstants.IF_MATCH]) +
    getvalueToAppend(webResource.headers[HeaderConstants.IF_NONE_MATCH]) +
    getvalueToAppend(webResource.headers[HeaderConstants.IF_UNMODIFIED_SINCE]) +
    getvalueToAppend(webResource.headers[HeaderConstants.RANGE]) +
    this._getCanonicalizedHeaders(webResource) +
    this._getCanonicalizedResource(webResource);

  var signature = this.signer.sign(stringToSign);

  webResource.withHeader(HeaderConstants.AUTHORIZATION, 'SharedKey ' + this.storageAccount + ':' + signature);
  callback(null);
};

/*
* Retrieves the webresource's canonicalized resource string.
* @param {WebResource} webResource The webresource to get the canonicalized resource string from.
* @return {string} The canonicalized resource string.
*/
SharedKey.prototype._getCanonicalizedResource = function (webResource) {
  var path = '/';
  if (webResource.path) {
    path = webResource.path;
  }

  var canonicalizedResource = '/' + this.storageAccount + path;

  // Get the raw query string values for signing
  var queryStringValues = webResource.queryString;

  // Build the canonicalized resource by sorting the values by name.
  if (queryStringValues) {
    var paramNames = [];
    Object.keys(queryStringValues).forEach(function (n) {
      paramNames.push(n);
    });

    paramNames = paramNames.sort();
    Object.keys(paramNames).forEach(function (name) {
      canonicalizedResource += '\n' + paramNames[name] + ':' + queryStringValues[paramNames[name]];
    });
  }

  return canonicalizedResource;
};

/*
* Constructs the Canonicalized Headers string.
*
* To construct the CanonicalizedHeaders portion of the signature string,
* follow these steps: 1. Retrieve all headers for the resource that begin
* with x-ms-, including the x-ms-date header. 2. Convert each HTTP header
* name to lowercase. 3. Sort the headers lexicographically by header name,
* in ascending order. Each header may appear only once in the
* string. 4. Unfold the string by replacing any breaking white space with a
* single space. 5. Trim any white space around the colon in the header. 6.
* Finally, append a new line character to each canonicalized header in the
* resulting list. Construct the CanonicalizedHeaders string by
* concatenating all headers in this list into a single string.
*
* @param {object} The webresource object.
* @return {string} The canonicalized headers.
*/
SharedKey.prototype._getCanonicalizedHeaders = function (webResource) {
  // Build canonicalized headers
  var canonicalizedHeaders = '';
  if (webResource.headers) {
    var canonicalizedHeadersArray = [];
    for (var header in webResource.headers) {
      if (header.indexOf(HeaderConstants.PREFIX_FOR_STORAGE_HEADER) === 0) {
        canonicalizedHeadersArray.push(header);
      }
    }

    canonicalizedHeadersArray.sort();

    _.each(canonicalizedHeadersArray, function (currentHeader) {
      canonicalizedHeaders += currentHeader.toLowerCase() + ':' + webResource.headers[currentHeader] + '\n';
    });
  }

  return canonicalizedHeaders;
};

module.exports = SharedKey;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package org.drip.analytics.input</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.drip.analytics.input

Packages that use org.drip.analytics.input

Package
Description

org.drip.analytics.definition

org.drip.analytics.input

org.drip.state.basis

org.drip.state.credit

org.drip.state.curve

org.drip.state.discount

org.drip.state.forward

org.drip.state.fx

org.drip.state.govvie

org.drip.state.repo

Classes in org.drip.analytics.input used by org.drip.analytics.definition

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.analytics.input

Class and Description

BootCurveConstructionInput

BootCurveConstructionInput contains the Parameters needed for the Curve Calibration/Estimation.

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.basis

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.credit

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.curve

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.discount

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.forward

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.fx

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.govvie

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Classes in org.drip.analytics.input used by org.drip.state.repo

Class and Description

CurveConstructionInputSet

CurveConstructionInputSet interface contains the Parameters needed for the Curve Calibration/Estimation.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<!doctype html>

	<meta charset="utf-8">

	<title>NRGHost - Responsive Multipurpose Theme</title>

	<meta name="description" content="A Perfect HTML5 Template for your site with unlimited options">
	<meta name="author" content="vor">
	<meta name="copyright" content="vor">
	<meta name="generator" content="Documenter v1.0 http://rxa.li/documenter">
	<meta name="date" content="2015-01-05T00:00:00+02:00">

	<link rel="stylesheet" href="assets/css/documenter_style.css" media="all">
	<link type="text/css" rel="stylesheet" href="assets/css/SyntaxHighlighter.css"></link>
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,700,800' rel='stylesheet' type='text/css'>
	<link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">

Welcome

Installing Template

HTML Structure

CSS Structure

Javascript Structure

Tutorial

Sources and Credits

Copyright Moonart 2015

		made with the Documenter v1.0

NRGHost

Responsive Multipurpose Theme

Welcome To NRGHost Template Documentation.

Firstly, a huge thanks for purchasing this theme, your support is truly appreciated!

	This document covers the installation and use of this theme and often reveals answers to common problems and issues - read this document thoroughly if you are experiencing any difficulties. If you have any questions that are beyond the scope of this document, feel free to pose them in the dedicated support section.

Template Features

Clean & Simple Design

Advance Bootstrap 3 Framework

HTML5 & CSS3

CSS3 Animations

Fully Responsive Design

Mutipurpose Concept

All files are well commented

Crossbrowser Compatible with IE9+, Firefox, Safari, Opera, Chrome

Extensive Documentation

Go ahead to know more.

Installing Template

After unzip the download pack, you'll found a Template Folder with all the files.

	You can view this Template in any browser, you can display or edit the Template without an internet connection.

	Now open your FTP Client (like Filezilla) or directly through cpanel,  upload the content of the Template on your server root.

	Once the files are done uploading go to www.yourdomainname.com/index.html

HTML Structure

HTML Structure

This Template has a Responsive layout and is based on the Bootstrap Framework. For more information about this visit Bootstrap.

The default Bootstrap grid system utilizes 12 columns, making for a 1170px wide container without responsive features enabled. With the responsive CSS file added, the grid adapts to be 724px and 1170px wide depending on your viewport. Below 767px viewports, the columns become fluid and stack vertically.

Basic Grid HTML

For a simple two column layout, create a .container and add the appropriate number of .col-md* columns.

Given this example, we have .col-md-4 and .col-md-8, making for 12 total columns and a complete row.

...

...

Nesting Columns

To nest your content with the default grid, add a new .container and set of .col-md* columns within an existing .col-md* column. Nested rows should include a set of columns that add up to the number of columns of its parent.

        Level 1 column

Level 2

Level 2

        Level 2 column

CSS Structure

These are the css files that are loaded into templates in Head Section.

	           <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="css/idangerous.swiper.css" rel="stylesheet" type="text/css" />
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <link href="css/animate.css" rel="stylesheet" type="text/css" />
    <link rel="shortcut icon" href="img/favicon.ico" />

Dont change anything in bootstrap.css file. It may affect the whole theme.

Javascript

These are the JS files that are loaded into templates in end of the Body Section.

Tutorial

Lets start updating the template. Open index.html file and follow the steps.

Most of the updates are same for all pages. So will explain once here.

Header - Logo

Replace your logo image url source.

Navmenu

This is the basic structure.

                                Home

                                        Style 1
                                        Style 2
                                        Style 3

                                Hosting

                                        Hosting
                                        Shared
                                        VPS
                                        Dedicated

                                Domains

                                Pages

                                        About
                                        FAQ
                                        Testimonials
                                        Datacenters
                                        Support
                                        Login/Register
                                        Typography

                                Blog

                                        Style 1
                                        Style 2
                                        Blog Detail

                                Contact us

Replace "Home", "Hosting", etc.. with the menu name and "#" with the link.

The secondary ".submenu a" inside the menu is the dropdown

Swiper Slider

Click here for the Swiper Slider documentation.

Blog Content

26 Feb 2014

821

1028

58

                                Phasellus vel odio commodo, pharetra urna sit amet, gravida nibh

                                    Tech by Dorian Gray

Integer vitae rhoncus enim. Nam interdum vitae leo in viverra. Interdum et malesuada fames
								ac ante ipsum primis in faucibus. Ut fermentum risus in enim elementum pretium. Aliquam faucibus mattis nunc quis lobortis.
								In pulvinar eros sed purus sollicitudin auctor. Vivamus facilisis odio in nisi gravida euismod

                                Read More

replace 26 Feb 2014  with the post date.

replace Phasellus vel... with the post category.

replace Dorian Gray with the post author.

replace Integer vitae rhoncus... with the post text.

Same for all.

Testimonials Content

Testimonials

Integer faucibus, dui quis pellentesque vestibulum, nulla ante aliquet turpis, in consectetur ex dui vitae erat in eleifend eros

replace Testimonials with the category title.

replace Integer faucibus, dui... with the project text.

Same for all.

Google map link

To replace the google map link, click here

Google Map

Open contact.html file and Find this code.

replace data-lat and data-lng with the your location google map

Footer Copyright

  © 2015 All rights reserved. NRGHost

replace "© 2015 © 2015 All rights reserved. NRGHost"  with the copyright info.

Thats it. You are done. Now your website is ready to launch.

Sources and Credits

We have used the following plugins, fonts & images. All fonts, images, icons used in this template are free for commercial use.

jQuery Plugins

WOW plugin by Matt Aussaguel

Images

Images used from

thinkstockphotos.com

shutterstock.com

Images in live preview are not included to the template.

Once again, thank you so much for purchasing this theme.
As I said at the beginning, We'd be glad to help you if you have any questions relating to this theme. We I'll do our best to assist.

Thanks


text:
using System;
using System.Data.SqlClient;
using System.Reflection;
using Autofac;
using CodeSanook.Core.Services;
using CodeSanook.Infrastructure;
using CodeSanook.Repositories.NH;
using CodeSanook.Repositories.NH.Repositories;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
using log4net;
using log4net.Config;

namespace CodeSanook.Tests.Integration
{
    [TestFixture]
    public class IntegrationTestFixtureBase
    {
        protected ILog Log = LogManager.GetLogger("IntegrationTestFixtureBase");
        protected IContainer Config;
        protected ILifetimeScope Scope;
        protected NHUnitOfWorkFactory UnitOfWorkFactory;
        private const string connectionStringToMasterDatabase =
@"Server=.\SQLEXPRESS;Integrated security=SSPI;database=master";

        private void SetupAutofac()
        {
            var builder = new ContainerBuilder();
            var dataAccess = Assembly.GetAssembly(typeof(TopicRepository));
            builder.RegisterAssemblyTypes(dataAccess)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces();

            var service = Assembly.GetAssembly(typeof(TopicService));
            builder.RegisterAssemblyTypes(service)
                .Where(t => t.Name.EndsWith("Service"))
                .PropertiesAutowired();

            //unit of work
            UnitOfWorkFactory = new NHUnitOfWorkFactory();
            builder.RegisterInstance(UnitOfWorkFactory).As<IUnitOfWorkFactory>();

            var log = LogManager.GetLogger(typeof(IntegrationTestFixtureBase).Namespace);
            builder.RegisterInstance(log).As<ILog>();

            Config = builder.Build();
        }

        [TestFixtureSetUp]
        public virtual void TestFixtureSetup()
        {
            //CreateDatabase();
            XmlConfigurator.Configure();
            var sqlAzurePersistenceConfigurerInitializer = new SqlAzurePersistenceConfigurerInitializer();
            SessionFactory.Initialize(sqlAzurePersistenceConfigurerInitializer);
            SetupAutofac();

            //drop all table
            using(UnitOfWorkFactory.Create())
            {
                var session = SessionFactory.GetCurrentSession();
                session.ExecuteSqlFile("SqlScripts/DropAllForeignKeyConstraintsSqlDatabase.sql");
                session.ExecuteSqlFile("SqlScripts/DropAllTablesSqlDatabase.sql");
            }

            //create table
            var schemaExport = new SchemaExport(SessionFactory.Config);
            schemaExport.SetOutputFile("db_create.sql");
            schemaExport.Create(true, true);

            //create additional indexs
            using(UnitOfWorkFactory.Create())
            {
                var session = SessionFactory.GetCurrentSession();
                session.ExecuteSqlFile("SqlScripts/CreateClusterIndexesSqlDatabase.sql");
            }

            Scope = Config.BeginLifetimeScope();
        }

        [TestFixtureTearDown]
        public virtual void TestFxitureTearDown()
        {
            Scope.Dispose();
        }

        [SetUp]
        public virtual void SetUp()
        {

            using (UnitOfWorkFactory.Create())
            {
                var session = SessionFactory.GetCurrentSession();
                session.ExecuteSqlFile("SqlScripts/TruncateAllTablesSqlDatabase.sql");
            }
        }

        [TearDown]
        public virtual void TearDown()
        {
        }

        private void CreateDatabase()
        {
            try
            {
                //check if exist
                using (var con = new SqlConnection(connectionStringToMasterDatabase))
                using (var command = con.CreateCommand())
                {
                    var sql =
@"if db_id('CodeSanookTestDb') is not null
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 0
END";
                    command.CommandText = sql;
                    con.Open();

                    var result = (int)command.ExecuteScalar();

                    if (result == 1)
                    {
                        Log.Debug("database exist");
                        return; //database exist
                    }
                }

                using (var con = new SqlConnection(connectionStringToMasterDatabase))
                using (var command = con.CreateCommand())
                {
                    //var sql = @"CREATE DATABASE CodeSanookTestDb ON PRIMARY " +
                    //      "(NAME = CodeSanookTestDb, " +
                    //      "FILENAME = 'C:\\CodeSanookTestDb.mdf', " +
                    //      "SIZE = 3MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
                    //      "LOG ON (NAME = CodeSanookTestDb_Log, " +
                    //      "FILENAME = 'C:\\CodeSanookTestDb.ldf', " +
                    //      "SIZE = 1MB, " +
                    //      "MAXSIZE = 5MB, " +
                    //      "FILEGROWTH = 10%)";
                    var sql = " CREATE DATABASE CodeSanookTestDb";
                    command.CommandText = sql;
                    con.Open();

                    command.ExecuteNonQuery();
                    Log.Debug("DataBase is Created Successfully");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        private void DropDatabase()
        {
            try
            {

                //check if exist
                using (var con = new SqlConnection(connectionStringToMasterDatabase))
                using (var command = con.CreateCommand())
                {
                    var sql =
@"if db_id('CodeSanookTestDb') is not null
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 0
END";
                    command.CommandText = sql;
                    con.Open();

                    var result = (int)command.ExecuteScalar();

                    if (result == 0)
                    {
                        Log.Debug("no database to drop");
                        return; //database exist
                    }
                }

                //check if exist
                using (var con = new SqlConnection(connectionStringToMasterDatabase))
                using (var command = con.CreateCommand())
                {
                    var sql = "DROP DATABASE CodeSanookTestDb";
                    command.CommandText = sql;
                    con.Open();

                    command.ExecuteNonQuery();
                    Log.Debug("database drop successfully");
                }

            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

    }
}


text:
namespace Microsoft.Azure.Management.PostgreSQL
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// CheckNameAvailabilityOperations operations.
    /// </summary>
    public partial interface ICheckNameAvailabilityOperations
    {
        /// <summary>
        /// Check the availability of name for resource
        /// </summary>
        /// <param name='nameAvailabilityRequest'>
        /// The required parameters for checking if resource name is available.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<NameAvailability>> ExecuteWithHttpMessagesAsync(NameAvailabilityRequest nameAvailabilityRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
package org.sqlite;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import org.junit.jupiter.api.Test;

public class TypeMapTest {

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:sqlite::memory:");
    }

    @Test
    public void getTypeMap() throws Exception {
        Connection conn = getConnection();

        Map<String, Class<?>> m = conn.getTypeMap();

        conn.close();
    }

    @Test
    public void setTypeMap() throws Exception {
        Connection conn = getConnection();

        Map<String, Class<?>> m = conn.getTypeMap();
        conn.setTypeMap(m);

        conn.close();
    }
}


text:
#ifndef PREPROCESSING_MPI_H_
#define PREPROCESSING_MPI_H_
#include "src/mpi.h"
#include "src/preprocessing.h"
#include "src/parallel.h"

class PreprocessingMpi: public Preprocessing
{
private:
	MpiNode *node;

public:
	/** Destructor, calls MPI_Finalize */
    ~PreprocessingMpi()
    {
        delete node;
    }

    // Limit the number of effective MPI nodes to this value, rather than what is given through mpirun
    int max_mpi_nodes;

    /** Read
     * This could take care of mpi-parallelisation-dependent variables
     */
    void read(int argc, char **argv);

    // Parallelized run functions
    void runExtractParticles();
    void run();

};

#endif /* PREPROCESSING_MPI_H_ */


text:
package types

import (
	"encoding/json"
	"strconv"
)

// NullUint64 is a wrapper around uint64 values that can be null or an unint64.
// Use IsSet to check if the value is provided, instead of checking against 0.
type NullUint64 struct {
	IsSet bool
	Value uint64
}

// ParseStringValue is used to parse a user provided flag argument.
func (n *NullUint64) ParseStringValue(val string) error {
	if val == "" {
		return nil
	}

	uint64Val, err := strconv.ParseUint(val, 10, 64)
	if err != nil {
		return err
	}

	n.Value = uint64Val
	n.IsSet = true

	return nil
}

func (n *NullUint64) UnmarshalJSON(rawJSON []byte) error {
	var value json.Number
	err := json.Unmarshal(rawJSON, &value)
	if err != nil {
		return err
	}

	if value.String() == "" {
		n.Value = 0
		n.IsSet = false
		return nil
	}

	valueInt, err := strconv.ParseUint(value.String(), 10, 64)
	if err != nil {
		return err
	}

	n.Value = valueInt
	n.IsSet = true

	return nil
}


text:
package com.google.api.explorer.client.auth;

import com.google.api.explorer.client.AuthManager;
import com.google.api.explorer.client.AuthManager.AuthCompleteCallback;
import com.google.api.explorer.client.AuthManager.AuthToken;
import com.google.api.explorer.client.analytics.AnalyticsManager;
import com.google.api.explorer.client.auth.AuthPresenter.Display;
import com.google.api.explorer.client.auth.AuthPresenter.Display.State;
import com.google.api.explorer.client.base.ApiMethod;
import com.google.api.explorer.client.base.ApiService;
import com.google.api.explorer.client.base.ApiService.AuthInformation;
import com.google.api.explorer.client.base.ApiService.AuthScope;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;

import junit.framework.TestCase;

import org.easymock.Capture;
import org.easymock.EasyMock;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

/**
 * Tests for {@link AuthPresenter}.
 *
 * @author jasonhall@google.com (Jason Hall)
 */
public class AuthPresenterTest extends TestCase {

  private static final Set<String> EMPTY_SCOPES = Collections.emptySet();

  private final Display display = EasyMock.createMock(Display.class);
  private final AuthManager authManager = EasyMock.createStrictMock(AuthManager.class);
  private final ApiService service = EasyMock.createControl().createMock(ApiService.class);
  private final AnalyticsManager analytics =
      EasyMock.createControl().createMock(AnalyticsManager.class);

  /**
   * When a ServiceLoadedEvent fires, the Display becomes visible and displays
   * the user as un-authenticated by default.
   */

  public void testServiceLoadedWithoutAuth() {
    ApiMethod method1 = EasyMock.createControl().createMock(ApiMethod.class);
    ApiMethod method2 = EasyMock.createControl().createMock(ApiMethod.class);
    EasyMock.expect(service.allMethods()).andReturn(
        ImmutableMap.of("method.one", method1, "method.two", method2));
    EasyMock.expect(service.getName()).andReturn("service");
    display.setScopes(Collections.<String, ApiService.AuthScope>emptyMap());
    display.setState(State.PUBLIC, EMPTY_SCOPES, EMPTY_SCOPES);
    display.preSelectScopes(EMPTY_SCOPES);
    EasyMock.replay(display);

    @SuppressWarnings("unused")
    AuthPresenter presenter = new AuthPresenter(service, authManager, analytics, display);

    EasyMock.verify(display);
  }

  /** Check the flow which sets up the display for auth. */
  public void testAuthGranted() {
    ApiMethod method1 = EasyMock.createControl().createMock(ApiMethod.class);
    ApiMethod method2 = EasyMock.createControl().createMock(ApiMethod.class);
    EasyMock.expect(method1.getScopes()).andReturn(ImmutableList.of("scopeName")).anyTimes();
    ImmutableSet<String> authScopes = ImmutableSet.of("scopeName");
    Map<String, AuthInformation> auth = generateAuthInformation(authScopes);
    EasyMock.expect(service.getAuth()).andReturn(auth).anyTimes();

    // This is called once for every call to the presenter.
    display.setScopes(auth.get("oauth2").getScopes());
    EasyMock.expectLastCall().times(2);

    // When the presenter is created these will be called.
    display.setState(State.PUBLIC, EMPTY_SCOPES, EMPTY_SCOPES);
    EasyMock.expectLastCall();
    display.preSelectScopes(EMPTY_SCOPES);
    EasyMock.expectLastCall();
    EasyMock.expect(authManager.getToken(service)).andReturn(null).times(2);

    // When the method is set, these will be called.
    EasyMock.expect(display.getSelectedScopes()).andReturn(authScopes);
    final Capture<AuthCompleteCallback> cbCapture = new Capture<AuthCompleteCallback>();
    authManager.requestAuth(
        EasyMock.eq(service), EasyMock.eq(authScopes), EasyMock.capture(cbCapture));
    EasyMock.expectLastCall();

    display.setState(State.PUBLIC, authScopes, EMPTY_SCOPES);
    EasyMock.expectLastCall();
    display.preSelectScopes(authScopes);
    EasyMock.expectLastCall();

    // When execute auth is clicked, these will be called.
    display.hideScopeDialog();
    EasyMock.expectLastCall();
    display.setState(State.PRIVATE, authScopes, authScopes);
    EasyMock.expectLastCall();

    AuthToken token = EasyMock.createMock(AuthToken.class);
    EasyMock.expect(token.getScopes()).andReturn(authScopes);
    EasyMock.expect(authManager.getToken(service)).andReturn(token);

    EasyMock.replay(service, display, method1, method2, authManager, token);

    AuthPresenter presenter = new AuthPresenter(service, authManager, analytics, display);
    presenter.setStateForMethod(method1);
    presenter.clickExecuteAuth();
    cbCapture.getValue().complete(token);

    EasyMock.verify(display);
  }

  private Map<String, AuthInformation> generateAuthInformation(Set<String> scopes) {
    Map<String, AuthScope> authScopes = Maps.newHashMap();

    for (String scopeName : scopes) {
      AuthScope mockScope = EasyMock.createMock(AuthScope.class);
      EasyMock.replay(mockScope);
      authScopes.put(scopeName, mockScope);
    }

    AuthInformation mockAuth = EasyMock.createMock(AuthInformation.class);
    EasyMock.expect(mockAuth.getScopes()).andReturn(authScopes).anyTimes();

    EasyMock.replay(mockAuth);

    Map<String, AuthInformation> auth = Maps.newHashMap();
    auth.put("oauth2", mockAuth);

    return auth;
  }
}


text:
RSpec::Matchers.define :map_specs do |specs|
  match do |autotest|
    @specs = specs
    @autotest = prepare(autotest)
    autotest.test_files_for(@file) == specs
  end

  chain :to do |file|
    @file = file
  end

  failure_message_for_should do
    "expected #{@autotest.class} to map #{@specs.inspect} to #{@file.inspect}\ngot #{@actual.inspect}"
  end

  def prepare(autotest)
    find_order = @specs.dup << @file
    autotest.instance_eval { @find_order = find_order }
    autotest
  end
end

RSpec::Matchers.define :have_interface_for do |method|
  match do |object|
    @method = method
    @object = object
    object.respond_to?(method) && actual_arity == @expected_arity
  end

  chain :with do |arity|
    @expected_arity = arity
  end

  chain(:argument) {}
  chain(:arguments) {}

  failure_message_for_should do
    "#{@object} should have method :#{@method} with #{@expected_arity} argument(s), but it had #{actual_arity}"
  end

  def actual_arity
    @object.method(@method).arity
  end
end


text:
package de.ppi.samples.fuwesta.service.impl;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import de.ppi.samples.fuwesta.dao.api.PostDao;
import de.ppi.samples.fuwesta.dao.api.UserDao;
import de.ppi.samples.fuwesta.model.Post;
import de.ppi.samples.fuwesta.model.User;
import de.ppi.samples.fuwesta.service.api.UserService;

/**
 * The Class UserServiceImplTest.
 */
public class UserServiceImplTest {

    /**
     * Mock for userDao.
     */
    @Mock
    private UserDao userDao;

    /**
     * Mock for postDao.
     */
    @Mock
    private PostDao postDao;

    /**
     * The service to test.
     */
    @InjectMocks
    private UserService userService = new UserServiceImpl();

    /**
     * Initialize the test.
     *
     */
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#getAllUser()}
     * .
     */
    @Test
    public void testGetAllUser() {
        // Arange

        // Act
        userService.getAllUser();

        // Assert
        verify(userDao, times(1)).findAll((Pageable) null);
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#getUser(int, int, org.springframework.data.domain.Sort.Order[])}
     * .
     */
    @Test
    public void testGetUser() {
        // CSOFF: MagicNumber
        // Arange
        PageRequest pr = new PageRequest(2, 4);

        // Act
        userService.getUser(10, 4);

        // Assert
        verify(userDao, times(1)).findAll(pr);
        // CSON: MagicNumber
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#save(de.ppi.fuwesta.samples.springmvc.model.User)}
     * .
     */
    @Test
    public void testSave() {
        // Arange
        final User aUser = new User();
        when(userDao.save(any(User.class))).thenReturn(aUser);

        // Act
        final User testUser = userService.save(new User());

        // Assert
        assertThat(testUser).isEqualTo(aUser);
        verify(userDao, times(1)).save(any(User.class));
        // CSON: MagicNumber
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#read(java.lang.Long)}
     * .
     */
    @Test
    public void testRead() {
        // Arrange
        when(userDao.findOne(Long.valueOf(1L))).thenReturn(new User());

        // Act
        userService.read(Long.valueOf(1L));

        // Assert
        verify(userDao, times(1)).findOne(Long.valueOf(1L));
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#delete(java.lang.Long)}
     * .
     */
    @Test
    public void testDelete() {
        // Arrange
        final User user = new User();
        when(userDao.findOne(Long.valueOf(1L))).thenReturn(user);

        // Act
        userService.delete(Long.valueOf(1L));

        // Assert
        verify(userDao, times(1)).delete(user);
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#getNrOfUsers()}
     * .
     */
    @SuppressWarnings("boxing")
    @Test
    public void testNrOfUsers() {
        final long nrOfUser = 10;
        when(userDao.count()).thenReturn(nrOfUser);

        // Act
        long testValue = userService.getNrOfUsers();

        // Assert
        verify(userDao, times(1)).count();
        assertThat(testValue).isEqualTo(nrOfUser);
    }

    /**
     * Test method for
     * {@link de.ppi.fuwesta.samples.springmvc.service.impl.UserServiceImpl#getPostingSelectOptions()}
     * .
     */
    @Test
    public void testGetPostingSelectOptions() {
        // Arrange
        final List<Post> postings = new ArrayList<Post>();
        final int numberOfPosts = 5;
        for (long i = 0; i < numberOfPosts; i++) {
            Post post = new Post();
            post.setId(Long.valueOf(i));
            post.setTitle("Title " + i);
            postings.add(post);
        }
        when(postDao.findAllOrderByTitle()).thenReturn(postings);
        // Act
        final List<Post> result = userService.getPostingSelectOptions();
        // Assert
        assertThat(result).hasSize(numberOfPosts).isEqualTo(postings);

    }
}


text:
<?php
/**
 * Basic parameter holder that can be configured to allow adding of new
 * parameters at runtime. Alternatively a class could be derived from this one
 * to set all parameters a design time. As an alternative the sfParameterHolder
 * could be used. It works in a smililar way without magic methods for the
 * getters and setters and also allows a default value to be passed to the get
 * method.
 *
 * @package     uUtilitiesPlugin
 * @subpackage  uParameterHolder
 * @author      Henning Glatter-Gotz <henning@glatter-gotz.com>
 */
class uParameterHolder
{
  /**
   * @var array The set of parameters for this class
   */
  protected $parameters = array();

  /**
   * @var boolean If set to true the class allows adding new parameters at
   *              runtime
   */
  protected $allowNewParameters;

  /**
   * Constructor for a ParameterHolder
   *
   * @param array   $parameters         The list of parameters to use if any
   * @param boolean $allowNewParameters See member description
   */
  public function __construct($parameters = array(), $allowNewParameters = true)
  {
    foreach ($parameters as $param)
    {
      $this->parameters[$param] = '';
    }

    $this->allowNewParameters = $allowNewParameters;
  }

  /**
   * Magic setter method that allows access to private members by simply using
   * the name.
   *
   * Example:
   *   If the class has a parameter called 'foo' then it can be accessed by
   *   using ->foo
   *
   * @param string $name The name of the parameter
   * @param mixed $value Any valid PHP value
   */
  public function __set($name, $value)
  {
    if (!$this->allowNewParameters)
    {
      if (!array_key_exists($name, $this->parameters))
      {
        throw new Exception(__METHOD__.':'.__LINE__.'|The parameter '.$name.' does not exist.');
      }
    }

    $this->parameters[$name] = $value;
  }

  /**
   * Magic getter method that allows access to private members by simply using
   * the name.
   *
   * @param string $name The name of the paramter
   * @return mixed       The value of the parameter
   */
  public function __get($name)
  {
    if (isset($this->parameters[$name]))
    {
      return $this->parameters[$name];
    }
    else
    {
      throw new Exception(__METHOD__.':'.__LINE__.'|The parameter "'.$name.
        '" does not exist.');
    }
  }

  /**
   * Check if a named paramter exists in the parameter holder object.
   *
   * @param string $name Name of the parameter to check for
   * @return boolean
   */
  public function has($name)
  {
    return isset($this->parameters[$name]);
  }

  /**
   * Helper method to write the contents of the parameter holder to a string.
   * This can be useful for logging purposes.
   *
   * @return String A serialized, human readable version of the class.
   */
  public function __toString()
  {
    return $this->name.'|'.uArray::assocArrayToPrintableString($this->parameters);
  }
}


text:
import threading
import time
import serial
import datetime
import os
import sys
import re
import json

import http.server
from http.server import HTTPServer

sys.stderr = open('/data/log/voltageserver_err.log', 'w')

# Values we expect to read

voltage = -1		# voltage
mains_power = -1	# mains power
inverter = -1		# inverter status

class MyRequestHandler(http.server.SimpleHTTPRequestHandler):

    log_file = open('/data/log/voltageserver_access.log', 'w')

    def do_GET(self):
	    self.send_response(200)
	    self.send_header("Content-type", "application/json")
	    self.send_header("Access-Control-Allow-Origin","*")
	    self.end_headers()
	    #self.wfile.write(json.dumps({"voltage" : voltage}))
	    self.wfile.write(json.dumps({"voltage" : voltage}).encode('UTF-8'))

    def log_message(self, format, *args):
        self.log_file.write("%s - - [%s] %s\n" %
                            (self.client_address[0],
                             self.log_date_time_string(),
                             format%args))
        self.log_file.flush()

server = HTTPServer(('', 8080), MyRequestHandler)

thread = threading.Thread(target = server.serve_forever)
thread.daemon = True

try:
    thread.start()
except KeyboardInterrupt:
    server.shutdown()
    sys.exit(0)

print('Server started on port 8080')

port = '/dev/ttyACM0'
ser = serial.Serial(port, 9600, timeout=12) # Create a serial object

# ser.readline();

mv_re = re.compile('voltage=([0-9.]+)');
mains_re = re.compile('mains_power=([01]+)');
inverter_re = re.compile('inverter=([01]+)');

while True:
	status = ser.readline().decode('ascii')

	# print("status: " + status + "\n")

	m = mv_re.search(status)
	if m:
		voltage = m.group(1)

	m = mains_re.search(status)
	if m:
		mains_power = m.group(1);

	m = inverter_re.search(status)
	if m:
		inverter = m.group(1);

	# print(json.dumps({"voltage" : voltage, "mains_power" : mains_power, "inverter" : inverter}))


text:
package camelinaction;

import org.apache.camel.Exchange;
import org.apache.camel.Header;

/**
 * Bean which implements the logic where the message should be routed by the Dynamic Router EIP.
 *
 * @version $Revision$
 */
public class DynamicRouterBean {

    /**
     * The method invoked by Dynamic Router EIP to compute where to go next.
     *
     * @param body          the message body
     * @param previous   the previous endpoint, is <tt>null</tt> on the first invocation
     * @return endpoint uri where to go, or <tt>null</tt> to indicate no more
     */
    public String route(String body, @Header(Exchange.SLIP_ENDPOINT) String previous) {
        return whereToGo(body, previous);
    }

    /**
     * Method which computes where to go next
     */
    private String whereToGo(String body, String previous) {
        if (previous == null) {
            // 1st time
            return "mock://a";
        } else if ("mock://a".equals(previous)) {
            // 2nd time - transform the message body using the simple language
            return "language://simple:Bye ${body}";
        } else {
            // no more, so return null to indicate end of dynamic router
            return null;
        }
    }

}