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

<title>
Google Trends Visualizer
</title>

<textarea id="noTexture" name="fx" cols="80" rows="20">
float4x4 worldViewProjection : WorldViewProjection;
float4x4 world : World;
float4x4 view : View;

float3 sunPos;

struct a2v {
  float4 pos : POSITION;
  float3 normal : NORMAL;
};

struct v2f {
  float4 pos : POSITION;
  float3 normal : TEXCOORD0;
  float3 sun : TEXCOORD1;
  float3 view : TEXCOORD2;
};

v2f vsMain(a2v IN) {
  v2f OUT;

  OUT.pos = mul(IN.pos, worldViewProjection);
  OUT.normal = mul(float4(IN.normal, 0), world).xyz;
  float3 worldPos = mul(IN.pos, world).xyz;
  OUT.sun = sunPos - worldPos;
  OUT.view = (view[3] - worldPos);

  return OUT;
}

float4 psMain(v2f IN): COLOR {
  float3 norm = normalize(IN.normal);
  float3 sun = normalize(IN.sun);
  float  light = dot(norm, sun);
  float  lightSign = sign(light);
  float  dayNight = 1 - sqrt(light);
  dayNight = dayNight * dayNight;
  dayNight = (1 - dayNight) * lightSign;
  dayNight = clamp(dayNight, 0, 1);
  float3 view = normalize(IN.view);
  float3 r = normalize(reflect(norm, sun));
  float4 litR = lit(light, dot(r, view), 0.0).y;
  float3 day = float3(0.5, 0.5, 1.0) * litR.y + float3(1,1,1) * litR.z;
  float3 night = float3(0.2, 0.2, 0.5);
  return float4(lerp(night, day, dayNight),1);
}

// #o3d VertexShaderEntryPoint vsMain
// #o3d PixelShaderEntryPoint psMain
// #o3d MatrixLoadOrder RowMajor
</textarea>
<textarea id="dayOnly" name="fx" cols="80" rows="20">
float4x4 worldViewProjection : WorldViewProjection;
float4x4 world : World;
float4x4 view : View;

float3 sunPos;
float mix;

sampler2D daySampler;

struct a2v {
  float4 pos : POSITION;
  float3 normal : NORMAL;
  float2 uv : TEXCOORD0;
};

struct v2f {
  float4 pos : POSITION;
  float2 uv : TEXCOORD0;
  float3 normal : TEXCOORD1;
  float3 sun : TEXCOORD2;
  float3 view : TEXCOORD3;
};

v2f vsMain(a2v IN) {
  v2f OUT;

  OUT.pos = mul(IN.pos, worldViewProjection);
  OUT.uv = IN.uv;
  OUT.normal = mul(float4(IN.normal, 0), world).xyz;
  float3 worldPos = mul(IN.pos, world).xyz;
  OUT.sun = sunPos - worldPos;
  OUT.view = (view[3] - worldPos);

  return OUT;
}

float4 psMain(v2f IN): COLOR {
  float3 norm = normalize(IN.normal);
  float3 sun = normalize(IN.sun);
  float  light = dot(norm, sun);
  float  lightSign = sign(light);
  float  dayNight = 1 - sqrt(light);
  dayNight = dayNight * dayNight;
  dayNight = (1 - dayNight) * lightSign;
  dayNight = clamp(dayNight, 0, 1);
  float3 view = normalize(IN.view);
  float3 r = normalize(reflect(norm, sun));
  float4 litR = lit(light, dot(r, view), 0.0).y;
  float3 earth = tex2D(daySampler, IN.uv).xyz;
  float3 day = lerp(float3(0.5, 0.5, 1.0), earth, mix);
  day = day * litR.y + float3(1,1,1) * litR.z;
  float3 night = lerp(float3(0.2, 0.2, 0.5), earth * 0.3, mix);
  return float4(lerp(night, day, dayNight),1);
}

// #o3d VertexShaderEntryPoint vsMain
// #o3d PixelShaderEntryPoint psMain
// #o3d MatrixLoadOrder RowMajor
</textarea>
<textarea id="nightAndDay" name="fx" cols="80" rows="20">
float4x4 worldViewProjection : WorldViewProjection;
float4x4 world : World;
float4x4 view : View;

float3 sunPos;
float mix;

sampler2D daySampler;
sampler2D nightSampler;

struct a2v {
  float4 pos : POSITION;
  float3 normal : NORMAL;
  float2 uv : TEXCOORD0;
};

struct v2f {
  float4 pos : POSITION;
  float2 uv : TEXCOORD0;
  float3 normal : TEXCOORD1;
  float3 sun : TEXCOORD2;
  float3 view : TEXCOORD3;
};

v2f vsMain(a2v IN) {
  v2f OUT;

  OUT.pos = mul(IN.pos, worldViewProjection);
  OUT.uv = IN.uv;
  OUT.normal = mul(float4(IN.normal, 0), world).xyz;
  float3 worldPos = mul(IN.pos, world).xyz;
  OUT.sun = sunPos - worldPos;
  OUT.view = (view[3] - worldPos);

  return OUT;
}

float4 psMain(v2f IN): COLOR {
  float3 norm = normalize(IN.normal);
  float3 sun = normalize(IN.sun);
  float  light = dot(norm, sun);
  float  lightSign = sign(light);
  float  dayNight = 1 - sqrt(light);
  dayNight = dayNight * dayNight;
  dayNight = (1 - dayNight) * lightSign;
  dayNight = clamp(dayNight, 0, 1);
  float3 view = normalize(IN.view);
  float3 r = normalize(reflect(norm, sun));
  float4 litR = lit(light, dot(r, view), 0.0).y;
  float3 earth = tex2D(daySampler, IN.uv).xyz;
  float3 day = tex2D(daySampler, IN.uv).xyz;
  float3 night = lerp(day * 0.3, tex2D(nightSampler, IN.uv).xyz, mix);
  day = day * litR.y + float3(1,1,1) * litR.z;
  return float4(lerp(night, day, dayNight),1);
}

// #o3d VertexShaderEntryPoint vsMain
// #o3d PixelShaderEntryPoint psMain
// #o3d MatrixLoadOrder RowMajor
</textarea>

<textarea id="mask" name="fx" cols="80" rows="20">
float4x4 worldViewProjection : WorldViewProjection;
float4x4 world : World;
float4x4 view : View;

float3 sunPos;
float mix;

sampler2D daySampler;
sampler2D nightSampler;
sampler2D maskSampler;

struct a2v {
  float4 pos : POSITION;
  float3 normal : NORMAL;
  float2 uv : TEXCOORD0;
};

struct v2f {
  float4 pos : POSITION;
  float2 uv : TEXCOORD0;
  float3 normal : TEXCOORD1;
  float3 sun : TEXCOORD2;
  float3 view : TEXCOORD3;
};

v2f vsMain(a2v IN) {
  v2f OUT;

  OUT.pos = mul(IN.pos, worldViewProjection);
  OUT.uv = IN.uv;
  OUT.normal = mul(float4(IN.normal, 0), world).xyz;
  float3 worldPos = mul(IN.pos, world).xyz;
  OUT.sun = sunPos - worldPos;
  OUT.view = (view[3] - worldPos);

  return OUT;
}

float4 psMain(v2f IN): COLOR {
  float3 norm = normalize(IN.normal);
  float3 sun = normalize(IN.sun);
  float  light = dot(norm, sun);
  float  lightSign = sign(light);
  float  dayNight = 1 - sqrt(light);
  dayNight = dayNight * dayNight;
  dayNight = (1 - dayNight) * lightSign;
  dayNight = clamp(dayNight, 0, 1);
  float3 view = normalize(IN.view);
  float3 r = normalize(reflect(norm, sun));
  float4 litR = lit(light, dot(r, view), 0.0).y;
  float3 earth = tex2D(daySampler, IN.uv).xyz;
  float4 mask = tex2D(maskSampler, IN.uv);
  float3 day = lerp(tex2D(daySampler, IN.uv).xyz,
                    mask.xyz, mix);
  float3 night = tex2D(nightSampler, IN.uv).xyz;
  day = day * litR.y + float3(1,1,1) * litR.z * (1 - mask.w * mix);

  float3 color = lerp(night, day, dayNight);
  return float4(color,1);
}

// #o3d VertexShaderEntryPoint vsMain
// #o3d PixelShaderEntryPoint psMain
// #o3d MatrixLoadOrder RowMajor
</textarea>
<textarea id="energy" name="fx" cols="80" rows="20">
float4x4 worldViewProjection : WorldViewProjection;

// time is used to scroll the UV coords
float time;

// offset is used to allow each shard to scroll over a different part of the
// texture.
float offset;

// Sets the color of the shard.
float4 colorMult;

// Provides the dots on the shard.
sampler2D energySampler;

struct a2v {
  float4 pos : POSITION;
  float3 norm : NORMAL;
  float4 color : COLOR;
  float2 uv : TEXCOORD0;
};

struct v2f {
  float4 pos : POSITION;
  float2 uv : TEXCOORD0;
  float4 color : TEXCOORD1;
};

v2f vsMain(a2v IN) {
  v2f OUT;

  OUT.pos = mul(IN.pos, worldViewProjection);
  OUT.uv = float2(IN.uv.x, IN.uv.y + time + offset);
  OUT.color = IN.color;

  return OUT;
}

float4 psMain(v2f IN): COLOR {
  return float4(tex2D(energySampler, IN.uv)) * IN.color * colorMult;
}

// #o3d VertexShaderEntryPoint vsMain
// #o3d PixelShaderEntryPoint psMain
// #o3d MatrixLoadOrder RowMajor
</textarea>
<textarea id="atmosphere" name="fx" cols="80" rows="20">
float4x4 worldViewProjection : WorldViewProjection;
float4x4 worldView : WorldView;
float3 sunPos;
float3 eyePos;

struct a2v {
  float4 pos : POSITION;
  float3 norm : NORMAL;
};

struct v2f {
  float4 pos : POSITION;
  float3 normal : TEXCOORD0;
};

v2f vsMain(a2v IN) {
  v2f OUT;

  OUT.pos = mul(IN.pos, worldViewProjection);
  OUT.normal = normalize(mul(float4(IN.norm,0), worldView).xyz);
  return OUT;
}

float4 psMain(v2f IN): COLOR {
  float n = 1 - log(2 * normalize(IN.normal).z);
  return float4(0.3, 0.3, 1, n * n * n * n);
}

// #o3d VertexShaderEntryPoint vsMain
// #o3d PixelShaderEntryPoint psMain
// #o3d MatrixLoadOrder RowMajor
</textarea>


text:
package com.pkware.truth.android.view;

import android.view.KeyCharacterMap;
import androidx.annotation.IntDef;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.SOURCE;

@IntDef({
    KeyCharacterMap.NUMERIC,
    KeyCharacterMap.PREDICTIVE,
    KeyCharacterMap.ALPHA,
    KeyCharacterMap.FULL,
    KeyCharacterMap.SPECIAL_FUNCTION
})
@Retention(SOURCE)
@interface KeyCharacterMapKeyboardType {
}

redpajama_set_name: RedPajamaGithub


text:
{{project.currentProject.name}}

    <ng-switch on="project.currentProject.image || '_undefined_'">

            <anguvideo class="video" ng-model="project.currentProject.video"></anguvideo>

    </ng-switch>


text:
import routes from './routes';
import store from './store';

export {
  routes,
  store
};


text:
class Token < ActiveRecord::Base
  has_secure_token :value

  def self.valid?(source, token)
    token.present? && exists?(source: source, value: token)
  end

  def self.revoke(id)
    find(id).destroy
  end

  def self.sources
    EventTypeRepository.from_rails_config.external_types +
      [OpenStruct.new(endpoint: 'github_notifications', name: 'Github Notifications')]
  end

  def source_name
    if source == 'github_notifications'
      'Github Notifications'
    else
      EventTypeRepository.from_rails_config.find_by_endpoint(source).name
    end
  end
end


text:
#ifndef ICMPTUNNEL_ECHOSKT_H
#define ICMPTUNNEL_ECHOSKT_H

#include <stdint.h>
#include <stdlib.h>

struct echo_skt
{
    int fd;
    int bufsize;
    char *buf, *data;
};

struct echo
{
    int size;
    int reply;
    uint16_t id;
    uint16_t seq;
};

/* open an icmp echo socket. */
int open_echo_skt(struct echo_skt *skt, int mtu);

/* send an echo packet. */
int send_echo(struct echo_skt *skt, uint32_t destip, struct echo *echo);

/* receive an echo packet. */
int receive_echo(struct echo_skt *skt, uint32_t *sourceip, struct echo *echo);

/* close the socket. */
void close_echo_skt(struct echo_skt *skt);

#endif


text:
package org.mariotaku.okfaye;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ws.WebSocketCall;

import java.util.Scanner;

/**
 * Created by mariotaku on 16/3/27.
 */
public class Sample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://localhost:18080").build();
        WebSocketCall call = WebSocketCall.create(client, request);
        Faye faye = Faye.create(client, call);
        faye.setErrorListener((e, code, reason) -> {
            if (e != null) {
                e.printStackTrace();
            } else {
                System.err.printf("%d: %s\n", code, reason);
            }
        });
        Scanner scanner = new Scanner(System.in);
        while (faye.getState() != Faye.DISCONNECTED && scanner.hasNext()) {
            final String line = scanner.nextLine();
            if (line.startsWith("/subscribe")) {
                final String[] split = line.split(" ", 2);
                if (split.length < 2) {
                    System.err.println("Usage: /subscribe [channel]");
                    break;
                }
                faye.subscribe(split[1], System.out::println);
            } else if (line.startsWith("/unsubscribe")) {
                final String[] split = line.split(" ", 2);
                if (split.length < 2) {
                    System.err.println("Usage: /unsubscribe [channel]");
                    break;
                }
                faye.unsubscribe(split[1]);
            } else if (line.startsWith("/disconnect")) {
                faye.disconnect();
            } else if (line.startsWith("/send")) {
                final String[] split = line.split(" ", 3);
                if (split.length < 3) {
                    System.err.println("Send message: /send [channel] [text]");
                    break;
                }
                faye.publish(split[1], split[2], System.out::println);
            } else {
                System.out.println("Subscribe to channel: /subscribe [channel]");
                System.out.println("Unsubscribe from channel: /unsubscribe [channel]");
                System.out.println("Disconnect: /disconnect");
                System.out.println("Show usage: /help");
                System.out.println("Send message: /send [channel] [text]");
            }
        }
        System.out.println("Disconnected");
    }

}


text:
using System.Collections;
using Game;
using JetBrains.Annotations;
using Mod;
using Mod.Managers;
using Mod.Modules;
using Photon.Enums;
using RC;
using UnityEngine;

// ReSharper disable once CheckNamespace
public class TITAN_SETUP : Photon.MonoBehaviour
{
    public GameObject eye;
    private CostumeHair hair;
    private GameObject hair_go_ref;
    private int hairType;
    public bool haseye;
    private GameObject part_hair;
    public int skin;

    private void Awake()
    {
        this.hair_go_ref = new GameObject();
        this.eye.transform.parent = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck/head").transform;
        this.hair_go_ref.transform.position = this.eye.transform.position + Vector3.up * 3.5f + transform.forward * 5.2f;
        this.hair_go_ref.transform.rotation = this.eye.transform.rotation;
        this.hair_go_ref.transform.RotateAround(this.eye.transform.position, transform.right, -20f);
        this.hair_go_ref.transform.localScale = new Vector3(210f, 210f, 210f);
        this.hair_go_ref.transform.parent = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck/head").transform;
    }

    [RPC]
    [UsedImplicitly]
    private IEnumerator LoadskinE(int hairId, int eyeId, string hairlink)
    {
        bool unloadAssets = false;
        Destroy(this.part_hair);
        this.hair = CostumeHair.MaleHairs[hairId];
        this.hairType = hairId;
        if (this.hair.Texture != string.Empty)
        {
            GameObject hairs = (GameObject) Instantiate(Resources.Load("Character/" + this.hair.Texture));
            hairs.transform.parent = this.hair_go_ref.transform.parent;
            hairs.transform.position = this.hair_go_ref.transform.position;
            hairs.transform.rotation = this.hair_go_ref.transform.rotation;
            hairs.transform.localScale = this.hair_go_ref.transform.localScale;
            hairs.renderer.material = CharacterMaterials.materials[this.hair.Texture];
            bool mipmap = GameManager.settings.UseMipmap;
            if (hairlink.EqualsIgnoreCase("transparent"))
                hairs.renderer.enabled = false;
            else if (Utility.IsValidImageUrl(hairlink))
            {
                if (!GameManager.linkHash[0].ContainsKey(hairlink))
                {
                    using (WWW www = new WWW(hairlink))
                    {
                        yield return www;
                        if (www.error != null)
                            yield break;
                        hairs.renderer.material.mainTexture = RCextensions.LoadImageRC(www, mipmap, 200000);
                    }

                    unloadAssets = true;
                    GameManager.linkHash[0].Add(hairlink, hairs.renderer.material);
                    hairs.renderer.material = (Material) GameManager.linkHash[0][hairlink];
                }
                else
                {
                    hairs.renderer.material = (Material) GameManager.linkHash[0][hairlink];
                }
            }
            this.part_hair = hairs;
        }

        if (eyeId >= 0)
            SetFacialTexture(eye, eyeId);
        if (unloadAssets)
            GameManager.instance.UnloadAssets();
    }

    private static void SetFacialTexture(GameObject go, int id)
    {
        if (id < 0)
            return;

        float x = 0.125f * (int)(id / 8f);
        float y = -0.25f * (id % 4);
        go.renderer.material.mainTextureOffset = new Vector2(x, y);
    }

    public void SetHair()
    {
        int num;
        if (ModuleManager.Enabled(nameof(ModuleEnableSkins)) && (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine))
        {
            var titanSkin = GameManager.settings.TitanSkin;

            Color color;
            num = Random.Range(0, 9);
            if (num == 3)
                num = 9;

            int index;
            if (GameManager.settings.Randomize)
                index = Random.Range(0, 5);
            else
                index = 0;

            if (titanSkin.Type[index] >= 0)
                num = titanSkin.Type[index];

            string hairlink = titanSkin.Hairs[index];
            int eyeId = Random.Range(1, 8);
            if (this.haseye)
            {
                eyeId = 0;
            }
            bool valid = Utility.IsValidImageUrl(hairlink);
            switch (IN_GAME_MAIN_CAMERA.GameType)
            {
                case GameType.Multiplayer when photonView.isMine && valid:
                    photonView.RPC(Rpc.SetHairSkin, PhotonTargets.AllBuffered, num, eyeId, hairlink);
                    break;

                case GameType.Multiplayer when photonView.isMine:
                    color = HeroCostume.costume[Random.Range(0, HeroCostume.costume.Length - 5)].hair_color;
                    photonView.RPC(Rpc.SetHairColor, PhotonTargets.AllBuffered, num, eyeId, color.r, color.g, color.b);
                    break;

                case GameType.Singleplayer when valid:
                    StartCoroutine(this.LoadskinE(num, eyeId, hairlink));
                    break;

                case GameType.Singleplayer:
                    color = HeroCostume.costume[Random.Range(0, HeroCostume.costume.Length - 5)].hair_color;
                    this.SetHairPRC(num, eyeId, color.r, color.g, color.b);
                    break;
            }
        }
        else
        {
            num = Random.Range(0, CostumeHair.MaleHairs.Length);
            if (num == 3)
            {
                num = 9;
            }
            Destroy(this.part_hair);
            this.hairType = num;
            this.hair = CostumeHair.MaleHairs[num];
            if (this.hair.Texture == string.Empty)
            {
                this.hair = CostumeHair.MaleHairs[9];
                this.hairType = 9;
            }
            this.part_hair = (GameObject) Instantiate(Resources.Load("Character/" + this.hair.Texture));
            this.part_hair.transform.parent = this.hair_go_ref.transform.parent;
            this.part_hair.transform.position = this.hair_go_ref.transform.position;
            this.part_hair.transform.rotation = this.hair_go_ref.transform.rotation;
            this.part_hair.transform.localScale = this.hair_go_ref.transform.localScale;
            this.part_hair.renderer.material = CharacterMaterials.materials[this.hair.Texture];
            this.part_hair.renderer.material.color = HeroCostume.costume[Random.Range(0, HeroCostume.costume.Length - 5)].hair_color;
            int id = Random.Range(1, 8);
            SetFacialTexture(this.eye, id);
            if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && photonView.isMine)
            {
                var color = part_hair.renderer.material.color;
                photonView.RPC(Rpc.SetHairColor, PhotonTargets.OthersBuffered,
                    hairType,
                    id,
                    color.r,
                    color.g,
                    color.b);
            }
        }
    }

    [RPC]
    [UsedImplicitly]
    private void SetHairRPC(int type, int eye_type, float r, float g, float b) => SetHairPRC(type, eye_type, r, g, b);

    [RPC]
    [UsedImplicitly]
    private void SetHairPRC(int type, int eye_type, float r, float g, float b)
    {
        Destroy(this.part_hair);
        this.hair = CostumeHair.MaleHairs[type];
        this.hairType = type;
        if (this.hair.Texture != string.Empty)
        {
            GameObject obj2 = (GameObject) Instantiate(Resources.Load("Character/" + this.hair.Texture));
            obj2.transform.parent = this.hair_go_ref.transform.parent;
            obj2.transform.position = this.hair_go_ref.transform.position;
            obj2.transform.rotation = this.hair_go_ref.transform.rotation;
            obj2.transform.localScale = this.hair_go_ref.transform.localScale;
            obj2.renderer.material = CharacterMaterials.materials[this.hair.Texture];
            obj2.renderer.material.color = new Color(r, g, b);
            this.part_hair = obj2;
        }
        SetFacialTexture(this.eye, eye_type);
    }

    [RPC]
    [UsedImplicitly]
    public void SetHairRPC2(int hairId, int eyeId, string hairlink)
    {
        if (ModuleManager.Enabled(nameof(ModuleEnableSkins)))
        {
            StartCoroutine(this.LoadskinE(hairId, eyeId, hairlink));
        }
    }

    public void setVar(int skinId, bool hasEye)
    {
        this.skin = skinId;
        this.haseye = hasEye;
    }
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>Three.js - Starter kit</title>
		<meta name="description" content="Experiment starter kit using Three.js, Wagner, TweenMax & Webpack">
        <meta name="viewport" content="width=device-width, initial-scale=1">


text:
import callApi from '../../util/apiCaller';
import localStorage from 'localStorage';

export const ACTIONS = {
};

export function postNews(news) {
  return () => {
    return callApi('news', 'post', '', { news }).then(res => {
      return res;
    });
  };
}

export function uploadImage(base64image) {
  return () => {
    const file = {
      base64image,
    };
    return callApi('news/photo', 'post', '', { file }).then((res) => {
      return res;
    });
  };
}


text:
<?php

namespace DeSymfony\UserBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * DeSymfonyRequestListener
 *
 */
class DeSymfonyRequestListener
{
    protected $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
            $this->logger->info("DeSymfonyUserBundle está escribiendo ...");
        }
    }
}


text:
package db

import (
	"database/sql"
	"fmt"

	_ "github.com/mattn/go-sqlite3"

	"github.com/lxc/lxd/lxd/types"
	"github.com/lxc/lxd/shared/api"
)

// Profiles returns a string list of profiles.
func Profiles(db *sql.DB) ([]string, error) {
	q := fmt.Sprintf("SELECT name FROM profiles")
	inargs := []interface{}{}
	var name string
	outfmt := []interface{}{name}
	result, err := QueryScan(db, q, inargs, outfmt)
	if err != nil {
		return []string{}, err
	}

	response := []string{}
	for _, r := range result {
		response = append(response, r[0].(string))
	}

	return response, nil
}

func ProfileGet(db *sql.DB, name string) (int64, *api.Profile, error) {
	id := int64(-1)
	description := sql.NullString{}

	q := "SELECT id, description FROM profiles WHERE name=?"
	arg1 := []interface{}{name}
	arg2 := []interface{}{&id, &description}
	err := dbQueryRowScan(db, q, arg1, arg2)
	if err != nil {
		return -1, nil, err
	}

	config, err := ProfileConfig(db, name)
	if err != nil {
		return -1, nil, err
	}

	devices, err := Devices(db, name, true)
	if err != nil {
		return -1, nil, err
	}

	profile := api.Profile{
		Name: name,
	}

	profile.Config = config
	profile.Description = description.String
	profile.Devices = devices

	return id, &profile, nil
}

func ProfileCreate(db *sql.DB, profile string, description string, config map[string]string,
	devices types.Devices) (int64, error) {

	tx, err := Begin(db)
	if err != nil {
		return -1, err
	}
	result, err := tx.Exec("INSERT INTO profiles (name, description) VALUES (?, ?)", profile, description)
	if err != nil {
		tx.Rollback()
		return -1, err
	}
	id, err := result.LastInsertId()
	if err != nil {
		tx.Rollback()
		return -1, err
	}

	err = ProfileConfigAdd(tx, id, config)
	if err != nil {
		tx.Rollback()
		return -1, err
	}

	err = DevicesAdd(tx, "profile", id, devices)
	if err != nil {
		tx.Rollback()
		return -1, err
	}

	err = TxCommit(tx)
	if err != nil {
		return -1, err
	}

	return id, nil
}

func ProfileCreateDefault(db *sql.DB) error {
	id, _, _ := ProfileGet(db, "default")

	if id != -1 {
		// default profile already exists
		return nil
	}

	// TODO: We should scan for bridges and use the best available as default.
	devices := map[string]map[string]string{
		"eth0": {
			"name":    "eth0",
			"type":    "nic",
			"nictype": "bridged",
			"parent":  "lxdbr0"}}
	_, err := ProfileCreate(db, "default", "Default LXD profile", map[string]string{}, devices)
	if err != nil {
		return err
	}

	return nil
}

func dbProfileCreateDocker(db *sql.DB) error {
	id, _, err := ProfileGet(db, "docker")

	if id != -1 {
		// docker profile already exists
		return nil
	}

	config := map[string]string{
		"security.nesting":     "true",
		"linux.kernel_modules": "overlay, nf_nat"}
	aadisable := map[string]string{
		"path":   "/sys/module/apparmor/parameters/enabled",
		"type":   "disk",
		"source": "/dev/null",
	}
	devices := map[string]map[string]string{"aadisable": aadisable}

	_, err = ProfileCreate(db, "docker", "Profile supporting docker in containers", config, devices)
	return err
}

// Get the profile configuration map from the DB
func ProfileConfig(db *sql.DB, name string) (map[string]string, error) {
	var key, value string
	query := `
        SELECT
            key, value
        FROM profiles_config
        JOIN profiles ON profiles_config.profile_id=profiles.id
		WHERE name=?`
	inargs := []interface{}{name}
	outfmt := []interface{}{key, value}
	results, err := QueryScan(db, query, inargs, outfmt)
	if err != nil {
		return nil, fmt.Errorf("Failed to get profile '%s'", name)
	}

	if len(results) == 0 {
		/*
		 * If we didn't get any rows here, let's check to make sure the
		 * profile really exists; if it doesn't, let's send back a 404.
		 */
		query := "SELECT id FROM profiles WHERE name=?"
		var id int
		results, err := QueryScan(db, query, []interface{}{name}, []interface{}{id})
		if err != nil {
			return nil, err
		}

		if len(results) == 0 {
			return nil, NoSuchObjectError
		}
	}

	config := map[string]string{}

	for _, r := range results {
		key = r[0].(string)
		value = r[1].(string)

		config[key] = value
	}

	return config, nil
}

func ProfileDelete(db *sql.DB, name string) error {
	id, _, err := ProfileGet(db, name)
	if err != nil {
		return err
	}

	_, err = Exec(db, "DELETE FROM profiles WHERE id=?", id)
	if err != nil {
		return err
	}

	return nil
}

func ProfileUpdate(db *sql.DB, name string, newName string) error {
	tx, err := Begin(db)
	if err != nil {
		return err
	}

	_, err = tx.Exec("UPDATE profiles SET name=? WHERE name=?", newName, name)
	if err != nil {
		tx.Rollback()
		return err
	}

	err = TxCommit(tx)

	return err
}

func ProfileDescriptionUpdate(tx *sql.Tx, id int64, description string) error {
	_, err := tx.Exec("UPDATE profiles SET description=? WHERE id=?", description, id)
	return err
}

func ProfileConfigClear(tx *sql.Tx, id int64) error {
	_, err := tx.Exec("DELETE FROM profiles_config WHERE profile_id=?", id)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`DELETE FROM profiles_devices_config WHERE id IN
		(SELECT profiles_devices_config.id
		 FROM profiles_devices_config JOIN profiles_devices
		 ON profiles_devices_config.profile_device_id=profiles_devices.id
		 WHERE profiles_devices.profile_id=?)`, id)
	if err != nil {
		return err
	}
	_, err = tx.Exec("DELETE FROM profiles_devices WHERE profile_id=?", id)
	if err != nil {
		return err
	}
	return nil
}

func ProfileConfigAdd(tx *sql.Tx, id int64, config map[string]string) error {
	str := fmt.Sprintf("INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)")
	stmt, err := tx.Prepare(str)
	defer stmt.Close()

	for k, v := range config {
		_, err = stmt.Exec(id, k, v)
		if err != nil {
			return err
		}
	}

	return nil
}

func ProfileContainersGet(db *sql.DB, profile string) ([]string, error) {
	q := `SELECT containers.name FROM containers JOIN containers_profiles
		ON containers.id == containers_profiles.container_id
		JOIN profiles ON containers_profiles.profile_id == profiles.id
		WHERE profiles.name == ?`

	results := []string{}
	inargs := []interface{}{profile}
	var name string
	outfmt := []interface{}{name}

	output, err := QueryScan(db, q, inargs, outfmt)
	if err != nil {
		return results, err
	}

	for _, r := range output {
		results = append(results, r[0].(string))
	}

	return results, nil
}


text:
//=============================================================================================================

//ToDo Paint to render area

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "realtimemultisamplearraywidget.h"

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace SCDISPLIB;
using namespace SCMEASLIB;

//=============================================================================================================
/**
* Tool enumeration.
*/
enum Tool
{
    Freeze     = 0,     /**< Freezing tool. */
    Annotation = 1      /**< Annotation tool. */
};

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

RealTimeMultiSampleArrayWidget::RealTimeMultiSampleArrayWidget(QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA, QSharedPointer<QTime> &pTime, QWidget* parent)
: NewMeasurementWidget(parent)
, m_pRTMSAModel(NULL)
, m_pRTMSADelegate(NULL)
, m_pTableView(NULL)
, m_fDefaultSectionSize(80.0f)
, m_fZoomFactor(1.0f)
, m_pRTMSA(pRTMSA)
, m_bInitialized(false)
, m_iT(10)
, m_fSamplingRate(1024)
, m_bHideBadChannels(false)
, m_iMaxFilterTapSize(0)
, m_pQuickControlWidget(Q_NULLPTR)
, m_pChInfoModel(Q_NULLPTR)
, m_pSelectionManagerWindow(Q_NULLPTR)
, m_pFilterWindow(Q_NULLPTR)
{
    Q_UNUSED(pTime)

    m_pActionSelectSensors = new QAction(QIcon(":/images/selectSensors.png"), tr("Shows the region selection widget (F9)"),this);
    m_pActionSelectSensors->setShortcut(tr("F9"));
    m_pActionSelectSensors->setToolTip(tr("Shows the region selection widget (F9)"));
    connect(m_pActionSelectSensors, &QAction::triggered,
            this, &RealTimeMultiSampleArrayWidget::showSensorSelectionWidget);
    addDisplayAction(m_pActionSelectSensors);
    m_pActionSelectSensors->setVisible(true);

    m_pActionHideBad = new QAction(QIcon(":/images/hideBad.png"), tr("Toggle all bad channels"),this);
    m_pActionHideBad->setStatusTip(tr("Toggle all bad channels"));
    connect(m_pActionHideBad, &QAction::triggered,
            this, &RealTimeMultiSampleArrayWidget::hideBadChannels);
    addDisplayAction(m_pActionHideBad);
    m_pActionHideBad->setVisible(true);

    m_pActionQuickControl = new QAction(QIcon(":/images/quickControl.png"), tr("Show quick control widget"),this);
    m_pActionQuickControl->setStatusTip(tr("Show quick control widget"));
    connect(m_pActionQuickControl, &QAction::triggered,
            this, &RealTimeMultiSampleArrayWidget::showQuickControlWidget);
    addDisplayAction(m_pActionQuickControl);
    m_pActionQuickControl->setVisible(true);

    if(m_pTableView)
        delete m_pTableView;
    m_pTableView = new QTableView;

    //Install event filter for tracking mouse movements
    m_pTableView->viewport()->installEventFilter(this);
    m_pTableView->setMouseTracking(true);

    //set vertical layout
    QVBoxLayout *rtmsaLayout = new QVBoxLayout(this);

    rtmsaLayout->addWidget(m_pTableView);

    //set layouts
    this->setLayout(rtmsaLayout);

    qRegisterMetaType<QMap<int,QList<QPair<int,double> > > >();

    init();
}

//*************************************************************************************************************

RealTimeMultiSampleArrayWidget::~RealTimeMultiSampleArrayWidget()
{
    //
    // Store Settings
    //
    if(!m_pRTMSA->getName().isEmpty()) {
        QString t_sRTMSAWName = m_pRTMSA->getName();

        QSettings settings;

        //Store scaling
        if(m_qMapChScaling.contains(FIFF_UNIT_T))
            settings.setValue(QString("RTMSAW/%1/scaleMAG").arg(t_sRTMSAWName), m_qMapChScaling[FIFF_UNIT_T]);

        if(m_qMapChScaling.contains(FIFF_UNIT_T_M))
            settings.setValue(QString("RTMSAW/%1/scaleGRAD").arg(t_sRTMSAWName), m_qMapChScaling[FIFF_UNIT_T_M]);

        if(m_qMapChScaling.contains(FIFFV_EEG_CH))
            settings.setValue(QString("RTMSAW/%1/scaleEEG").arg(t_sRTMSAWName), m_qMapChScaling[FIFFV_EEG_CH]);

        if(m_qMapChScaling.contains(FIFFV_EOG_CH))
            settings.setValue(QString("RTMSAW/%1/scaleEOG").arg(t_sRTMSAWName), m_qMapChScaling[FIFFV_EOG_CH]);

        if(m_qMapChScaling.contains(FIFFV_STIM_CH))
            settings.setValue(QString("RTMSAW/%1/scaleSTIM").arg(t_sRTMSAWName), m_qMapChScaling[FIFFV_STIM_CH]);

        if(m_qMapChScaling.contains(FIFFV_MISC_CH))
            settings.setValue(QString("RTMSAW/%1/scaleMISC").arg(t_sRTMSAWName), m_qMapChScaling[FIFFV_MISC_CH]);

        //Store filter
        if(m_pFilterWindow != 0) {
            FilterData filter = m_pFilterWindow->getUserDesignedFilter();

            settings.setValue(QString("RTMSAW/%1/filterHP").arg(t_sRTMSAWName), filter.m_dHighpassFreq);
            settings.setValue(QString("RTMSAW/%1/filterLP").arg(t_sRTMSAWName), filter.m_dLowpassFreq);
            settings.setValue(QString("RTMSAW/%1/filterOrder").arg(t_sRTMSAWName), filter.m_iFilterOrder);
            settings.setValue(QString("RTMSAW/%1/filterType").arg(t_sRTMSAWName), (int)filter.m_Type);
            settings.setValue(QString("RTMSAW/%1/filterDesignMethod").arg(t_sRTMSAWName), (int)filter.m_designMethod);
            settings.setValue(QString("RTMSAW/%1/filterTransition").arg(t_sRTMSAWName), filter.m_dParksWidth*(filter.m_sFreq/2));
            settings.setValue(QString("RTMSAW/%1/filterUserDesignActive").arg(t_sRTMSAWName), m_pFilterWindow->userDesignedFiltersIsActive());
            settings.setValue(QString("RTMSAW/%1/filterChannelType").arg(t_sRTMSAWName), m_pFilterWindow->getChannelType());
        }

        //Store view
        settings.setValue(QString("RTMSAW/%1/viewZoomFactor").arg(t_sRTMSAWName), m_fZoomFactor);
        settings.setValue(QString("RTMSAW/%1/viewWindowSize").arg(t_sRTMSAWName), m_iT);
        if(m_pQuickControlWidget != 0)
            settings.setValue(QString("RTMSAW/%1/viewOpacity").arg(t_sRTMSAWName), m_pQuickControlWidget->getOpacityValue());

        //Store show/hide bad channel flag
        settings.setValue(QString("RTMSAW/%1/showHideBad").arg(t_sRTMSAWName), m_bHideBadChannels);

        //Store selected layout file
        if(m_pSelectionManagerWindow != 0)
            settings.setValue(QString("RTMSAW/%1/selectedLayoutFile").arg(t_sRTMSAWName), m_pSelectionManagerWindow->getCurrentLayoutFile());

        //Store show/hide bad channel flag
        if(m_pQuickControlWidget != 0)
            settings.setValue(QString("RTMSAW/%1/distanceTimeSpacerIndex").arg(t_sRTMSAWName), m_pQuickControlWidget->getDistanceTimeSpacerIndex());

        //Store signal and background colors
        if(m_pQuickControlWidget != 0) {
            settings.setValue(QString("RTMSAW/%1/signalColor").arg(t_sRTMSAWName), m_pQuickControlWidget->getSignalColor());
            settings.setValue(QString("RTMSAW/%1/backgroundColor").arg(t_sRTMSAWName), m_pQuickControlWidget->getBackgroundColor());
        }
    }
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::broadcastScaling(QMap<qint32,float> scaleMap)
{
    m_qMapChScaling = scaleMap;
    m_pRTMSAModel->setScaling(scaleMap);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::update(SCMEASLIB::NewMeasurement::SPtr)
{
    if(!m_bInitialized)
    {
        if(m_pRTMSA->isChInit())
        {
            m_qListChInfo = m_pRTMSA->chInfo(); //ToDo Obsolete -> use fiffInfo instead
            m_pFiffInfo = m_pRTMSA->info();

            emit fiffFileUpdated(*m_pFiffInfo.data());

            m_fSamplingRate = m_pRTMSA->getSamplingRate();

            m_iMaxFilterTapSize = m_pRTMSA->getMultiSampleArray().at(m_pRTMSA->getMultiSampleArray().size()-1).cols();

            init();
        }
    }
    else
        m_pRTMSAModel->addData(m_pRTMSA->getMultiSampleArray());
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::init()
{
    if(m_qListChInfo.size() > 0)
    {
        QSettings settings;
        QString t_sRTMSAWName = m_pRTMSA->getName();

        //Init the model
        m_pRTMSAModel = RealTimeMultiSampleArrayModel::SPtr(new RealTimeMultiSampleArrayModel(this));

        m_pRTMSAModel->setFiffInfo(m_pFiffInfo);
        m_pRTMSAModel->setChannelInfo(m_qListChInfo);//ToDo Obsolete
        m_pRTMSAModel->setSamplingInfo(m_fSamplingRate, m_iT);

        //
        //-------- Init the delegate --------
        //
        m_pRTMSADelegate = RealTimeMultiSampleArrayDelegate::SPtr(new RealTimeMultiSampleArrayDelegate(this));
        m_pRTMSADelegate->initPainterPaths(m_pRTMSAModel.data());

        connect(this, &RealTimeMultiSampleArrayWidget::markerMoved,
                m_pRTMSADelegate.data(), &RealTimeMultiSampleArrayDelegate::markerMoved);

        //
        //-------- Init the view --------
        //
        m_pTableView->setModel(m_pRTMSAModel.data());
        m_pTableView->setItemDelegate(m_pRTMSADelegate.data());

        connect(m_pTableView, &QTableView::doubleClicked,
                m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::toggleFreeze);

        //set some size settings for m_pTableView
        m_pTableView->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

        m_pTableView->setShowGrid(false);

        m_pTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); //Stretch 2 column to maximal width
        m_pTableView->horizontalHeader()->hide();
        m_pTableView->verticalHeader()->setDefaultSectionSize(m_fZoomFactor*m_fDefaultSectionSize);//Row Height

        m_pTableView->setAutoScroll(false);
        m_pTableView->setColumnHidden(0,true); //because content is plotted jointly with column=1
        m_pTableView->setColumnHidden(2,true);

        m_pTableView->resizeColumnsToContents();

        m_pTableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);

//        connect(m_pTableView->verticalScrollBar(), &QScrollBar::valueChanged,
//                this, &RealTimeMultiSampleArrayWidget::visibleRowsChanged);

        if(settings.value(QString("RTMSAW/%1/showHideBad").arg(t_sRTMSAWName), false).toBool())
            hideBadChannels();

        //
        //-------- Init signal and background colors --------
        //
        QColor signalDefault = Qt::darkBlue;
        QColor backgroundDefault = Qt::white;
        QColor signal = settings.value(QString("RTMSAW/%1/signalColor").arg(t_sRTMSAWName), signalDefault).value<QColor>();
        QColor background = settings.value(QString("RTMSAW/%1/backgroundColor").arg(t_sRTMSAWName), backgroundDefault).value<QColor>();

        this->onTableViewBackgroundColorChanged(background);
        m_pRTMSADelegate->setSignalColor(signal);

        //
        //-------- Init context menu --------
        //
        m_pTableView->setContextMenuPolicy(Qt::CustomContextMenu);

        connect(m_pTableView,SIGNAL(customContextMenuRequested(QPoint)),
                this,SLOT(channelContextMenu(QPoint)));

        //
        //-------- Init scaling --------
        //
        //Show only spin boxes and labels which type are present in the current loaded fiffinfo
        QList<FiffChInfo> channelList = m_pFiffInfo->chs;
        QList<int> availabeChannelTypes;

        for(int i = 0; i<channelList.size(); i++) {
            int unit = channelList.at(i).unit;
            int type = channelList.at(i).kind;

            if(!availabeChannelTypes.contains(unit))
                availabeChannelTypes.append(unit);

            if(!availabeChannelTypes.contains(type))
                availabeChannelTypes.append(type);
        }

//        if(!t_sRTMSAWName.isEmpty())
//        {
            m_qMapChScaling.clear();

            float val = 0.0f;
            if(availabeChannelTypes.contains(FIFF_UNIT_T)) {
                val = settings.value(QString("RTMSAW/%1/scaleMAG").arg(t_sRTMSAWName), 1e-11f).toFloat();
                m_qMapChScaling.insert(FIFF_UNIT_T, val);
            }

            if(availabeChannelTypes.contains(FIFF_UNIT_T_M)) {
                val = settings.value(QString("RTMSAW/%1/scaleGRAD").arg(t_sRTMSAWName), 1e-10f).toFloat();
                m_qMapChScaling.insert(FIFF_UNIT_T_M, val);
            }

            if(availabeChannelTypes.contains(FIFFV_EEG_CH)) {
                val = settings.value(QString("RTMSAW/%1/scaleEEG").arg(t_sRTMSAWName), 1e-4f).toFloat();
                m_qMapChScaling.insert(FIFFV_EEG_CH, val);
            }

            if(availabeChannelTypes.contains(FIFFV_EOG_CH)) {
                val = settings.value(QString("RTMSAW/%1/scaleEOG").arg(t_sRTMSAWName), 1e-3f).toFloat();
                m_qMapChScaling.insert(FIFFV_EOG_CH, val);
            }

            if(availabeChannelTypes.contains(FIFFV_STIM_CH)) {
                val = settings.value(QString("RTMSAW/%1/scaleSTIM").arg(t_sRTMSAWName), 1e-3f).toFloat();
                m_qMapChScaling.insert(FIFFV_STIM_CH, val);
            }

            if(availabeChannelTypes.contains(FIFFV_MISC_CH)) {
                val = settings.value(QString("RTMSAW/%1/scaleMISC").arg(t_sRTMSAWName), 1e-3f).toFloat();
                m_qMapChScaling.insert(FIFFV_MISC_CH, val);
            }

            m_pRTMSAModel->setScaling(m_qMapChScaling);
//        }

        //
        //-------- Init bad channel list --------
        //
        m_qListBadChannels.clear();
        for(int i = 0; i<m_pRTMSAModel->rowCount(); i++)
            if(m_pRTMSAModel->data(m_pRTMSAModel->index(i,2)).toBool())
                m_qListBadChannels << i;

        //-------- Init filter window --------
        m_pFilterWindow = QSharedPointer<FilterWindow>(new FilterWindow(this, Qt::Window/* | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint*/));
        //m_pFilterWindow->setWindowFlags(Qt::WindowStaysOnTopHint);

        m_pFilterWindow->setFiffInfo(m_pFiffInfo);
        m_pFilterWindow->setWindowSize(m_iMaxFilterTapSize);
        m_pFilterWindow->setMaxFilterTaps(m_iMaxFilterTapSize);

        connect(m_pFilterWindow.data(),static_cast<void (FilterWindow::*)(QString)>(&FilterWindow::applyFilter),
                m_pRTMSAModel.data(),static_cast<void (RealTimeMultiSampleArrayModel::*)(QString)>(&RealTimeMultiSampleArrayModel::setFilterChannelType));

        connect(m_pFilterWindow.data(), &FilterWindow::filterChanged,
                m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::filterChanged);

        connect(m_pFilterWindow.data(), &FilterWindow::filterActivated,
                m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::filterActivated);

        //Set stored filter settings from last session
        m_pFilterWindow->setFilterParameters(settings.value(QString("RTMSAW/%1/filterHP").arg(t_sRTMSAWName), 5.0).toDouble(),
                                                settings.value(QString("RTMSAW/%1/filterLP").arg(t_sRTMSAWName), 40.0).toDouble(),
                                                settings.value(QString("RTMSAW/%1/filterOrder").arg(t_sRTMSAWName), 128).toInt(),
                                                settings.value(QString("RTMSAW/%1/filterType").arg(t_sRTMSAWName), 2).toInt(),
                                                settings.value(QString("RTMSAW/%1/filterDesignMethod").arg(t_sRTMSAWName), 0).toInt(),
                                                settings.value(QString("RTMSAW/%1/filterTransition").arg(t_sRTMSAWName), 5.0).toDouble(),
                                                settings.value(QString("RTMSAW/%1/filterUserDesignActive").arg(t_sRTMSAWName), false).toBool(),
                                                settings.value(QString("RTMSAW/%1/filterChannelType").arg(t_sRTMSAWName), "MEG").toString());

        //
        //-------- Init channel selection manager --------
        //
        m_pChInfoModel = QSharedPointer<ChInfoModel>(new ChInfoModel(m_pFiffInfo, this));

        m_pSelectionManagerWindow = SelectionManagerWindow::SPtr(new SelectionManagerWindow(this, m_pChInfoModel));
        //m_pSelectionManagerWindow->setWindowFlags(Qt::WindowStaysOnTopHint);

        connect(m_pSelectionManagerWindow.data(), &SelectionManagerWindow::showSelectedChannelsOnly,
                this, &RealTimeMultiSampleArrayWidget::showSelectedChannelsOnly);

        //Connect channel info model
        connect(m_pSelectionManagerWindow.data(), &SelectionManagerWindow::loadedLayoutMap,
                m_pChInfoModel.data(), &ChInfoModel::layoutChanged);

        connect(m_pSelectionManagerWindow.data(), &SelectionManagerWindow::loadedLayoutMap,
                m_pSelectionManagerWindow.data(), &SelectionManagerWindow::updateBadChannels);

        connect(m_pChInfoModel.data(), &ChInfoModel::channelsMappedToLayout,
                m_pSelectionManagerWindow.data(), &SelectionManagerWindow::setCurrentlyMappedFiffChannels);

        m_pChInfoModel->fiffInfoChanged(m_pFiffInfo);

        m_pSelectionManagerWindow->setCurrentLayoutFile(settings.value(QString("RTMSAW/%1/selectedLayoutFile").arg(t_sRTMSAWName), "babymeg-mag-inner-layer.lout").toString());

        //
        //-------- Init quick control widget --------
        //
        QStringList slFlags = m_pRTMSA->getDisplayFlags();

        #ifdef BUILD_BASIC_MNESCAN_VERSION
            std::cout<<"BUILD_BASIC_MNESCAN_VERSION Defined"<<std::endl;
            slFlags.clear();
            slFlags << "projections" << "view" << "scaling";
        #endif

        m_pQuickControlWidget = QSharedPointer<QuickControlWidget>(new QuickControlWidget(m_qMapChScaling, m_pFiffInfo, "RT Display", slFlags));

        m_pQuickControlWidget->setWindowFlags(Qt::WindowStaysOnTopHint);

        //Handle scaling
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::scalingChanged,
                this, &RealTimeMultiSampleArrayWidget::broadcastScaling);

        //Handle signal color changes
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::signalColorChanged,
                m_pRTMSADelegate.data(), &RealTimeMultiSampleArrayDelegate::setSignalColor);

        //Handle background color changes
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::backgroundColorChanged,
                this, &RealTimeMultiSampleArrayWidget::onTableViewBackgroundColorChanged);

        //Handle screenshot signals
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::makeScreenshot,
                this, &RealTimeMultiSampleArrayWidget::onMakeScreenshot);

        //Handle projections
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::projSelectionChanged,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::updateProjection);

        //Handle compensators
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::compSelectionChanged,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::updateCompensator);

        //Handle SPHARA
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::spharaActivationChanged,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::updateSpharaActivation);

        connect(m_pQuickControlWidget.data(), &QuickControlWidget::spharaOptionsChanged,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::updateSpharaOptions);

        //Handle view changes
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::zoomChanged,
                this, &RealTimeMultiSampleArrayWidget::zoomChanged);

        connect(m_pQuickControlWidget.data(), &QuickControlWidget::timeWindowChanged,
                this, &RealTimeMultiSampleArrayWidget::timeWindowChanged);

        //Handle Filtering
        connect(m_pFilterWindow.data(), &FilterWindow::activationCheckBoxListChanged,
                m_pQuickControlWidget.data(), &QuickControlWidget::filterGroupChanged);

        connect(m_pQuickControlWidget.data(), &QuickControlWidget::showFilterOptions,
                this, &RealTimeMultiSampleArrayWidget::showFilterWidget);

        //Handle trigger detection
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::triggerInfoChanged,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::triggerInfoChanged);

        connect(m_pQuickControlWidget.data(), &QuickControlWidget::resetTriggerCounter,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::resetTriggerCounter);

        connect(this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::triggerDetected,
                m_pQuickControlWidget.data(), &QuickControlWidget::setNumberDetectedTriggersAndTypes);

        //Handle time spacer distance
        connect(m_pQuickControlWidget.data(), &QuickControlWidget::distanceTimeSpacerChanged,
                this->m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::distanceTimeSpacerChanged);

        m_pQuickControlWidget->filterGroupChanged(m_pFilterWindow->getActivationCheckBoxList());

        m_pQuickControlWidget->setViewParameters(settings.value(QString("RTMSAW/%1/viewZoomFactor").arg(t_sRTMSAWName), 1.0).toFloat(),
                                                 settings.value(QString("RTMSAW/%1/viewWindowSize").arg(t_sRTMSAWName), 10).toInt(),
                                                 settings.value(QString("RTMSAW/%1/viewOpacity").arg(t_sRTMSAWName), 95).toInt());

        m_pQuickControlWidget->setDistanceTimeSpacerIndex(settings.value(QString("RTMSAW/%1/distanceTimeSpacerIndex").arg(t_sRTMSAWName), 3).toInt());

        m_pQuickControlWidget->setSignalBackgroundColors(signal, background);

        //If projections are wanted activate projections as default
        if(slFlags.contains("projections")) {
            m_pRTMSAModel->updateProjection();
        }

        //Initialized
        m_bInitialized = true;
    }
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::channelContextMenu(QPoint pos)
{
    //obtain index where index was clicked
    QModelIndex index = m_pTableView->indexAt(pos);

    //get selected items
    QModelIndexList selected = m_pTableView->selectionModel()->selectedIndexes();

    //create custom context menu and actions
    QMenu *menu = new QMenu(this);

    //**************** Marking ****************
    if(!m_qListBadChannels.contains(index.row())) {
        QAction* doMarkChBad = menu->addAction(tr("Mark as bad"));
        connect(doMarkChBad, &QAction::triggered,
                this, &RealTimeMultiSampleArrayWidget::markChBad);
    } else {
        QAction* doMarkChGood = menu->addAction(tr("Mark as good"));
        connect(doMarkChGood, &QAction::triggered,
                this, &RealTimeMultiSampleArrayWidget::markChBad);
    }

    // non C++11 alternative
    m_qListCurrentSelection.clear();
    for(qint32 i = 0; i < selected.size(); ++i)
        if(selected[i].column() == 1)
            m_qListCurrentSelection.append(m_pRTMSAModel->getIdxSelMap()[selected[i].row()]);

    QAction* doSelection = menu->addAction(tr("Apply selection"));
    connect(doSelection, &QAction::triggered,
            this, &RealTimeMultiSampleArrayWidget::applySelection);

    //select channels
    QAction* hideSelection = menu->addAction(tr("Hide selection"));
    connect(hideSelection, &QAction::triggered, this,
            &RealTimeMultiSampleArrayWidget::hideSelection);

    //undo selection
    QAction* resetAppliedSelection = menu->addAction(tr("Reset selection"));
    connect(resetAppliedSelection, &QAction::triggered,
            m_pRTMSAModel.data(), &RealTimeMultiSampleArrayModel::resetSelection);
    connect(resetAppliedSelection, &QAction::triggered,
            this, &RealTimeMultiSampleArrayWidget::resetSelection);

    //show context menu
    menu->popup(m_pTableView->viewport()->mapToGlobal(pos));
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::resizeEvent(QResizeEvent* resizeEvent)
{
    Q_UNUSED(resizeEvent)
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::keyPressEvent(QKeyEvent* keyEvent)
{
    Q_UNUSED(keyEvent)
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::mousePressEvent(QMouseEvent* mouseEvent)
{
    Q_UNUSED(mouseEvent)
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::mouseMoveEvent(QMouseEvent* mouseEvent)
{
    Q_UNUSED(mouseEvent)
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::mouseReleaseEvent(QMouseEvent* mouseEvent)
{
    Q_UNUSED(mouseEvent)
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::mouseDoubleClickEvent(QMouseEvent* mouseEvent)
{
    Q_UNUSED(mouseEvent)
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::wheelEvent(QWheelEvent* wheelEvent)
{
    Q_UNUSED(wheelEvent)
}

//*************************************************************************************************************

bool RealTimeMultiSampleArrayWidget::eventFilter(QObject *object, QEvent *event)
{
    if (object == m_pTableView->viewport() && event->type() == QEvent::MouseMove) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        emit markerMoved(mouseEvent->pos(), m_pTableView->rowAt(mouseEvent->pos().y()));
        return true;
    }

    return NewMeasurementWidget::eventFilter(object, event);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::zoomChanged(double zoomFac)
{
    m_fZoomFactor = zoomFac;

    m_pTableView->verticalHeader()->setDefaultSectionSize(m_fZoomFactor*m_fDefaultSectionSize);//Row Height
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::timeWindowChanged(int T)
{
    m_iT = T;

    m_pRTMSAModel->setSamplingInfo(m_fSamplingRate, T);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::applySelection()
{
    //Hide non selected channels/rows in the data views
    for(int i = 0; i<m_pRTMSAModel->rowCount(); i++) {
        //if channel is a bad channel and bad channels are to be hidden -> do not show
        if(m_qListCurrentSelection.contains(i))
            m_pTableView->showRow(i);
        else
            m_pTableView->hideRow(i);
    }

    //Update the visible channel list which are to be filtered
    //visibleRowsChanged(0);

    //m_pRTMSAModel->selectRows(m_qListCurrentSelection);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::hideSelection()
{
    for(int i=0; i<m_qListCurrentSelection.size(); i++)
        m_pTableView->hideRow(m_qListCurrentSelection.at(i));

    //Update the visible channel list which are to be filtered
    //visibleRowsChanged(0);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::resetSelection()
{
    // non C++11 alternative
    for(qint32 i = 0; i < m_qListChInfo.size(); ++i) {
        if(m_qListBadChannels.contains(i)) {
            if(!m_bHideBadChannels) {
                m_pTableView->showRow(i);
            }
        }
        else {
            m_pTableView->showRow(i);
        }
    }

    //Update the visible channel list which are to be filtered
    //visibleRowsChanged(0);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::showSelectedChannelsOnly(QStringList selectedChannels)
{
    m_slSelectedChannels = selectedChannels;

    //Hide non selected channels/rows in the data views
    for(int i = 0; i<m_pRTMSAModel->rowCount(); i++) {
        QString channel = m_pRTMSAModel->data(m_pRTMSAModel->index(i, 0), Qt::DisplayRole).toString();

        //if channel is a bad channel and bad channels are to be hidden -> do not show
        if(!selectedChannels.contains(channel) || (m_qListBadChannels.contains(i) && m_bHideBadChannels))
            m_pTableView->hideRow(i);
        else
            m_pTableView->showRow(i);
    }

    //Update the visible channel list which are to be filtered
    //visibleRowsChanged(0);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::visibleRowsChanged(int value)
{
    Q_UNUSED(value);
    //std::cout <<"Visible channels: "<< m_pTableView->rowAt(0) << "-" << m_pTableView->rowAt(m_pTableView->height())<<std::endl;

    int from = m_pTableView->rowAt(0);
    if(from != 0)
        from--;

    int to = m_pTableView->rowAt(m_pTableView->height()-1);
    if(to != m_pRTMSAModel->rowCount()-1)
        to++;

    if(from > to)
        to = m_pRTMSAModel->rowCount()-1;

    QStringList channelNames;

    for(int i = from; i<=to; i++) {
        channelNames << m_pRTMSAModel->data(m_pRTMSAModel->index(i, 0), Qt::DisplayRole).toString();
        //std::cout << m_pRTMSAModel->data(m_pRTMSAModel->index(i, 0), Qt::DisplayRole).toString().toStdString() << std::endl;
    }

    m_pRTMSAModel->createFilterChannelList(channelNames);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::markChBad()
{
    QModelIndexList selected = m_pTableView->selectionModel()->selectedIndexes();

    for(int i=0; i<selected.size(); i++) {
        if(m_qListBadChannels.contains(selected[i].row())) { //mark as good
            m_pRTMSAModel->markChBad(selected[i], false);
            m_qListBadChannels.removeAll(selected[i].row());
        }
        else {
            m_pRTMSAModel->markChBad(selected[i], true);
            m_qListBadChannels.append(selected[i].row());
        }
    }

    m_pRTMSAModel->updateProjection();

    m_pSelectionManagerWindow->updateBadChannels();
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::hideBadChannels()
{
    if(m_pActionHideBad->toolTip() == "Show all bad channels") {
        m_pActionHideBad->setIcon(QIcon(":/images/hideBad.png"));
        m_pActionHideBad->setToolTip("Hide all bad channels");
        m_pActionHideBad->setStatusTip(tr("Hide all bad channels"));
        m_bHideBadChannels = false;
    }
    else {
        m_pActionHideBad->setIcon(QIcon(":/images/showBad.png"));
        m_pActionHideBad->setToolTip("Show all bad channels");
        m_pActionHideBad->setStatusTip(tr("Show all bad channels"));
        m_bHideBadChannels = true;
    }

    //Hide non selected channels/rows in the data views
    for(int i = 0; i<m_qListBadChannels.size(); i++) {
        if(m_bHideBadChannels)
            m_pTableView->hideRow(m_qListBadChannels.at(i));
        else
            m_pTableView->showRow(m_qListBadChannels.at(i));
    }

    //Update the visible channel list which are to be filtered
    //visibleRowsChanged(0);
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::showFilterWidget(bool state)
{
    if(state) {
        if(m_pFilterWindow->isActiveWindow())
            m_pFilterWindow->hide();
        else {
            m_pFilterWindow->activateWindow();
            m_pFilterWindow->show();
        }
    } else {
        m_pFilterWindow->hide();
    }
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::showSensorSelectionWidget()
{
    if(m_pSelectionManagerWindow->isActiveWindow())
        m_pSelectionManagerWindow->hide();
    else {
        m_pSelectionManagerWindow->activateWindow();
        m_pSelectionManagerWindow->show();
    }
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::showQuickControlWidget()
{
    m_pQuickControlWidget->show();
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::onTableViewBackgroundColorChanged(const QColor& backgroundColor)
{
    m_pTableView->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(backgroundColor.red()).arg(backgroundColor.green()).arg(backgroundColor.blue()));
}

//*************************************************************************************************************

void RealTimeMultiSampleArrayWidget::onMakeScreenshot(const QString& imageType)
{
    // Create file name
    QString sDate = QDate::currentDate().toString("yyyy_MM_dd");
    QString sTime = QTime::currentTime().toString("hh_mm_ss");

    if(!QDir("./Screenshots").exists()) {
        QDir().mkdir("./Screenshots");
    }

    if(imageType.contains("SVG"))
    {
        QString fileName = QString("./Screenshots/%1-%2-DataView.svg").arg(sDate).arg(sTime);
        // Generate screenshot
        QSvgGenerator svgGen;
        svgGen.setFileName(fileName);
        svgGen.setSize(m_pTableView->size());
        svgGen.setViewBox(m_pTableView->rect());

        m_pTableView->render(&svgGen);
    }

    if(imageType.contains("PNG"))
    {
        QString fileName = QString("./Screenshots/%1-%2-DataView.png").arg(sDate).arg(sTime);
        QPixmap pixMap = QPixmap::grabWidget(m_pTableView);
        pixMap.save(fileName);
    }
}


text:
! http://adventofcode.com/day/2
!
! Part 1
! ------
! The elves are running low on wrapping paper, and so they need to submit an
! order for more. They have a list of the dimensions (length l, width w, and
! height h) of each present, and only want to order exactly as much as they
! need.
!
! Fortunately, every present is a box (a perfect right rectangular prism),
! which makes calculating the required wrapping paper for each gift a little
! easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l.
! The elves also need a little extra paper for each present: the area of the
! smallest side.
!
! For example:
!
!   - A present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square
!        feet of wrapping paper plus 6 square feet of slack, for a total of
!        58 square feet.
!  - A present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square
!        feet of wrapping paper plus 1 square foot of slack, for a total of
!        43 square feet.
!
! All numbers in the elves' list are in feet. How many total square feet of
! wrapping paper should they order?
!
!
! Part 2
! ------
! The elves are also running low on ribbon. Ribbon is all the same width, so
! they only have to worry about the length they need to order, which they
! would again like to be exact.
!
! The ribbon required to wrap a present is the shortest distance around its
! sides, or the smallest perimeter of any one face. Each present also
! requires a bow made out of ribbon as well; the feet of ribbon required for
! the perfect bow is equal to the cubic feet of volume of the present. Don't
! ask how they tie the bow, though; they'll never tell.
!
! For example:
!
!   - A present with dimensions 2x3x4 requires 2+2+3+3 = 10 feet of ribbon to
!        wrap the present plus 2*3*4 = 24 feet of ribbon for the bow, for a
!        total of 34 feet.
!   - A present with dimensions 1x1x10 requires 1+1+1+1 = 4 feet of ribbon to
!        wrap the present plus 1*1*10 = 10 feet of ribbon for the bow, for a
!        total of 14 feet.
!
! How many total feet of ribbon should they order?

program puzzle02
    implicit none

    integer, parameter :: infile = 10
    character(50) :: text
    character(8) :: num
    integer :: paper, ribbon, length, width, height, ios
    integer :: area1, area2, area3, smallarea, s1, s2

    open(unit=infile, file='../advent2015/inputs/input02.txt')
    paper = 0
    ribbon = 0

    do
        ! Read the next line in
        read(infile, '(a50)', iostat=ios) text
        if (ios .ne. 0) then
            exit
        end if

        call tokenize(trim(text), length, width, height)
        call twosmallest(length, width, height, s1, s2)

        area1 = 2 * length * width
        area2 = 2 * width * height
        area3 = 2 * height * length
        smallarea = min(area1, area2, area3) / 2

        paper = paper + area1 + area2 + area3 + smallarea
        ribbon = ribbon + (2 * s1) + (2 * s2) + length * width * height
    end do

    write (num, '(i8)') paper
    print '(a22, a8)', '[Fortran] Puzzle 2-1: ', adjustl(num)
    write (num, '(i8)') ribbon
    print '(a22, a8)', '[Fortran] Puzzle 2-2: ', adjustl(num)
end program

subroutine tokenize(text, length, width, height)
    implicit none

    character(*), intent(in) :: text
    integer, intent(out) :: length, width, height
    character(10) :: values(3)
    integer :: pos1, pos2, n, i

    pos1 = 1
    pos2 = 0
    n = 0

    do
        pos2 = index(text(pos1:), 'x')

        if (pos2 == 0) then
            n = n + 1
            values(n) = text(pos1:)
            exit
        end if

        n = n + 1
        values(n) = text(pos1:pos1 + pos2 - 2)
        pos1 = pos2 + pos1
    end do

    read (values(1), '(i10)') length
    read (values(2), '(i10)') width
    read (values(3), '(i10)') height
end subroutine

subroutine twosmallest(val1, val2, val3, small1, small2)
    implicit none

    integer, intent(in) :: val1, val2, val3
    integer, intent(out) :: small1, small2
    integer :: big

    ! WARNING: ugly hack

    big = max(val1, val2, val3)

    if (big == val1) then
        small1 = val2
        small2 = val3
    elseif (big == val2) then
        small1 = val1
        small2 = val3
    else
        small1 = val1
        small2 = val2
    end if
end subroutine


text:
package ch.fhnw.util;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.util.Set;

public class AutoDisposer<T> extends Thread {
	private static final Log LOG = Log.create();

	private static final boolean DBG = false;

	protected ReferenceQueue<T>                   refQ   = new ReferenceQueue<>();
	protected IdentityHashSet<Reference<T>>       refSet = new IdentityHashSet<>();
	private   Class<? extends Reference<T>>       refCls;
	private   Constructor<? extends Reference<T>> ctor;

	public AutoDisposer(Class<? extends Reference<T>> refCls) {
		super("AutoDisposer for " + refCls.getName());
		this.refCls = refCls;
		setDaemon(true);
		setPriority(Thread.MIN_PRIORITY);
		start();
	}

	@SuppressWarnings("unchecked")
	public synchronized void add(T object) {
		try {
			if(ctor == null) {
				for(Constructor<?> ctor : refCls.getDeclaredConstructors()) {
					Class<?>[] argTypes = ctor.getParameterTypes();
					if(argTypes.length == 2
							&& argTypes[0].isAssignableFrom(object.getClass())
							&& argTypes[1].isAssignableFrom(refQ.getClass())) {
						this.ctor = (Constructor<? extends Reference<T>>) ctor;
						break;
					}
				}
				if(ctor == null)
					throw new IllegalArgumentException("No reference constructor found in " + refCls.getName());
			}

			Reference<T> ref = ctor.newInstance(object, refQ);
			refSet.add(ref);

			if(DBG) System.out.println("add:" + ref);
		} catch(Throwable t) {
			LOG.severe(t);
		}
	}

	@Override
	public void run() {
		for(;;) {
			try {
				doDispose((Reference<?>)refQ.remove());
			} catch (Throwable t) {
				LOG.severe(t);
			}
		}
	}

	public synchronized void doDispose() {
		if(DBG) System.out.println("*** " + refCls.getName() + ": doDispose(" + refSet.size() + ")");
		for(;;) {
			Reference<?> ref = (Reference<?>) refQ.poll();
			if(ref == null)
				break;

			doDispose(ref);
		}
		if(DBG) System.out.println("+++ " + refCls.getName() + ": doDispose");
	}

	private void doDispose(Reference<?> ref) {
		if(DBG) System.out.println("dispose:" + ref);
		ref.dispose();
		refSet.remove(ref);
	}

	public abstract static class Reference<T> extends WeakReference<T> {
		String label;

		public Reference(T referent, ReferenceQueue<? super T> q) {
			super(referent, q);
			try {
				label = referent.toString();
			} catch(Throwable t) {}
		}

		public abstract void dispose();

		@Override
		public String toString() {
			return getClass().getName() + ":" + ClassUtilities.identityHashCode(this) + ":" + label;
		}
	}

	public Set<Reference<T>> getRefSet() {
		return refSet;
	}

	public static void runGC() {
		for(int i = 0; i < 5; i++) {
			long before = Runtime.getRuntime().freeMemory();
			System.gc();
			Runtime.getRuntime().runFinalization();
			System.gc();
			long after  = Runtime.getRuntime().freeMemory();
			if(after >= before)
				break;
		}
	}
}


text:
package org.jetbrains.plugins.scala.testingSupport.scalatest.generators

import org.jetbrains.plugins.scala.testingSupport.scalatest.ScalaTestTestCase

/**
  * @author Roman.Shein
  * @since 10.02.2015.
  */
trait FunSpecGenerator extends ScalaTestTestCase {
  def funSpecClassName = "FunSpecTest"

  def funSpecFileName = funSpecClassName + ".scala"

  def addFunSpec() {
    addFileToProject("FunSpecTest.scala",
      """
        |import org.scalatest._
        |
        |class FunSpecTest extends FunSpec {
        |  describe("FunSpecTest") {
        |    it ("should launch single test") {
        |      print(">>TEST: OK<<")
        |    }
        |
        |    it ("should not launch other tests") {
        |      print(">>TEST: FAILED<<")
        |    }
        |  }
        |
        |  describe("OtherScope") {
        |    it ("is here") {}
        |  }
        |
        |  describe("emptyScope") {}
        |}
      """.stripMargin.trim()
    )
  }
}


text:
package test

type typeForTest [4]byte


text:
from django.conf.urls import include, patterns

from mkt.purchase.urls import app_purchase_patterns
from mkt.receipts.urls import app_receipt_patterns

urlpatterns = patterns('',
    # Merge app purchase / receipt patterns.
    ('^purchase/', include(app_purchase_patterns)),
    ('^purchase/', include(app_receipt_patterns)),
)


text:
========================================
spectra-SPECTROGRAPH-TILEID-GROUPID.fits
========================================

:Summary: *This section should be filled in with a high-level description of
    this file. In general, you should remove or replace the emphasized text
    (\*this text is emphasized\*) in this document.*
:Naming Convention: ``spectra-SPECTROGRAPH-TILEID-GROUPID.fits``, where
    ``SPECTROGRAPH`` is the spectrograph ID, ``TILEID`` is the tile number and
    ``GROUPID`` depends on the ``GROUPTYPE`` of the tile coadd.
:Regex: ``spectra-[0-9]-[0-9]+-([14]xsubset[1-6]|lowspeedsubset[1-6]|exp[0-9]{8}|thru[0-9]{8}|[0-9]{8})\.fits``
:File Type: FITS, 198 MB

Contents
========

====== ============ ======== ===================
Number EXTNAME      Type     Contents
====== ============ ======== ===================
HDU00_              IMAGE    Keywords only
HDU01_ FIBERMAP     BINTABLE *Brief Description*
HDU02_ SCORES       BINTABLE *Brief Description*
HDU03_ B_WAVELENGTH IMAGE    *Brief Description*
HDU04_ B_FLUX       IMAGE    *Brief Description*
HDU05_ B_IVAR       IMAGE    *Brief Description*
HDU06_ B_MASK       BINTABLE *Brief Description*
HDU07_ B_RESOLUTION IMAGE    *Brief Description*
HDU08_ R_WAVELENGTH IMAGE    *Brief Description*
HDU09_ R_FLUX       IMAGE    *Brief Description*
HDU10_ R_IVAR       IMAGE    *Brief Description*
HDU11_ R_MASK       BINTABLE *Brief Description*
HDU12_ R_RESOLUTION IMAGE    *Brief Description*
HDU13_ Z_WAVELENGTH IMAGE    *Brief Description*
HDU14_ Z_FLUX       IMAGE    *Brief Description*
HDU15_ Z_IVAR       IMAGE    *Brief Description*
HDU16_ Z_MASK       BINTABLE *Brief Description*
HDU17_ Z_RESOLUTION IMAGE    *Brief Description*
====== ============ ======== ===================

FITS Header Units
=================

HDU00
-----

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ========== ================ ==== ==============================================
    KEY        Example Value    Type Comment
    ========== ================ ==== ==============================================
    SPGRP      1x_depth         str
    SPGRPVAL   3                int
    NIGHT [1]_ 20210708         int
    TILEID     80605            int
    SPECTRO    6                int
    PETAL      6                int
    CHECKSUM   cXXRdWUQcWUQcWUQ str  HDU checksum updated 2021-07-15T00:33:13
    DATASUM    0                str  data unit checksum updated 2021-07-15T00:33:13
    ========== ================ ==== ==============================================

Empty HDU.

HDU01
-----

EXTNAME = FIBERMAP

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ======== ================ ==== ==============================================
    KEY      Example Value    Type Comment
    ======== ================ ==== ==============================================
    NAXIS1   413              int  length of dimension 1
    NAXIS2   500              int  length of dimension 2
    CHECKSUM TcPqUbPoTbPoTbPo str  HDU checksum updated 2021-07-15T00:33:13
    DATASUM  1051947488       str  data unit checksum updated 2021-07-15T00:33:13
    ======== ================ ==== ==============================================

Required Data Table Columns
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. rst-class:: columns

===================== ======= ===== ===========
Name                  Type    Units Description
===================== ======= ===== ===========
TARGETID              int64
PETAL_LOC             int16
DEVICE_LOC            int32
LOCATION              int64
FIBER                 int32
FIBERSTATUS           int32
TARGET_RA             float64
TARGET_DEC            float64
PMRA                  float32
PMDEC                 float32
REF_EPOCH             float32
LAMBDA_REF            float32
FA_TARGET             int64
FA_TYPE               binary
OBJTYPE               char[3]
FIBERASSIGN_X         float32
FIBERASSIGN_Y         float32
PRIORITY              int32
SUBPRIORITY           float64
OBSCONDITIONS         int32
RELEASE               int16
BRICKID               int32
BRICK_OBJID           int32
MORPHTYPE             char[4]
FLUX_G                float32
FLUX_R                float32
FLUX_Z                float32
FLUX_IVAR_G           float32
FLUX_IVAR_R           float32
FLUX_IVAR_Z           float32
MASKBITS              int16
REF_ID                int64
REF_CAT               char[2]
GAIA_PHOT_G_MEAN_MAG  float32
GAIA_PHOT_BP_MEAN_MAG float32
GAIA_PHOT_RP_MEAN_MAG float32
PARALLAX              float32
BRICKNAME             char[8]
EBV                   float32
FLUX_W1               float32
FLUX_W2               float32
FLUX_IVAR_W1          float32
FLUX_IVAR_W2          float32
FIBERFLUX_G           float32
FIBERFLUX_R           float32
FIBERFLUX_Z           float32
FIBERTOTFLUX_G        float32
FIBERTOTFLUX_R        float32
FIBERTOTFLUX_Z        float32
SERSIC                float32
SHAPE_R               float32
SHAPE_E1              float32
SHAPE_E2              float32
PHOTSYS               char[1]
PRIORITY_INIT         int64
NUMOBS_INIT           int64
SV1_DESI_TARGET [1]_  int64
SV1_BGS_TARGET [1]_   int64
SV1_MWS_TARGET [1]_   int64
SV1_SCND_TARGET [1]_  int64
SV3_DESI_TARGET [1]_  int64
SV3_BGS_TARGET [1]_   int64
SV3_MWS_TARGET [1]_   int64
SV3_SCND_TARGET [1]_  int64
DESI_TARGET           int64
BGS_TARGET            int64
MWS_TARGET            int64
SCND_TARGET [1]_      int64
PLATE_RA              float64
PLATE_DEC             float64
NUM_ITER              int64
FIBER_X               float64
FIBER_Y               float64
DELTA_X               float64
DELTA_Y               float64
FIBER_RA              float64
FIBER_DEC             float64
EXPTIME               float64
PSF_TO_FIBER_SPECFLUX float64
NIGHT                 int32
EXPID                 int32
MJD                   float64
TILEID                int32
===================== ======= ===== ===========

.. [1] Optional

HDU02
-----

EXTNAME = SCORES

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =======================
    KEY    Example Value Type Comment
    ====== ============= ==== =======================
    NAXIS1 488           int  width of table in bytes
    NAXIS2 500           int  number of rows in table
    ====== ============= ==== =======================

Required Data Table Columns
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. rst-class:: columns

===================== ======= ===== ===================
Name                  Type    Units Description
===================== ======= ===== ===================
TARGETID              int64         label for field   1
SUM_RAW_COUNT_B       float64       label for field   2
MEDIAN_RAW_COUNT_B    float64       label for field   3
MEDIAN_RAW_SNR_B      float64       label for field   4
SUM_FFLAT_COUNT_B     float64       label for field   5
MEDIAN_FFLAT_COUNT_B  float64       label for field   6
MEDIAN_FFLAT_SNR_B    float64       label for field   7
SUM_SKYSUB_COUNT_B    float64       label for field   8
MEDIAN_SKYSUB_COUNT_B float64       label for field   9
MEDIAN_SKYSUB_SNR_B   float64       label for field  10
SUM_CALIB_COUNT_B     float64       label for field  11
MEDIAN_CALIB_COUNT_B  float64       label for field  12
MEDIAN_CALIB_SNR_B    float64       label for field  13
TSNR2_GPBDARK_B       float64       label for field  14
TSNR2_ELG_B           float64       label for field  15
TSNR2_GPBBRIGHT_B     float64       label for field  16
TSNR2_LYA_B           float64       label for field  17
TSNR2_BGS_B           float64       label for field  18
TSNR2_GPBBACKUP_B     float64       label for field  19
TSNR2_QSO_B           float64       label for field  20
TSNR2_LRG_B           float64       label for field  21
SUM_RAW_COUNT_R       float64       label for field  22
MEDIAN_RAW_COUNT_R    float64       label for field  23
MEDIAN_RAW_SNR_R      float64       label for field  24
SUM_FFLAT_COUNT_R     float64       label for field  25
MEDIAN_FFLAT_COUNT_R  float64       label for field  26
MEDIAN_FFLAT_SNR_R    float64       label for field  27
SUM_SKYSUB_COUNT_R    float64       label for field  28
MEDIAN_SKYSUB_COUNT_R float64       label for field  29
MEDIAN_SKYSUB_SNR_R   float64       label for field  30
SUM_CALIB_COUNT_R     float64       label for field  31
MEDIAN_CALIB_COUNT_R  float64       label for field  32
MEDIAN_CALIB_SNR_R    float64       label for field  33
TSNR2_GPBDARK_R       float64       label for field  34
TSNR2_ELG_R           float64       label for field  35
TSNR2_GPBBRIGHT_R     float64       label for field  36
TSNR2_LYA_R           float64       label for field  37
TSNR2_BGS_R           float64       label for field  38
TSNR2_GPBBACKUP_R     float64       label for field  39
TSNR2_QSO_R           float64       label for field  40
TSNR2_LRG_R           float64       label for field  41
SUM_RAW_COUNT_Z       float64       label for field  42
MEDIAN_RAW_COUNT_Z    float64       label for field  43
MEDIAN_RAW_SNR_Z      float64       label for field  44
SUM_FFLAT_COUNT_Z     float64       label for field  45
MEDIAN_FFLAT_COUNT_Z  float64       label for field  46
MEDIAN_FFLAT_SNR_Z    float64       label for field  47
SUM_SKYSUB_COUNT_Z    float64       label for field  48
MEDIAN_SKYSUB_COUNT_Z float64       label for field  49
MEDIAN_SKYSUB_SNR_Z   float64       label for field  50
SUM_CALIB_COUNT_Z     float64       label for field  51
MEDIAN_CALIB_COUNT_Z  float64       label for field  52
MEDIAN_CALIB_SNR_Z    float64       label for field  53
TSNR2_GPBDARK_Z       float64       label for field  54
TSNR2_ELG_Z           float64       label for field  55
TSNR2_GPBBRIGHT_Z     float64       label for field  56
TSNR2_LYA_Z           float64       label for field  57
TSNR2_BGS_Z           float64       label for field  58
TSNR2_GPBBACKUP_Z     float64       label for field  59
TSNR2_QSO_Z           float64       label for field  60
TSNR2_LRG_Z           float64       label for field  61
===================== ======= ===== ===================

HDU03
-----

EXTNAME = B_WAVELENGTH

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =====================
    KEY    Example Value Type Comment
    ====== ============= ==== =====================
    NAXIS1 2751          int  length of data axis 1
    BUNIT  Angstrom      str
    ====== ============= ==== =====================

Data: FITS image [float64, 2751]

HDU04
-----

EXTNAME = B_FLUX

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============================ ==== =====================
    KEY    Example Value                Type Comment
    ====== ============================ ==== =====================
    NAXIS1 2751                         int  length of data axis 1
    NAXIS2 500                          int  length of data axis 2
    BUNIT  10**-17 erg/(s cm2 Angstrom) str
    ====== ============================ ==== =====================

Data: FITS image [float32, 2751x500]

HDU05
-----

EXTNAME = B_IVAR

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ================================= ==== =====================
    KEY    Example Value                     Type Comment
    ====== ================================= ==== =====================
    NAXIS1 2751                              int  length of data axis 1
    NAXIS2 500                               int  length of data axis 2
    BUNIT  10**+34 (s2 cm4 Angstrom2) / erg2 str
    ====== ================================= ==== =====================

Data: FITS image [float32, 2751x500]

HDU06
-----

EXTNAME = B_MASK

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== ==========================================
    KEY    Example Value Type Comment
    ====== ============= ==== ==========================================
    NAXIS1 8             int  width of table in bytes
    NAXIS2 500           int  number of rows in table
    BZERO  2147483648    int  offset data range to that of unsigned long
    BSCALE 1             int  default scaling factor
    ====== ============= ==== ==========================================

Data: FITS image [int32 (compressed), 2751x500]

HDU07
-----

EXTNAME = B_RESOLUTION

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =====================
    KEY    Example Value Type Comment
    ====== ============= ==== =====================
    NAXIS1 2751          int  length of data axis 1
    NAXIS2 11            int  length of data axis 2
    NAXIS3 500           int  length of data axis 3
    ====== ============= ==== =====================

Data: FITS image [float32, 2751x11x500]

HDU08
-----

EXTNAME = R_WAVELENGTH

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =====================
    KEY    Example Value Type Comment
    ====== ============= ==== =====================
    NAXIS1 2326          int  length of data axis 1
    BUNIT  Angstrom      str
    ====== ============= ==== =====================

Data: FITS image [float64, 2326]

HDU09
-----

EXTNAME = R_FLUX

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============================ ==== =====================
    KEY    Example Value                Type Comment
    ====== ============================ ==== =====================
    NAXIS1 2326                         int  length of data axis 1
    NAXIS2 500                          int  length of data axis 2
    BUNIT  10**-17 erg/(s cm2 Angstrom) str
    ====== ============================ ==== =====================

Data: FITS image [float32, 2326x500]

HDU10
-----

EXTNAME = R_IVAR

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ================================= ==== =====================
    KEY    Example Value                     Type Comment
    ====== ================================= ==== =====================
    NAXIS1 2326                              int  length of data axis 1
    NAXIS2 500                               int  length of data axis 2
    BUNIT  10**+34 (s2 cm4 Angstrom2) / erg2 str
    ====== ================================= ==== =====================

Data: FITS image [float32, 2326x500]

HDU11
-----

EXTNAME = R_MASK

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== ==========================================
    KEY    Example Value Type Comment
    ====== ============= ==== ==========================================
    NAXIS1 8             int  width of table in bytes
    NAXIS2 500           int  number of rows in table
    BZERO  2147483648    int  offset data range to that of unsigned long
    BSCALE 1             int  default scaling factor
    ====== ============= ==== ==========================================

Data: FITS image [int32 (compressed), 2326x500]

HDU12
-----

EXTNAME = R_RESOLUTION

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =====================
    KEY    Example Value Type Comment
    ====== ============= ==== =====================
    NAXIS1 2326          int  length of data axis 1
    NAXIS2 11            int  length of data axis 2
    NAXIS3 500           int  length of data axis 3
    ====== ============= ==== =====================

Data: FITS image [float32, 2326x11x500]

HDU13
-----

EXTNAME = Z_WAVELENGTH

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =====================
    KEY    Example Value Type Comment
    ====== ============= ==== =====================
    NAXIS1 2881          int  length of data axis 1
    BUNIT  Angstrom      str
    ====== ============= ==== =====================

Data: FITS image [float64, 2881]

HDU14
-----

EXTNAME = Z_FLUX

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============================ ==== =====================
    KEY    Example Value                Type Comment
    ====== ============================ ==== =====================
    NAXIS1 2881                         int  length of data axis 1
    NAXIS2 500                          int  length of data axis 2
    BUNIT  10**-17 erg/(s cm2 Angstrom) str
    ====== ============================ ==== =====================

Data: FITS image [float32, 2881x500]

HDU15
-----

EXTNAME = Z_IVAR

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ================================= ==== =====================
    KEY    Example Value                     Type Comment
    ====== ================================= ==== =====================
    NAXIS1 2881                              int  length of data axis 1
    NAXIS2 500                               int  length of data axis 2
    BUNIT  10**+34 (s2 cm4 Angstrom2) / erg2 str
    ====== ================================= ==== =====================

Data: FITS image [float32, 2881x500]

HDU16
-----

EXTNAME = Z_MASK

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== ==========================================
    KEY    Example Value Type Comment
    ====== ============= ==== ==========================================
    NAXIS1 8             int  width of table in bytes
    NAXIS2 500           int  number of rows in table
    BZERO  2147483648    int  offset data range to that of unsigned long
    BSCALE 1             int  default scaling factor
    ====== ============= ==== ==========================================

Data: FITS image [int32 (compressed), 2881x500]

HDU17
-----

EXTNAME = Z_RESOLUTION

*Summarize the contents of this HDU.*

Required Header Keywords
~~~~~~~~~~~~~~~~~~~~~~~~

.. collapse:: Required Header Keywords Table

    .. rst-class:: keywords

    ====== ============= ==== =====================
    KEY    Example Value Type Comment
    ====== ============= ==== =====================
    NAXIS1 2881          int  length of data axis 1
    NAXIS2 11            int  length of data axis 2
    NAXIS3 500           int  length of data axis 3
    ====== ============= ==== =====================

Data: FITS image [float32, 2881x11x500]

Notes and Examples
==================

*Add notes and examples here.  You can also create links to example files.*


text:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure;

namespace Ordering.Infrastructure.EntityConfigurations
{
    class CardTypeEntityTypeConfiguration
        : IEntityTypeConfiguration<CardType>
    {
        public void Configure(EntityTypeBuilder<CardType> cardTypesConfiguration)
        {
            cardTypesConfiguration.ToTable("cardtypes", OrderingContext.DEFAULT_SCHEMA);

            cardTypesConfiguration.HasKey(ct => ct.Id);

            cardTypesConfiguration.Property(ct => ct.Id)
                .HasDefaultValue(1)
                .ValueGeneratedNever()
                .IsRequired();

            cardTypesConfiguration.Property(ct => ct.Name)
                .HasMaxLength(200)
                .IsRequired();
        }
    }
}