text:
package transform

import (
	"image"
	"math"

	"github.com/anthonynsimon/bild/clone"
	"github.com/anthonynsimon/bild/parallel"
)

// ShearH applies a shear linear transformation along the horizontal axis,
// the parameter angle is the shear angle to be applied.
// The transformation will be applied with the center of the image as the pivot.
func ShearH(img image.Image, angle float64) *image.RGBA {
	src := clone.AsRGBA(img)
	srcW, srcH := src.Bounds().Dx(), src.Bounds().Dy()

	// Supersample, currently hard set to 2x
	srcW, srcH = srcW*2, srcH*2
	src = Resize(src, srcW, srcH, NearestNeighbor)

	// Calculate shear factor
	kx := math.Tan(angle * (math.Pi / 180))

	dstW, dstH := srcW+int(float64(srcH)*math.Abs(kx)), srcH
	dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))

	pivotX := float64(dstW) / 2
	pivotY := float64(dstH) / 2

	// Calculate offset since we are resizing the bounds to
	// fit the sheared image.
	dx := (dstW - srcW) / 2
	dy := (dstH - srcH) / 2

	parallel.Line(dstH, func(start, end int) {
		for y := start; y < end; y++ {
			for x := 0; x < dstW; x++ {
				// Move positions to revolve around pivot
				ix := x - int(pivotX) - dx
				iy := y - int(pivotY) - dy

				// Apply linear transformation
				ix = ix + int(float64(iy)*kx)

				// Move positions back to image coordinates
				ix += int(pivotX)
				iy += int(pivotY)

				if ix < 0 || ix >= srcW || iy < 0 || iy >= srcH {
					continue
				}

				srcPos := iy*src.Stride + ix*4
				dstPos := y*dst.Stride + x*4

				dst.Pix[dstPos+0] = src.Pix[srcPos+0]
				dst.Pix[dstPos+1] = src.Pix[srcPos+1]
				dst.Pix[dstPos+2] = src.Pix[srcPos+2]
				dst.Pix[dstPos+3] = src.Pix[srcPos+3]
			}
		}
	})

	// Downsample to original bounds as part of the Supersampling
	dst = Resize(dst, dstW/2, dstH/2, Linear)

	return dst
}

// ShearV applies a shear linear transformation along the vertical axis,
// the parameter angle is the shear angle to be applied.
// The transformation will be applied with the center of the image as the pivot.
func ShearV(img image.Image, angle float64) *image.RGBA {
	src := clone.AsRGBA(img)
	srcW, srcH := src.Bounds().Dx(), src.Bounds().Dy()

	// Supersample, currently hard set to 2x
	srcW, srcH = srcW*2, srcH*2
	src = Resize(src, srcW, srcH, NearestNeighbor)

	// Calculate shear factor
	ky := math.Tan(angle * (math.Pi / 180))

	dstW, dstH := srcW, srcH+int(float64(srcW)*math.Abs(ky))
	dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))

	pivotX := float64(dstW) / 2
	pivotY := float64(dstH) / 2

	// Calculate offset since we are resizing the bounds to
	// fit the sheared image.
	dx := (dstW - srcW) / 2
	dy := (dstH - srcH) / 2

	parallel.Line(dstH, func(start, end int) {
		for y := start; y < end; y++ {
			for x := 0; x < dstW; x++ {
				// Move positions to revolve around pivot
				ix := x - int(pivotX) - dx
				iy := y - int(pivotY) - dy

				// Apply linear transformation
				iy = iy + int(float64(ix)*ky)

				// Move positions back to image coordinates
				ix += int(pivotX)
				iy += int(pivotY)

				if ix < 0 || ix >= srcW || iy < 0 || iy >= srcH {
					continue
				}

				srcPos := iy*src.Stride + ix*4
				dstPos := y*dst.Stride + x*4

				dst.Pix[dstPos+0] = src.Pix[srcPos+0]
				dst.Pix[dstPos+1] = src.Pix[srcPos+1]
				dst.Pix[dstPos+2] = src.Pix[srcPos+2]
				dst.Pix[dstPos+3] = src.Pix[srcPos+3]
			}
		}
	})

	// Downsample to original bounds as part of the Supersampling
	dst = Resize(dst, dstW/2, dstH/2, Linear)

	return dst
}


text:
// Load jquery, less and floatz in correct order
$LAB.script("../src/scripts/jquery-1.11.3.min.js")
	.script("../src/scripts/ua-parser-0.7.9.min.js").wait()
	.script("../src/scripts/floatz.js").wait()
	.script("../src/scripts/floatz.scroller.js")
	.script("../src/scripts/floatz.mobile.js")
	.script("../src/scripts/floatz.skiplink.js")
	.script("scripts/custom.js")
	.wait(function () {
		$(document).ready(function () {
			floatz.start({
				debug: true,
				logLevel: floatz.LOGLEVEL.DEBUG,
				modules: ["floatz.mobile",
					"floatz.scroller"],
				onStarted: function () {
					handleStarted();
				}
			});
		});
	});

function handleStarted() {

	floatz.scroller.context
		.scroll(handleScroll)
		.scrollIn("#section1", handleScrollInSection)
		.scrollOut("#section1", handleScrollOutSection)
		.scrollIn("#section2", handleScrollInSection)
		.scrollOut("#section2", handleScrollOutSection)
/*		.scrollIn("#section3", handleScrollInSection)
		.scrollOut("#section3", handleScrollOutSection)
		.scrollIn("#section4", handleScrollInSection)
		.scrollOut("#section4", handleScrollOutSection)*/
		.scrollIn("#section5", handleScrollInSection)
		.scrollOut("#section5", handleScrollOutSection)
		.scrollIn("#section3", handleScrollInSection, handleScrollInBreakPoint)
		.scrollIn("#section4", handleScrollInSection, handleScrollInBreakPoint)
	;
}

function handleScroll(scrollInfo) {
/*	var msg =
		"Scroll position: " + scrollInfo.scrollTop + "/" + scrollInfo.scrollLeft +
		", Direction: " + (scrollInfo.isForward() ? "FORWARD" : "BACKWARD" ) +
		", Orientation: " + ( scrollInfo.isHorizontal() ? "HORIZONTAL" : "VERTICAL") +
		", Container: " + (scrollInfo.container.nodeName === undefined ? "Window" : scrollInfo.container.nodeName );

	msg += ", Visible sections: ";
	for(var i=0; i < scrollInfo.visibleSections.length; i++) {
		msg += scrollInfo.visibleSections[i].id;
		msg += " (" + (scrollInfo.isVertical() ? scrollInfo.visibleSections[i].visibility.vertical : scrollInfo.visibleSections[i].visibility.horizontal) + ") ";
	}

	console.log(msg); */
}

function handleScrollInSection(scrollInfo, section) {
	console.log("Scrolled into " + section.id);
}

function handleScrollOutSection(scrollInfo, section) {
	console.log("Scrolled out of " + section.id);
}

function handleScrollInBreakPoint(scrollInfo, section) {

	// Percentage value can´t be exact because of jumps due to fast scrolling
	if(section.visibility.vertical >= 15 && section.visibility.vertical <= 30) {
		var article = $("article", section.jQuery);
		console.log("Section " + section.id + " visible at " + section.visibility.vertical+ "%");
		if(article.is(":hidden")) {
			article.fadeIn();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
mlab-plugin-sample
==================

firebreath depends on cmake, git, and a standard development environment with
gcc/g++/make and development headers installed.

After initial checkout run:

    git submodule update --init --recursive

Then generate a local build directory:

    ./firebreath/prepmake.sh MLabPlugin build

The build is separate from the sources in MLabPlugin, and you should re-run
prepmake.sh after changes or updates to source in MLabPlugin.

    cd build
    make

The initial build will take a while b/c all the dependencies are built.  Future
iteration on changes to MLabPlugin will be much faster. And, cmake helps make
that easy.

If you receive a build error like:

    project dir: /root/mlab-plugin-sample/MLabPlugin
    Single project: /root/mlab-plugin-sample/MLabPlugin
    CMake Error at src/libs/curl/CMakeLists.txt:19 (include):
      include could not find load file:

        FindCurl

Then this is probably b/c your version of cmake-data names the module FindCURL
instead of the referenced FindCurl.  A better work-around is unknown, but
manually updating the src/libs/curl/CMakeLists.txt with the correct name
allows the prep to finish.

Windows
=======

For dependencies:
http://www.firebreath.org/display/documentation/Building+with+Visual+Studio+Express

And afterward:
http://www.firebreath.org/display/documentation/Building+on+Windows

Mac OS X
========

http://www.firebreath.org/display/documentation/Building+on+Mac+OS+X


text:
package org.apache.hadoop.hdfs.protocol;

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

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.server.namenode.FSDirectory;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeLayoutVersion;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.NameNodeLayoutVersion;

/************************************
 * Some handy constants
 *
 ************************************/
@InterfaceAudience.Private
public class HdfsConstants {
  /* Hidden constructor */
  protected HdfsConstants() {
  }

  /**
   * HDFS Protocol Names:
   */
  public static final String CLIENT_NAMENODE_PROTOCOL_NAME =
      "org.apache.hadoop.hdfs.protocol.ClientProtocol";
  public static final String CLIENT_DATANODE_PROTOCOL_NAME =
      "org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol";

  public static final int MIN_BLOCKS_FOR_WRITE = 5;

  // Long that indicates "leave current quota unchanged"
  public static final long QUOTA_DONT_SET = Long.MAX_VALUE;
  public static final long QUOTA_RESET = -1L;

  //
  // Timeouts, constants
  //
  public static final long LEASE_SOFTLIMIT_PERIOD = 60 * 1000;
  public static final long LEASE_HARDLIMIT_PERIOD = 60 * LEASE_SOFTLIMIT_PERIOD;
  public static final long LEASE_RECOVER_PERIOD = 10 * 1000; // in ms

  // We need to limit the length and depth of a path in the filesystem.
  // HADOOP-438
  // Currently we set the maximum length to 8k characters and the maximum depth
  // to 1k.
  public static final int MAX_PATH_LENGTH = 8000;
  public static final int MAX_PATH_DEPTH = 1000;

  // TODO should be conf injected?
  public static final int DEFAULT_DATA_SOCKET_SIZE = 128 * 1024;
  public static final int IO_FILE_BUFFER_SIZE = new HdfsConfiguration().getInt(
      DFSConfigKeys.IO_FILE_BUFFER_SIZE_KEY,
      DFSConfigKeys.IO_FILE_BUFFER_SIZE_DEFAULT);
  // Used for writing header etc.
  public static final int SMALL_BUFFER_SIZE = Math.min(IO_FILE_BUFFER_SIZE / 2,
      512);

  public static final int BYTES_IN_INTEGER = Integer.SIZE / Byte.SIZE;

  // SafeMode actions
  public static enum SafeModeAction {
    SAFEMODE_LEAVE, SAFEMODE_ENTER, SAFEMODE_GET;
  }

  public static enum RollingUpgradeAction {
    QUERY, PREPARE, FINALIZE;

    private static final Map<String, RollingUpgradeAction> MAP
        = new HashMap<String, RollingUpgradeAction>();
    static {
      MAP.put("", QUERY);
      for(RollingUpgradeAction a : values()) {
        MAP.put(a.name(), a);
      }
    }

    /** Covert the given String to a RollingUpgradeAction. */
    public static RollingUpgradeAction fromString(String s) {
      return MAP.get(s.toUpperCase());
    }
  }

  // type of the datanode report
  public static enum DatanodeReportType {
    ALL, LIVE, DEAD
  }

  // An invalid transaction ID that will never be seen in a real namesystem.
  public static final long INVALID_TXID = -12345;

  // Number of generation stamps reserved for legacy blocks.
  public static final long RESERVED_GENERATION_STAMPS_V1 =
      1024L * 1024 * 1024 * 1024;

  /**
   * URI Scheme for hdfs://namenode/ URIs.
   */
  public static final String HDFS_URI_SCHEME = "hdfs";

  /**
   * A prefix put before the namenode URI inside the "service" field
   * of a delgation token, indicating that the URI is a logical (HA)
   * URI.
   */
  public static final String HA_DT_SERVICE_PREFIX = "ha-hdfs:";

  /**
   * Path components that are reserved in HDFS.
   * <p>
   * .reserved is only reserved under root ("/").
   */
  public static final String[] RESERVED_PATH_COMPONENTS = new String[] {
    HdfsConstants.DOT_SNAPSHOT_DIR,
    FSDirectory.DOT_RESERVED_STRING
  };

  /**
   * Current layout version for NameNode.
   * Please see {@link NameNodeLayoutVersion.Feature} on adding new layout version.
   */
  public static final int NAMENODE_LAYOUT_VERSION
      = NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION;

  /**
   * Current layout version for DataNode.
   * Please see {@link DataNodeLayoutVersion.Feature} on adding new layout version.
   */
  public static final int DATANODE_LAYOUT_VERSION
      = DataNodeLayoutVersion.CURRENT_LAYOUT_VERSION;

  /**
   * A special path component contained in the path for a snapshot file/dir
   */
  public static final String DOT_SNAPSHOT_DIR = ".snapshot";

  public static final byte[] DOT_SNAPSHOT_DIR_BYTES
      = DFSUtil.string2Bytes(DOT_SNAPSHOT_DIR);

  public static final String SEPARATOR_DOT_SNAPSHOT_DIR
      = Path.SEPARATOR + DOT_SNAPSHOT_DIR;
}


text:
<!DOCTYPE html>

  <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,400italic' rel='stylesheet' type='text/css'>

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

  <link rel="stylesheet" type="text/css" href="../theme/pygments/github.min.css">
  <link rel="stylesheet" type="text/css" href="../theme/font-awesome/css/font-awesome.min.css">

    <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/images/favicon.ico" type="image/x-icon">

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="True" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="robots" content="" />

    <meta name="author" content="Rishabh Chakrabarti" />
    <meta name="description" content="Rishabh Chakrabarti's Notes and Highlights" />
<meta property="og:site_name" content="Bassdeveloper's Blog"/>
<meta property="og:type" content="blog"/>
<meta property="og:title" content="Bassdeveloper's Blog"/>
<meta property="og:description" content="Rishabh Chakrabarti's Notes and Highlights"/>
<meta property="og:locale" content="en_US"/>
<meta property="og:url" content=".."/>
<meta property="og:image" content="/images/RC.jpg">

  <title>Bassdeveloper's Blog –     Category Learning
</title>

Rishabh Chakrabarti

Learning bout Data

Learning

Data-Science

Business

12 Factor App

          Posted on Wed 25 January 2017 in Learning

          •     Tagged with

              App-dev,              12factor

Learnt about 12-Factor App from NPM module information. Liked it. Decided to simply move forward with my version/summary.

          Continue reading

NLP using Neural Networks

          Posted on Tue 24 January 2017 in Learning

          •     Tagged with

              Neural Networks,              Speech recognition

Dive into Neural Networks to build End-to-End Systems

          Continue reading

Watson Knowledge Studio

          Posted on Tue 24 January 2017 in Learning

          •     Tagged with

              Watson,              Watson Knowledge,              IBM

Watson Knowledge Studio summary from the documentation.

          Continue reading

           Older Posts

          Newer Posts

© Rishabh Chakrabarti

    Powered by Pelican - Flex theme by Alexandre Vicenzi


text:
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use alloc::arc::Arc;

use clone::Clone;
use kinds::Send;
use ty::Unsafe;
use unstable::mutex::NativeMutex;

struct ExData<T> {
    lock: NativeMutex,
    failed: bool,
    data: T,
}

/**
 * An arc over mutable data that is protected by a lock. For library use only.
 *
 * # Safety note
 *
 * This uses a pthread mutex, not one that's aware of the userspace scheduler.
 * The user of an Exclusive must be careful not to invoke any functions that may
 * reschedule the task while holding the lock, or deadlock may result. If you
 * need to block or deschedule while accessing shared state, use extra::sync::RWArc.
 */
pub struct Exclusive<T> {
    x: Arc<Unsafe<ExData<T>>>
}

impl<T:Send> Clone for Exclusive<T> {
    // Duplicate an Exclusive Arc, as std::arc::clone.
    fn clone(&self) -> Exclusive<T> {
        Exclusive { x: self.x.clone() }
    }
}

impl<T:Send> Exclusive<T> {
    pub fn new(user_data: T) -> Exclusive<T> {
        let data = ExData {
            lock: unsafe {NativeMutex::new()},
            failed: false,
            data: user_data
        };
        Exclusive {
            x: Arc::new(Unsafe::new(data))
        }
    }

    // Exactly like sync::MutexArc.access(). Same reason for being
    // unsafe.
    //
    // Currently, scheduling operations (i.e., descheduling, receiving on a pipe,
    // accessing the provided condition variable) are prohibited while inside
    // the Exclusive. Supporting that is a work in progress.
    #[inline]
    pub unsafe fn with<U>(&self, f: |x: &mut T| -> U) -> U {
        let rec = self.x.get();
        let _l = (*rec).lock.lock();
        if (*rec).failed {
            fail!("Poisoned Exclusive::new - another task failed inside!");
        }
        (*rec).failed = true;
        let result = f(&mut (*rec).data);
        (*rec).failed = false;
        result
    }

    #[inline]
    pub unsafe fn with_imm<U>(&self, f: |x: &T| -> U) -> U {
        self.with(|x| f(x))
    }

    #[inline]
    pub unsafe fn hold_and_signal(&self, f: |x: &mut T|) {
        let rec = self.x.get();
        let guard = (*rec).lock.lock();
        if (*rec).failed {
            fail!("Poisoned Exclusive::new - another task failed inside!");
        }
        (*rec).failed = true;
        f(&mut (*rec).data);
        (*rec).failed = false;
        guard.signal();
    }

    #[inline]
    pub unsafe fn hold_and_wait(&self, f: |x: &T| -> bool) {
        let rec = self.x.get();
        let l = (*rec).lock.lock();
        if (*rec).failed {
            fail!("Poisoned Exclusive::new - another task failed inside!");
        }
        (*rec).failed = true;
        let result = f(&(*rec).data);
        (*rec).failed = false;
        if result {
            l.wait();
        }
    }
}

#[cfg(test)]
mod tests {
    use option::*;
    use prelude::*;
    use super::Exclusive;
    use task;

    #[test]
    fn exclusive_new_arc() {
        unsafe {
            let mut futures = Vec::new();

            let num_tasks = 10;
            let count = 10;

            let total = Exclusive::new(box 0);

            for _ in range(0u, num_tasks) {
                let total = total.clone();
                let (tx, rx) = channel();
                futures.push(rx);

                task::spawn(proc() {
                    for _ in range(0u, count) {
                        total.with(|count| **count += 1);
                    }
                    tx.send(());
                });
            };

            for f in futures.mut_iter() { f.recv() }

            total.with(|total| assert!(**total == num_tasks * count));
        }
    }

    #[test] #[should_fail]
    fn exclusive_new_poison() {
        unsafe {
            // Tests that if one task fails inside of an Exclusive::new, subsequent
            // accesses will also fail.
            let x = Exclusive::new(1);
            let x2 = x.clone();
            let _ = task::try(proc() {
                x2.with(|one| assert_eq!(*one, 2))
            });
            x.with(|one| assert_eq!(*one, 1));
        }
    }
}


text:
import hashlib

from django.contrib.auth.hashers import BasePasswordHasher, mask_hash
from django.utils.crypto import constant_time_compare
from django.utils.datastructures import SortedDict
from django.utils.encoding import smart_str
from django.utils.translation import ugettext as _

class SHA256PasswordHasher(BasePasswordHasher):
    """The SHA256 password hashing algorithm."""
    algorithm = "sha256"

    def encode(self, password, salt):
        assert password
        assert salt and '$' not in salt
        hash = hashlib.sha256(
            smart_str(salt) + smart_str(password)).hexdigest()
        return "%s$%s$%s" % (self.algorithm, salt, hash)

    def verify(self, password, encoded):
        algorithm, salt, hash = encoded.split('$', 2)
        assert algorithm == self.algorithm
        encoded_2 = self.encode(smart_str(password), smart_str(salt))
        return constant_time_compare(encoded, encoded_2)

    def safe_summary(self, encoded):
        algorithm, salt, hash = encoded.split('$', 2)
        assert algorithm == self.algorithm
        return SortedDict([
            (_('algorithm'), algorithm),
            (_('salt'), mask_hash(salt, show=2)),
            (_('hash'), mask_hash(hash)),
        ])


text:
namespace djinni {

// Throws an exception for an unimplemented method call.
[[noreturn]] void throwUnimplemented(const char * ctx, NSString * msg);

// Helper function for exception translation. Do not call directly!
[[noreturn]] void throwNSExceptionFromCurrent(const char * ctx);

} // namespace djinni

#define DJINNI_UNIMPLEMENTED(msg) \
    ::djinni::throwUnimplemented(__PRETTY_FUNCTION__, msg);

#define DJINNI_TRANSLATE_EXCEPTIONS() \
    catch (const std::exception & e) { \
        ::djinni::throwNSExceptionFromCurrent(__PRETTY_FUNCTION__); \
    }


text:
/*
 The backbone.js views for the item type : Document .
includes:

DiscoveryListDocumentView
DiscoveryCompactListDocumentView
DiscoveryThumbDocumentView
DiscoveryMapDocumentView
DiscoveryTimelineDocumentView
HomeCarouselDocumentView
HomePreviewPopupDocumentView
ItemPageDocumentView
LightboxDocumentView
 */

var DiscoveryListDocumentView = DiscoveryListItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;

	},

});

var DiscoveryCompactListDocumentView = DiscoveryCompactListItemView.extend({

	render : function() {
		$(this.el).html(this.res);
		return this;

	},

});
var DiscoveryThumbDocumentView = DiscoveryThumbItemView.extend({

	render : function() {
		$(this.el).html(this.res);
		return this;

	}
});
var DiscoveryMapDocumentView = DiscoveryMapItemView.extend({

	render : function() {
		$(this.el).html(this.res);
		return this;

	}
});

var DiscoveryTimelineDocumentView = DiscoveryTimelineItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;

	}
});

var HomeCarouselDocumentView = HomeCarouselItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;

	}
});

var HomePreviewPopupDocumentView = HomePreviewPopupItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;

	}
});

var PageDocumentView = PageItemView.extend({
	render : function() {
		uri = 'http://www.documentcloud.org/documents/' + this.model.get("uri");
		docPreview = $("");
		docPreview.attr("src", uri);
		docPreview.width("100%");
		docPreview.height("100%");

		previewArea = $(this.res).find(".page-preview-area");
		previewArea.width("50%");
		$(this.res).find(".page-preview").html(docPreview);

		$(this.el).html(this.res);
		return this;
	}
});

var LightboxDocumentView = LightboxItemView.extend({
	render : function() {
		uri = 'http://www.documentcloud.org/documents/' + this.model.get("uri");
		docPreview = $("");
		docPreview.attr("src", uri);
		docPreview.width("100%");
		docPreview.height("100%");

		this.res.find(".lightbox-preview").html(docPreview);

		$(this.el).html(this.res);
		return this;
	}
});


text:
* 2016-02-02 v2.0.0 ~80% perf improvement on repo lists with use of parallel. [semver-major] API change to all `gitHub` methods.
* 2015-11-14 v1.1.1 Fix: Files with zero lines should return 100 instead of NaN for coverage percent
* 2015-11-09 v1.1.0 Feature: add method `sortCoverage`
* 2015-10-23 v1.0.1 Fix: remove duplication of GitHub repos from owners and orgs list in `getGitHubRepos`
* 2015-10-22 v1.0.0 initial release


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

#ifndef FIFF_CONSTANTS_H
#define FIFF_CONSTANTS_H

//*************************************************************************************************************
//=============================================================================================================
// DEFINE NAMESPACE FIFFLIB
//=============================================================================================================

namespace FIFFLIB
{

//*************************************************************************************************************
//=============================================================================================================
// FIFF constants
//=============================================================================================================

#define  FIFFC_FAIL -1
#define  FIFFC_OK 0

#define  FIFFV_TRUE  1
#define  FIFFV_FALSE 0

/* Compatibility definitions */

#define  FIFF_FAIL -1
#define  FIFF_OK    0

#define FIFFV_NEXT_SEQ   0
#define FIFFV_NEXT_NONE -1

#define FIFFC_TAG_INFO_SIZE (sizeof(fiffTag) - sizeof(fiff_data_t *))
#define FIFFC_DATA_OFFSET FIFFC_TAG_INFO_SIZE
#define FIFFM_TAG_INFO(x) &((x)->kind)

#define FIFFV_MAGN_CH    1
#define FIFFV_EL_CH      2
#define FIFFV_MCG_CH     201
#define FIFFV_STIM_CH    3

#define FIFFV_EOG_CH   202
#define FIFFV_EMG_CH   302
#define FIFFV_ECG_CH   402
#define FIFFV_MISC_CH  502
#define FIFFV_RESP_CH  602		     /* Respiration monitoring */
/*
* Quaternion channels for head position monitoring
*/
#define FIFFV_QUAT_0   700                 /* Quaternion parameter q0; obsolete for unit quaternion */
#define FIFFV_QUAT_1   701                 /* Quaternion parameter q1; rotation */
#define FIFFV_QUAT_2   702                 /* Quaternion parameter q2; rotation */
#define FIFFV_QUAT_3   703                 /* Quaternion parameter q3; rotation */
#define FIFFV_QUAT_4   704                 /* Quaternion parameter q4; translation */
#define FIFFV_QUAT_5   705                 /* Quaternion parameter q5; translation */
#define FIFFV_QUAT_6   706                 /* Quaternion parameter q6; translation */
#define FIFFV_HPI_G    707                 /* Goodness-of-fit in continuous hpi */
#define FIFFV_HPI_ERR  708                 /* Estimation error in continuous hpi */
#define FIFFV_HPI_MOV  709                 /* Estimated head movement speed in continuous hpi */

#define FIFFM_QUAT_CH(X) ((X >= FIFFV_QUAT_0) && (X <= FIFFV_HPI_MOV))   /* Check for a quaternion channel */

#define FIFFV_DIPOLE_WAVE_CH   1000	   /* Dipole time curve */
#define FIFFV_GOODNESS_FIT_CH  1001	   /* Goodness of fit */

#define FIFFM_CHPOS(x) &((x)->chpos)

/*
* Units of measurement
*/

#define FIFF_UNIT_NONE -1
/*
* 1. SI base units
*/
#define FIFF_UNIT_M   1
#define FIFF_UNIT_KG  2
#define FIFF_UNIT_SEC 3
#define FIFF_UNIT_A   4
#define FIFF_UNIT_K   5
#define FIFF_UNIT_MOL 6
/*
* 2. SI Supplementary units
*/
#define FIFF_UNIT_RAD 7
#define FIFF_UNIT_SR  8
/*
* 1. SI base candela
*/
#define FIFF_UNIT_CD  9
/*
* 3. SI derived units
*/
#define FIFF_UNIT_HZ  101
#define FIFF_UNIT_N   102
#define FIFF_UNIT_PA  103
#define FIFF_UNIT_J   104
#define FIFF_UNIT_W   105
#define FIFF_UNIT_C   106
#define FIFF_UNIT_V   107
#define FIFF_UNIT_F   108
#define FIFF_UNIT_OHM 109
#define FIFF_UNIT_MHO 110
#define FIFF_UNIT_WB  111
#define FIFF_UNIT_T   112
#define FIFF_UNIT_H   113
#define FIFF_UNIT_CEL 114
#define FIFF_UNIT_LM  115
#define FIFF_UNIT_LX  116
/*
* 4. Others we need
*/
#define FIFF_UNIT_T_M 201   /* T/m */
#define FIFF_UNIT_AM  202   /* Am  */
/*
* 5. Multipliers
*/
#define FIFF_UNITM_E   18
#define FIFF_UNITM_PET 15
#define FIFF_UNITM_T   12
#define FIFF_UNITM_MEG  6
#define FIFF_UNITM_K    3
#define FIFF_UNITM_H    2
#define FIFF_UNITM_DA   1
#define FIFF_UNITM_NONE 0
#define FIFF_UNITM_D   -1
#define FIFF_UNITM_C   -2
#define FIFF_UNITM_M   -3
#define FIFF_UNITM_MU  -6
#define FIFF_UNITM_N   -9
#define FIFF_UNITM_P  -12
#define FIFF_UNITM_F  -15
#define FIFF_UNITM_A  -18

/*
* Coil types
*/

/* \def FIFFV_COIL_NONE */

#define FIFFV_COIL_NONE                  0  /**< The location info contains no data */
#define FIFFV_COIL_EEG                   1  /**< EEG electrode position in r0 */
#define FIFFV_COIL_NM_122                2  /**< Neuromag 122 coils */
#define FIFFV_COIL_NM_24                 3  /**< Old 24 channel system in HUT */
#define FIFFV_COIL_NM_MCG_AXIAL          4  /**< The axial devices in the HUCS MCG system */
#define FIFFV_COIL_EEG_BIPOLAR           5  /**< Bipolar EEG lead */

#define FIFFV_COIL_DIPOLE              200  /**< Time-varying dipole definition
                         * The coil info contains dipole location (r0) and
                         * direction (ex) */
#define FIFFV_COIL_MCG_42             1000  /**< For testing the MCG software */

#define FIFFV_COIL_POINT_MAGNETOMETER 2000  /**< Simple point magnetometer */
#define FIFFV_COIL_AXIAL_GRAD_5CM     2001  /**< Generic axial gradiometer */

#define FIFFV_COIL_VV_PLANAR_W        3011  /**< VV prototype wirewound planar sensor */
#define FIFFV_COIL_VV_PLANAR_T1       3012  /**< Vectorview SQ20483N planar gradiometer */
#define FIFFV_COIL_VV_PLANAR_T2       3013  /**< Vectorview SQ20483N-A planar gradiometer */
#define FIFFV_COIL_VV_PLANAR_T3       3014  /**< Vectorview SQ20950N planar gradiometer */
#define FIFFV_COIL_VV_MAG_W           3021  /**< VV prototype wirewound magnetometer */
#define FIFFV_COIL_VV_MAG_T1          3022  /**< Vectorview SQ20483N magnetometer */
#define FIFFV_COIL_VV_MAG_T2          3023  /**< Vectorview SQ20483-A magnetometer */
#define FIFFV_COIL_VV_MAG_T3          3024  /**< Vectorview SQ20950N magnetometer */

#define FIFFV_COIL_MAGNES_MAG         4001  /**< Magnes WH magnetometer */
#define FIFFV_COIL_MAGNES_GRAD        4002  /**< Magnes WH gradiometer  */
#define FIFFV_COIL_CTF_GRAD           5001  /**< CTF axial gradiometer */

/*
 * BabySQUID sensors
 */
#define FIFFV_COIL_BABY_GRAD          7001  /**< BabySQUID gradiometers */
#define FIFFV_COIL_BABY_MAG           7002  /**< BabyMEG inner layer magnetometers */
#define FIFFV_COIL_BABY_REF_MAG       7003  /**< BabyMEG outer layer magnetometers */
#define FIFFV_COIL_BABY_REF_MAG2      7004  /**< BabyMEG reference magnetometer */

///*
// * BabyMEG sensors --- added by Limin ---
// */
//#define FIFFV_COIL_BABY_INLAYER_MAG   7002  /**< babyMEG inlayer magnetometer */
//#define FIFFV_COIL_BABY_OUTLAYER_MAG  7003  /**< babyMEG outlayer magnetometer */
//#define FIFFV_COIL_BABY_REF_MAG       7004

#define FIFFM_IS_VV_COIL(c) ((c)/1000 == 3)

#define FIFFV_POINT_CARDINAL 1
#define FIFFV_POINT_HPI      2
#define FIFFV_POINT_EEG      3
#define FIFFV_POINT_EXTRA    4

#define FIFFV_POINT_LPA      1
#define FIFFV_POINT_NASION   2
#define FIFFV_POINT_RPA      3
/*
* These are the cardinal points for MCG data
* Left and right are supposed to be located below the sternum point
*/
#define FIFFV_POINT_CHEST_LEFT      1
#define FIFFV_POINT_CHEST_STERNUM   2
#define FIFFV_POINT_CHEST_RIGHT     3

/** Coordinate transformation descriptor */

#define FIFFV_COORD_UNKNOWN     0
#define FIFFV_COORD_DEVICE      1
#define FIFFV_COORD_ISOTRAK     2
#define FIFFV_COORD_HPI         3
#define FIFFV_COORD_HEAD        4
#define FIFFV_COORD_MRI         5
#define FIFFV_COORD_MRI_SLICE   6
#define FIFFV_COORD_MRI_DISPLAY 7
#define FIFFV_COORD_XRAY        FIFF_COORD_MRI
#define FIFFV_COORD_XRAY_SLICE  FIFF_COORD_MRI_SLICE
#define FIFFV_COORD_CT          FIFF_COORD_MRI
#define FIFFV_COORD_CT_SLICE    FIFF_COORD_MRI_SLICE

#define FIFFV_COORD_DICOM_DEVICE     8
#define FIFFV_COORD_IMAGING_DEVICE   9

#define FIFFV_COORD_TORSO      100

#define FIFFV_MOVE         1
#define FIFFV_NO_MOVE      0
/*
* Artefact removal parameters
*/
#define FIFFV_ARTEF_MAX   100
#define FIFFV_ARTEF_NONE   -1
#define FIFFV_ARTEF_KEEP   0
#define FIFFV_ARTEF_JUMP   1
#define FIFFV_ARTEF_NOJUMP 2

/*
* The layered sphere model
*/

#define FIFFV_LAYER_BRAIN   1
#define FIFFV_LAYER_CSF     2
#define FIFFV_LAYER_SKULL   3
#define FIFFV_LAYER_HEAD    4

#define FIFFV_XFIT_MAP_SURF_SENSORS 0  /**< Xfit contours on the sensor array */
#define FIFFV_XFIT_MAP_SURF_HEAD    1  /**< Xfit contours on a head surface */
#define FIFFV_XFIT_MAP_SURF_SPHERE  2  /**< Xfit contours on a spherical surface */

//
// Blocks - Standard tags used in all blocks
//
#define FIFFB_MEAS               100
#define FIFFB_MEAS_INFO          101
#define FIFFB_RAW_DATA           102
#define FIFFB_PROCESSED_DATA     103
#define FIFFB_CONTINUOUS_DATA    112
#define FIFFB_EVOKED             104
#define FIFFB_ASPECT             105
#define FIFFB_SUBJECT            106
#define FIFFB_ISOTRAK            107
#define FIFFB_HPI_MEAS           108
#define FIFFB_HPI_RESULT         109
#define FIFFB_DACQ_PARS          117
#define FIFFB_REF                118
#define FIFFB_SMSH_RAW_DATA      119
#define FIFFB_SMSH_ASPECT        120
#define FIFFB_BEM                310  /**< A BEM description. */
#define FIFFB_BEM_SURF           311  /**< Describes one BEM surface. */
#define FIFFB_PROJ               313
#define FIFFB_PROJ_ITEM          314
#define FIFFB_MRI                200
#define FIFFB_MRI_SET            201
#define FIFFB_MRI_SLICE          202
#define FIFFB_PROCESSING_HISTORY 900
#define FIFFB_SSS_INFO           502
#define FIFFB_SSS_CAL_ADJUST     503
#define FIFFB_SSS_ST_INFO        504
#define FIFFB_SSS_BASES          505
//
// Of general interest
//
#define FIFF_FILE_ID         100
#define FIFF_DIR_POINTER     101
#define FIFF_BLOCK_ID        103
#define FIFF_BLOCK_START     104
#define FIFF_BLOCK_END       105
#define FIFF_FREE_LIST       106
#define FIFF_FREE_BLOCK      107
#define FIFF_NOP             108
#define FIFF_PARENT_FILE_ID  109
#define FIFF_PARENT_BLOCK_ID 110
#define FIFF_BLOCK_NAME      111
#define FIFF_BLOCK_VERSION   112
#define FIFF_CREATOR         113   /* Program that created the file (string)  */
#define FIFF_MODIFIER        114   /* Program that modified the file (string) */

#define FIFF_REF_ROLE        115
#define FIFF_REF_FILE_ID     116
#define FIFF_REF_FILE_NUM    117
#define FIFF_REF_FILE_NAME   118
/* reserverd                 119 */
#define FIFF_REF_BLOCK_ID    120
//
//  Megacq saves the parameters in these tags
//
#define FIFF_DACQ_PARS      150
#define FIFF_DACQ_STIM      151

#define FIFF_SFREQ       201
#define FIFF_NCHAN       200
#define FIFF_DATA_PACK   202
#define FIFF_CH_INFO     203
#define FIFF_MEAS_DATE   204
#define FIFF_SUBJECT     205
#define FIFF_COMMENT     206
#define FIFF_NAVE        207
#define FIFF_DIG_POINT   213
#define FIFF_HPI_NCOIL   216
#define FIFF_LOWPASS     219
#define FIFF_COORD_TRANS 222
#define FIFF_HIGHPASS    223
#define FIFF_NAME        233
#define FIFF_LINE_FREQ   235
#define FIFF_DESCRIPTION FIFF_COMMENT
    //
    // Pointers
    //
#define FIFFV_NEXT_SEQ    0
#define FIFFV_NEXT_NONE   -1
    //
    // Channel types
    //
#define FIFFV_MEG_CH       1
#define FIFFV_REF_MEG_CH 301
#define FIFFV_EEG_CH       2
#define FIFFV_MCG_CH     201
#define FIFFV_STIM_CH      3
#define FIFFV_EOG_CH     202
#define FIFFV_EMG_CH     302
#define FIFFV_ECG_CH     402
#define FIFFV_MISC_CH    502
#define FIFFV_RESP_CH    602   /**< Respiration monitoring*/
    //
    // Quaternion channels for head position monitoring
    //
#define FIFFV_QUAT_0   700     /**< Quaternion param q0 obsolete for unit quaternion*/
#define FIFFV_QUAT_1   701     /**< Quaternion param q1 rotation*/
#define FIFFV_QUAT_2   702     /**< Quaternion param q2 rotation*/
#define FIFFV_QUAT_3   703     /**< Quaternion param q3 rotation*/
#define FIFFV_QUAT_4   704     /**< Quaternion param q4 translation*/
#define FIFFV_QUAT_5   705     /**< Quaternion param q5 translation*/
#define FIFFV_QUAT_6   706     /**< Quaternion param q6 translation*/
#define FIFFV_HPI_G    707     /**< Goodness-of-fit in continuous hpi*/
#define FIFFV_HPI_ERR  708     /**< Estimation error in continuous hpi*/
#define FIFFV_HPI_MOV  709     /**< Estimated head movement speed in continuous hpi*/
    //
    // Coordinate frames
    //
#define FIFFV_COORD_UNKNOWN        0
#define FIFFV_COORD_DEVICE         1
#define FIFFV_COORD_ISOTRAK        2
#define FIFFV_COORD_HPI            3
#define FIFFV_COORD_HEAD           4
#define FIFFV_COORD_MRI            5
#define FIFFV_COORD_MRI_SLICE      6
#define FIFFV_COORD_MRI_DISPLAY    7
#define FIFFV_COORD_DICOM_DEVICE   8
#define FIFFV_COORD_IMAGING_DEVICE 9
    //
    // Needed for raw and evoked-response data
    //
#define FIFF_FIRST_SAMPLE   208
#define FIFF_LAST_SAMPLE    209
#define FIFF_ASPECT_KIND    210
#define FIFF_DATA_BUFFER    300      /**< Buffer containing measurement data*/
#define FIFF_DATA_SKIP      301      /**< Data skip in buffers*/
#define FIFF_EPOCH          302      /**< Buffer containing one epoch and channel*/
#define FIFF_DATA_SKIP_SAMP 303      /**< Data skip in samples*/

    //
    // Different aspects of data
    //
#define FIFFV_ASPECT_AVERAGE       100    /**< Normal average of epochs*/
#define FIFFV_ASPECT_STD_ERR       101    /**< Std. error of mean*/
#define FIFFV_ASPECT_SINGLE        102    /**< Single epoch cut out from the continuous data*/
#define FIFFV_ASPECT_SUBAVERAGE    103
#define FIFFV_ASPECT_ALTAVERAGE    104    /**< Alternating subaverage*/
#define FIFFV_ASPECT_SAMPLE        105    /**< A sample cut out by graph*/
#define FIFFV_ASPECT_POWER_DENSITY 106    /**< Power density spectrum*/
#define FIFFV_ASPECT_DIPOLE_WAVE   200    /**< Dipole amplitude curve*/

    //
    // Conductor models
    //
#define FIFF_BEM_SURF_ID        3101  /**< int    - surface number */
#define FIFF_BEM_SURF_NAME      3102  /**< string - surface name */
#define FIFF_BEM_SURF_NNODE     3103  /**< int    - # of nodes on a surface */
#define FIFF_BEM_SURF_NTRI      3104  /**< int    - # number of triangles on a surface */
#define FIFF_BEM_SURF_NODES     3105  /**< float* - surface nodes */
#define FIFF_BEM_SURF_TRIANGLES 3106  /**< int*   - surface triangles */
#define FIFF_BEM_SURF_NORMALS   3107  /**< float* - surface node normal unit vectors */
#define FIFF_BEM_COORD_FRAME    3112  /**< enum   - the coordinate frame of the mode */
#define FIFF_BEM_SIGMA          3113  /**< float  - conductivity of a compartment */

    //
    // BEM surface IDs
    //
#define FIFFV_BEM_SURF_ID_UNKNOWN    -1
#define FIFFV_BEM_SURF_ID_BRAIN      1
#define FIFFV_BEM_SURF_ID_SKULL      3
#define FIFFV_BEM_SURF_ID_HEAD       4

    //
    // More of those defined in MNE
    //
#define FIFFV_MNE_SURF_UNKNOWN       -1
#define FIFFV_MNE_SURF_LEFT_HEMI     101
#define FIFFV_MNE_SURF_RIGHT_HEMI    102
    //
    //   These relate to the Isotrak data
    //
#define FIFFV_POINT_CARDINAL 1
#define FIFFV_POINT_HPI      2
#define FIFFV_POINT_EEG      3
#define FIFFV_POINT_ECG      FIFFV_POINT_EEG
#define FIFFV_POINT_EXTRA    4

#define FIFFV_POINT_LPA 1
#define FIFFV_POINT_NASION 2
#define FIFFV_POINT_RPA 3
    //
    //   SSP
    //
#define FIFF_PROJ_ITEM_KIND         3411
#define FIFF_PROJ_ITEM_TIME         3412
#define FIFF_PROJ_ITEM_NVEC         3414
#define FIFF_PROJ_ITEM_VECTORS      3415
#define FIFF_PROJ_ITEM_CH_NAME_LIST 3417
    //
    //   MRIs
    //
#define FIFF_MRI_SOURCE_PATH       1101
#define FIFF_MRI_SOURCE_FORMAT     2002
#define FIFF_MRI_PIXEL_ENCODING    2003
#define FIFF_MRI_PIXEL_DATA_OFFSET 2004
#define FIFF_MRI_PIXEL_SCALE       2005
#define FIFF_MRI_PIXEL_DATA        2006
#define FIFF_MRI_WIDTH             2010
#define FIFF_MRI_WIDTH_M           2011
#define FIFF_MRI_HEIGHT            2012
#define FIFF_MRI_HEIGHT_M          2013
#define FIFF_MRI_DEPTH             2014
#define FIFF_MRI_DEPTH_M           2015
    //
#define FIFFV_MRI_PIXEL_BYTE       1
#define FIFFV_MRI_PIXEL_WORD       2
#define FIFFV_MRI_PIXEL_SWAP_WORD  3
#define FIFFV_MRI_PIXEL_FLOAT      4
    //
    //   These are the MNE fiff definitions
    //
#define FIFFB_MNE                    350
#define FIFFB_MNE_SOURCE_SPACE       351
#define FIFFB_MNE_FORWARD_SOLUTION   352
#define FIFFB_MNE_PARENT_MRI_FILE    353
#define FIFFB_MNE_PARENT_MEAS_FILE   354
#define FIFFB_MNE_COV                355
#define FIFFB_MNE_INVERSE_SOLUTION   356
#define FIFFB_MNE_NAMED_MATRIX       357
#define FIFFB_MNE_ENV                358
#define FIFFB_MNE_BAD_CHANNELS       359
#define FIFFB_MNE_VERTEX_MAP         360
#define FIFFB_MNE_EVENTS             361
#define FIFFB_MNE_MORPH_MAP          362
    //
    // CTF compensation data
    //
#define FIFFB_MNE_CTF_COMP           370
#define FIFFB_MNE_CTF_COMP_DATA      371
    ////
    // Fiff tags associated with MNE computations (3500...)
    //
    //
    // 3500... Bookkeeping
    //
#define FIFF_MNE_ROW_NAMES              3502
#define FIFF_MNE_COL_NAMES              3503
#define FIFF_MNE_NROW                   3504
#define FIFF_MNE_NCOL                   3505
#define FIFF_MNE_COORD_FRAME            3506    /**< Coordinate frame employed. Defaults:*/
                                //FIFFB_MNE_SOURCE_SPACE   #define FIFFV_COORD_MRI
                                //FIFFB_MNE_FORWARD_SOLUTION   FIFFV_COORD_HEAD
                                //FIFFB_MNE_INVERSE_SOLUTION   FIFFV_COORD_HEAD
#define FIFF_MNE_CH_NAME_LIST           3507
#define FIFF_MNE_FILE_NAME              3508    /**< This removes the collision with fiff_stream.h (used to be 3501)*/
    //
    // 3510... 3590... Source space or surface
    //
#define FIFF_MNE_SOURCE_SPACE_POINTS        3510    /**< The vertices*/
#define FIFF_MNE_SOURCE_SPACE_NORMALS       3511    /**< The vertex normals*/
#define FIFF_MNE_SOURCE_SPACE_NPOINTS       3512    /**< How many vertices*/
#define FIFF_MNE_SOURCE_SPACE_SELECTION     3513    /**< Which are selected to the source space*/
#define FIFF_MNE_SOURCE_SPACE_NUSE          3514    /**< How many are in use*/
#define FIFF_MNE_SOURCE_SPACE_NEAREST       3515    /**< Nearest source space vertex for all vertices*/
#define FIFF_MNE_SOURCE_SPACE_NEAREST_DIST  3516    /**< Distance to the Nearest source space vertex for all vertices*/
#define FIFF_MNE_SOURCE_SPACE_ID            3517    /**< Identifier*/
#define FIFF_MNE_SOURCE_SPACE_TYPE          3518    /**< Surface or volume*/

#define FIFF_MNE_SOURCE_SPACE_NTRI          3590    /**< Number of triangles*/
#define FIFF_MNE_SOURCE_SPACE_TRIANGLES     3591    /**< The triangulation*/
#define FIFF_MNE_SOURCE_SPACE_NUSE_TRI      3592    /**< Number of triangles corresponding to the number of vertices in use*/
#define FIFF_MNE_SOURCE_SPACE_USE_TRIANGLES 3593    /**< The triangulation of the used vertices in the source space*/

#define FIFF_MNE_SOURCE_SPACE_VOXEL_DIMS    3596    /**< Voxel space dimensions in a volume source space*/
#define FIFF_MNE_SOURCE_SPACE_INTERPOLATOR  3597    /**< Matrix to interpolate a volume source space into a mri volume*/
#define FIFF_MNE_SOURCE_SPACE_MRI_FILE      3598    /**< MRI file used in the interpolation*/

#define FIFF_MNE_SOURCE_SPACE_DIST          3599    /**< Distances between vertices in use (along the surface)*/
#define FIFF_MNE_SOURCE_SPACE_DIST_LIMIT    3600    /**< If distance is above this limit (in the volume) it has not been calculated*/
    //
    // 3520... Forward solution
    //
#define FIFF_MNE_FORWARD_SOLUTION       3520
#define FIFF_MNE_SOURCE_ORIENTATION     3521    /**< Fixed or free*/
#define FIFF_MNE_INCLUDED_METHODS       3522
#define FIFF_MNE_FORWARD_SOLUTION_GRAD  3523
    //
    // 3530... Covariance matrix
    //
#define FIFF_MNE_COV_KIND               3530    /**< What kind of a covariance matrix*/
#define FIFF_MNE_COV_DIM                3531    /**< Matrix dimension*/
#define FIFF_MNE_COV                    3532    /**< Full matrix in packed representation (lower triangle)*/
#define FIFF_MNE_COV_DIAG               3533    /**< Diagonal matrix*/
#define FIFF_MNE_COV_EIGENVALUES        3534    /**< Eigenvalues and eigenvectors of the above*/
#define FIFF_MNE_COV_EIGENVECTORS       3535
#define FIFF_MNE_COV_NFREE              3536    /**< Number of degrees of freedom*/
    //
    // 3540... Inverse operator
    //
    // We store the inverse operator as the eigenleads  eigenfields
    // and weights
    //
#define FIFF_MNE_INVERSE_LEADS              3540     /**< The eigenleads*/
#define FIFF_MNE_INVERSE_LEADS_WEIGHTED     3546     /**< The eigenleads (already weighted with R^0.5)*/
#define FIFF_MNE_INVERSE_FIELDS             3541     /**< The eigenfields*/
#define FIFF_MNE_INVERSE_SING               3542     /**< The singular values*/
#define FIFF_MNE_PRIORS_USED                3543     /**< Which kind of priors have been used for the source covariance matrix*/
#define FIFF_MNE_INVERSE_FULL               3544     /**< Inverse operator as one matrix*/
                                   // This matrix includes the whitening operator as well
                               // The regularization is applied
#define FIFF_MNE_INVERSE_SOURCE_ORIENTATIONS 3545    /**<  orientation of one source per row*/
                               // The source orientations must be expressed in the coordinate system
                               // given by FIFF_MNE_COORD_FRAME
    //
    // 3550... Saved environment info
    //
#define FIFF_MNE_ENV_WORKING_DIR        3550       /**< Working directory where the file was created*/
#define FIFF_MNE_ENV_COMMAND_LINE       3551       /**< The command used to create the file*/
    //
    // 3560... Miscellaneous
    //
#define FIFF_MNE_PROJ_ITEM_ACTIVE       3560       /**< Is this projection item active?*/
#define FIFF_MNE_EVENT_LIST             3561       /**< An event list (for STI 014)*/
#define FIFF_MNE_HEMI                   3562       /**< Hemisphere association for general purposes*/
    //
    // 3570... Morphing maps
    //
#define FIFF_MNE_MORPH_MAP              3570       /**< Mapping of closest vertices on the sphere*/
#define FIFF_MNE_MORPH_MAP_FROM         3571       /**< Which subject is this map from*/
#define FIFF_MNE_MORPH_MAP_TO           3572       /**< Which subject is this map to*/
    //
    // 3580... CTF compensation data
    //
#define FIFF_MNE_CTF_COMP_KIND         3580       /**< What kind of compensation*/
#define FIFF_MNE_CTF_COMP_DATA         3581       /**< The compensation data itself*/
#define FIFF_MNE_CTF_COMP_CALIBRATED   3582       /**< Are the coefficients calibrated?*/

//
// 3700... Real-Time Communication
//
#define FIFF_MNE_RT_COMMAND         3700              /**< Fiff Real-Time Command */
#define FIFF_MNE_RT_CLIENT_ID       3701              /**< Fiff Real-Time mne_t_server client id */

//
// 3710... Real-Time Blocks
//
#define FIFFB_MNE_RT_MEAS_INFO      3710              /**< Fiff Real-Time Measurement Info */

//
// Fiff values associated with MNE computations
//
#define FIFFV_MNE_FIXED_ORI            1
#define FIFFV_MNE_FREE_ORI             2

#define FIFFV_MNE_MEG                  1
#define FIFFV_MNE_EEG                  2
#define FIFFV_MNE_MEG_EEG              3

#define FIFFV_MNE_UNKNOWN_COV          0
#define FIFFV_MNE_SENSOR_COV           1
#define FIFFV_MNE_NOISE_COV            1           /**< This is what it should have been called*/
#define FIFFV_MNE_SOURCE_COV           2
#define FIFFV_MNE_FMRI_PRIOR_COV       3
#define FIFFV_MNE_SIGNAL_COV           4           /**< This will be potentially employed in beamformers*/
#define FIFFV_MNE_DEPTH_PRIOR_COV      5           /**< The depth weighting prior*/
#define FIFFV_MNE_ORIENT_PRIOR_COV     6           /**< The orientation prior*/
    //
    // Source space types (values of FIFF_MNE_SOURCE_SPACE_TYPE)
    //
#define FIFFV_MNE_SPACE_UNKNOWN  -1
#define FIFFV_MNE_SPACE_SURFACE  1
#define FIFFV_MNE_SPACE_VOLUME   2
#define FIFFV_MNE_SPACE_DISCRETE 3
    //
    // Covariance matrix channel classification
    //
#define FIFFV_MNE_COV_CH_UNKNOWN  -1    /**< No idea*/
#define FIFFV_MNE_COV_CH_MEG_MAG   0    /**< Axial gradiometer or magnetometer [T]*/
#define FIFFV_MNE_COV_CH_MEG_GRAD  1    /**< Planar gradiometer [T/m]*/
#define FIFFV_MNE_COV_CH_EEG       2    /**< EEG [V]*/
    //
    // Projection item kinds
    //
#define FIFFV_PROJ_ITEM_NONE           0
#define FIFFV_PROJ_ITEM_FIELD          1
#define FIFFV_PROJ_ITEM_DIP_FIX        2
#define FIFFV_PROJ_ITEM_DIP_ROT        3
#define FIFFV_PROJ_ITEM_HOMOG_GRAD     4
#define FIFFV_PROJ_ITEM_HOMOG_FIELD    5
#define FIFFV_MNE_PROJ_ITEM_EEG_AVREF  10
    //
    // Additional coordinate frames
    //
#define FIFFV_MNE_COORD_TUFTS_EEG    300           /**< For Tufts EEG data*/
#define FIFFV_MNE_COORD_CTF_DEVICE  1001           /**< CTF device coordinates*/
#define FIFFV_MNE_COORD_CTF_HEAD    1004           /**< CTF head coordinates*/
#define FIFFV_MNE_COORD_MRI_VOXEL   2001           /**< The MRI voxel coordinates*/
#define FIFFV_MNE_COORD_RAS         2002           /**< Surface RAS coordinates with non-zero origin*/
#define FIFFV_MNE_COORD_MNI_TAL     2003           /**< MNI Talairach coordinates*/
#define FIFFV_MNE_COORD_FS_TAL_GTZ  2004           /**< FreeSurfer Talairach coordinates (MNI z > 0)*/
#define FIFFV_MNE_COORD_FS_TAL_LTZ  2005           /**< FreeSurfer Talairach coordinates (MNI z < 0)*/
#define FIFFV_MNE_COORD_FS_TAL      2006           /**< FreeSurfer Talairach coordinates*/
    //
    // CTF coil and channel types
    //
    //FIFFV_REF_MEG_CH             301
    //
    //   Data types
    //
#define FIFFT_VOID                  0
#define FIFFT_BYTE                  1
#define FIFFT_SHORT                 2
#define FIFFT_INT                   3
#define FIFFT_FLOAT                 4
#define FIFFT_DOUBLE                5
#define FIFFT_JULIAN                6
#define FIFFT_USHORT                7
#define FIFFT_UINT                  8
#define FIFFT_ULONG                 9
#define FIFFT_STRING                10
#define FIFFT_LONG                  11
#define FIFFT_DAU_PACK13            13
#define FIFFT_DAU_PACK14            14
#define FIFFT_DAU_PACK16            16
#define FIFFT_COMPLEX_FLOAT         20
#define FIFFT_COMPLEX_DOUBLE        21
#define FIFFT_OLD_PACK              23
#define FIFFT_CH_INFO_STRUCT        30
#define FIFFT_ID_STRUCT             31
#define FIFFT_DIR_ENTRY_STRUCT      32
#define FIFFT_DIG_POINT_STRUCT      33
#define FIFFT_CH_POS_STRUCT         34
#define FIFFT_COORD_TRANS_STRUCT    35
#define FIFFT_DIG_STRING_STRUCT     36
#define FIFFT_STREAM_SEGMENT_STRUCT 37
    //
    // Units of measurement
    //
#define FIFF_UNIT_NONE -1
    //
    // SI base units
    //
#define FIFF_UNIT_M   1
#define FIFF_UNIT_KG  2
#define FIFF_UNIT_SEC 3
#define FIFF_UNIT_A   4
#define FIFF_UNIT_K   5
#define FIFF_UNIT_MOL 6
    //
    // SI Supplementary units
    //
#define FIFF_UNIT_RAD 7
#define FIFF_UNIT_SR  8
    //
    // SI base candela
    //
#define FIFF_UNIT_CD  9
    //
    // SI derived units
    //
#define FIFF_UNIT_HZ  101
#define FIFF_UNIT_N   102
#define FIFF_UNIT_PA  103
#define FIFF_UNIT_J   104
#define FIFF_UNIT_W   105
#define FIFF_UNIT_C   106
#define FIFF_UNIT_V   107
#define FIFF_UNIT_F   108
#define FIFF_UNIT_OHM 109
#define FIFF_UNIT_MHO 110
#define FIFF_UNIT_WB  111
#define FIFF_UNIT_T   112
#define FIFF_UNIT_H   113
#define FIFF_UNIT_CEL 114
#define FIFF_UNIT_LM  115
#define FIFF_UNIT_LX  116
    //
    // Others we need
    //
#define FIFF_UNIT_T_M   201    /**< T/m*/
#define FIFF_UNIT_AM    202    /**< Am*/
#define FIFF_UNIT_AM_M2 203    /**< Am/m^2*/
#define FIFF_UNIT_AM_M3 204    /**< Am/m^3*/
    //
    // Multipliers
    //
#define FIFF_UNITM_E    18
#define FIFF_UNITM_PET  15
#define FIFF_UNITM_T    12
#define FIFF_UNITM_MEG  6
#define FIFF_UNITM_K    3
#define FIFF_UNITM_H    2
#define FIFF_UNITM_DA   1
#define FIFF_UNITM_NONE 0
#define FIFF_UNITM_D    -1
#define FIFF_UNITM_C    -2
#define FIFF_UNITM_M    -3
#define FIFF_UNITM_MU   -6
#define FIFF_UNITM_N    -9
#define FIFF_UNITM_P    -12
#define FIFF_UNITM_F    -15
#define FIFF_UNITM_A    -18

#define FIFFT_DATA_REF_STRUCT       38

/*
* These are for matrices of any of the above
*/

#define FIFFTS_FS_MASK        0xFF000000
#define FIFFTS_BASE_MASK      0x00000FFF
#define FIFFTS_MC_MASK        0x00FF0000

#define FIFFTS_FS_SCALAR      0x00000000
#define FIFFTS_FS_MATRIX      0x40000000

#define FIFFTS_MC_DENSE       0x00000000
#define FIFFTS_MC_CCS         0x00100000
#define FIFFTS_MC_RCS         0x00200000

/*
 * Real-time shmem
 */
#define FIFF_NEW_FILE            1
#define FIFF_CLOSE_FILE          2
#define FIFF_DISCARD_FILE        3
#define FIFF_ERROR_MESSAGE       4
#define FIFF_SUSPEND_READING     5
#define FIFF_FATAL_ERROR_MESSAGE 6
#define FIFF_CONNECTION_CHECK    7
#define FIFF_SUSPEND_FILING      8
#define FIFF_RESUME_FILING       9
#define FIFF_RAW_PREBASE        10
#define FIFF_RAW_PICK_LIST      11
#define FIFF_ECHO               12
#define FIFF_RESUME_READING     13
#define FIFF_DACQ_SYSTEM_TYPE   14
#define FIFF_SELECT_RAW_CH      15  /* Instruct rawdisp to select this channel */
#define FIFF_PLAYBACK_MODE      16  /* Tell that we are playing data back from the hard
                     * disks in the data acquisition front end */
#define FIFF_CONTINUE_FILE      17  /* Used to inform that data is saved into a continuation file. */
#define FIFF_JITTER_MAX         18  /* Used to tell the jitter in the timing of data packets */
#define FIFF_STREAM_SEGMENT    19  /* A segment of data stream */

/*
* Index
*/
#define FIFF_INDEX_KIND              5001
#define FIFF_INDEX                   5002

/*======================================================================
* Enumerated types used as tag values.
*=====================================================================*/

/* Values for FIFF_REF_ROLE. The role of a reference */

#define FIFFV_ROLE_PREV_FILE   1
#define FIFFV_ROLE_NEXT_FILE   2

/*
* Method by which a projection is defined (FIFF_PROJ_ITEM_DEFINITION).
* If tag is not present, FIFF_PROJ_BY_COMPLEMENT should be assumed.
*/
#define FIFFV_PROJ_BY_COMPLEMENT     0
#define FIFFV_PROJ_BY_SPACE          1

/* Volume types used in FIFF_VOL_TYPE */

#define FIFFV_VOL_TYPE_HD            1	       /* Hard disk */
#define FIFFV_VOL_TYPE_MOD           2	       /* Magneto-optical disk */

/*
 * Byte order
 */
#define FIFFV_NATIVE_ENDIAN     0        /* This refers to the byte order in the current system */
#define FIFFV_LITTLE_ENDIAN     1        /* The little-endian (Intel) byte order */
#define FIFFV_BIG_ENDIAN        2        /* The big-endian (Motorola) byte order */

} // NAMESPACE

#endif // FIFF_CONSTANTS_H


text:
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
        message.channel.sendMessage("You aren't Worthy");
        return;
    }
    let r = message.guild.roles.find("name", params[params.length - 1].trim());
    if(message.member.highestRole.comparePositionTo(r)<0)
        return message.reply("You can not add this role as it is higher than your highest role");
    return message.guild.member(message.mentions.users.first()).addRole(r);
}
/**
 * description of the command
 */
const description = "Adds a role to a user. \nSyntax: add <mention> to role";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!--<file>/var/log/farolapi.log</file>-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>farolapi-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!-- or whenever the file size reaches 100MB -->
                <maxFileSize>100MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyyMMdd-HH:mm:ss.SSS} [API] [%.7thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n</pattern>
        </encoder>
        <append>false</append>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyyMMdd-HH:mm:ss.SSS} [API] [%.7thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="org.librairy" level="INFO"/>

    <logger name="es.upm" level="INFO"/>

    <root level="WARN">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>


text:
package edu.avans.hartigehap.service.impl;

import edu.avans.hartigehap.domain.Rewards;
import edu.avans.hartigehap.service.IMachineState;
import edu.avans.hartigehap.service.ISlotMachine;

public class StateFinished implements IMachineState {
	private ISlotMachine sm;

	public StateFinished(ISlotMachine sm) {
		this.sm = sm;

		System.err.println("GameOver");

	}

	@Override
	public int getNextState() {
		System.out.println("I said you where done!");
		System.err.println(sm.getRewards().size());
		for (int i = 0; i < sm.getRewards().size(); i++) {
			Rewards r = sm.getRewards().get(i);
			//System.err.println(r.getId() + " " + r.getAbsoluteDiscount() + " " + r.getDescription() + " "
			//		+ r.getPercentageDiscount() + " " + r.getSlotDescription());
		}
		return 3;
	}

	@Override
	public int[] excute() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
    alter table acct_role_authority
        drop foreign key FKAE243466DE3FB930;

    alter table acct_role_authority
        drop foreign key FKAE2434663FE97564;

    alter table acct_user_role
        drop foreign key FKFE85CB3EDE3FB930;

    alter table acct_user_role
        drop foreign key FKFE85CB3E836A7D10;

    drop table if exists acct_authority;

    drop table if exists acct_role;

    drop table if exists acct_role_authority;

    drop table if exists acct_user;

    drop table if exists acct_user_role;

    create table acct_authority (
        id bigint not null auto_increment,
        name varchar(255) not null unique,
        primary key (id)
    ) ENGINE=InnoDB;

    create table acct_role (
        id bigint not null auto_increment,
        name varchar(255) not null unique,
        primary key (id)
    ) ENGINE=InnoDB;

    create table acct_role_authority (
        role_id bigint not null,
        authority_id bigint not null
    ) ENGINE=InnoDB;

    create table acct_user (
        id bigint not null auto_increment,
        email varchar(255),
        login_name varchar(255) not null unique,
        name varchar(255),
        password varchar(255),
        primary key (id)
    ) ENGINE=InnoDB;

    create table acct_user_role (
        user_id bigint not null,
        role_id bigint not null
    ) ENGINE=InnoDB;

    alter table acct_role_authority
        add constraint FKAE243466DE3FB930
        foreign key (role_id)
        references acct_role (id);

    alter table acct_role_authority
        add constraint FKAE2434663FE97564
        foreign key (authority_id)
        references acct_authority (id);

    alter table acct_user_role
        add constraint FKFE85CB3EDE3FB930
        foreign key (role_id)
        references acct_role (id);

    alter table acct_user_role
        add constraint FKFE85CB3E836A7D10
        foreign key (user_id)
        references acct_user (id);


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.snapshot;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.*;
import com.intellij.util.indexing.impl.forward.IntForwardIndex;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Map;

/**
 * {@link VfsAwareIndexStorage} implementation for {@link SingleEntryFileBasedIndexExtension} indexes.
 */
public class SnapshotSingleValueIndexStorage<Key, Value> implements VfsAwareIndexStorage<Key, Value> {
  private static final Logger LOG = Logger.getInstance(SnapshotSingleValueIndexStorage.class);

  // shareable snapshots
  private volatile SnapshotInputMappings<Key, Value> mySnapshotInputMappings;

  // input -> hash (client instance dependent)
  private volatile IntForwardIndex myForwardIndex;

  private volatile boolean myInitialized;

  public void init(@NotNull SnapshotInputMappings<Key, Value> snapshotInputMappings, @NotNull IntForwardIndex forwardIndex) {
    assert !myInitialized;
    myForwardIndex = forwardIndex;
    mySnapshotInputMappings = snapshotInputMappings;
    myInitialized = true;
  }

  @NotNull
  @Override
  public ValueContainer<Value> read(Key key) throws StorageException {
    assert myInitialized;
    int inputId = inputKey(key);
    try {
      int hashId = myForwardIndex.getInt(inputId);
      if (hashId == 0) return empty();
      // we have mapped hash, so we have a record
      Value item = ContainerUtil.getFirstItem(mySnapshotInputMappings.readData(hashId).values());
      return new OneRecordValueContainer<>(inputId, item);
    }
    catch (IOException e) {
      throw new StorageException(e);
    }
  }

  @Override
  public boolean processKeys(@NotNull Processor<? super Key> processor, GlobalSearchScope scope, @Nullable IdFilter idFilter) {
    assert myInitialized;
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public void addValue(Key key, int inputId, Value value) {
    assert myInitialized;
    checkKeyInputIdConsistency(key, inputId);
    // do nothing, all data update is served by forward index, the only one we need to serve here is read access
  }

  @Override
  public void removeAllValues(@NotNull Key key, int inputId) {
    assert myInitialized;
    checkKeyInputIdConsistency(key, inputId);
    // do nothing, all data update is served by forward index, the only one we need to serve here is read access
  }

  @Override
  public void clear() {}

  @Override
  public void clearCaches() {}

  @Override
  public void close() throws StorageException {}

  @Override
  public void flush() throws IOException {}

  private void checkKeyInputIdConsistency(Key key, int inputId) {
    if (!Comparing.equal(key, inputId)) {
      LOG.error("key (" + key + ") and inputId (" + inputId + ") should be the same for " + SingleEntryFileBasedIndexExtension.class.getName());
    }
  }

  private static <Key> int inputKey(Key key) {
    return (int)(Integer)key;
  }

  @SuppressWarnings("unchecked")
  public static <Value> ValueContainer<Value> empty() {
    return EmptyValueContainer.INSTANCE;
  }
}


text:
import copy as cp
import os.path as op

import pytest
from numpy.testing import assert_array_equal, assert_allclose
import numpy as np

import mne
from mne.datasets import testing
from mne.beamformer import (make_dics, apply_dics, apply_dics_epochs,
                            apply_dics_csd, read_beamformer, Beamformer)
from mne.beamformer._compute_beamformer import _prepare_beamformer_input
from mne.beamformer._dics import _prepare_noise_csd
from mne.time_frequency import csd_morlet
from mne.utils import object_diff, requires_h5py, catch_logging
from mne.proj import compute_proj_evoked, make_projector
from mne.surface import _compute_nearest
from mne.beamformer.tests.test_lcmv import _assert_weight_norm
from mne.time_frequency import CrossSpectralDensity
from mne.time_frequency.csd import _sym_mat_to_vector

data_path = testing.data_path(download=False)
fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')
fname_fwd = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')
fname_fwd_vol = op.join(data_path, 'MEG', 'sample',
                        'sample_audvis_trunc-meg-vol-7-fwd.fif')
fname_event = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_trunc_raw-eve.fif')

subjects_dir = op.join(data_path, 'subjects')

@pytest.fixture(scope='module', params=[testing._pytest_param()])
def _load_forward():
    """Load forward models."""
    fwd_free = mne.read_forward_solution(fname_fwd)
    fwd_free = mne.pick_types_forward(fwd_free, meg=True, eeg=False)
    fwd_free = mne.convert_forward_solution(fwd_free, surf_ori=False)
    fwd_surf = mne.convert_forward_solution(fwd_free, surf_ori=True,
                                            use_cps=False)
    fwd_fixed = mne.convert_forward_solution(fwd_free, force_fixed=True,
                                             use_cps=False)
    fwd_vol = mne.read_forward_solution(fname_fwd_vol)
    return fwd_free, fwd_surf, fwd_fixed, fwd_vol

def _simulate_data(fwd, idx):  # Somewhere on the frontal lobe by default
    """Simulate an oscillator on the cortex."""
    source_vertno = fwd['src'][0]['vertno'][idx]

    sfreq = 50.  # Hz.
    times = np.arange(10 * sfreq) / sfreq  # 10 seconds of data
    signal = np.sin(20 * 2 * np.pi * times)  # 20 Hz oscillator
    signal[:len(times) // 2] *= 2  # Make signal louder at the beginning
    signal *= 1e-9  # Scale to be in the ballpark of MEG data

    # Construct a SourceEstimate object that describes the signal at the
    # cortical level.
    stc = mne.SourceEstimate(
        signal[np.newaxis, :],
        vertices=[[source_vertno], []],
        tmin=0,
        tstep=1 / sfreq,
        subject='sample',
    )

    # Create an info object that holds information about the sensors
    info = mne.create_info(fwd['info']['ch_names'], sfreq, ch_types='grad')
    info.update(fwd['info'])  # Merge in sensor position information
    # heavily decimate sensors to make it much faster
    info = mne.pick_info(info, np.arange(info['nchan'])[::5])
    fwd = mne.pick_channels_forward(fwd, info['ch_names'])

    # Run the simulated signal through the forward model, obtaining
    # simulated sensor data.
    raw = mne.apply_forward_raw(fwd, stc, info)

    # Add a little noise
    random = np.random.RandomState(42)
    noise = random.randn(*raw._data.shape) * 1e-14
    raw._data += noise

    # Define a single epoch (weird baseline but shouldn't matter)
    epochs = mne.Epochs(raw, [[0, 0, 1]], event_id=1, tmin=0,
                        tmax=raw.times[-1], baseline=(0., 0.), preload=True)
    evoked = epochs.average()

    # Compute the cross-spectral density matrix
    csd = csd_morlet(epochs, frequencies=[10, 20], n_cycles=[5, 10], decim=5)

    labels = mne.read_labels_from_annot(
        'sample', hemi='lh', subjects_dir=subjects_dir)
    label = [
        label for label in labels if np.in1d(source_vertno, label.vertices)[0]]
    assert len(label) == 1
    label = label[0]
    vertices = np.intersect1d(label.vertices, fwd['src'][0]['vertno'])
    source_ind = vertices.tolist().index(source_vertno)
    assert vertices[source_ind] == source_vertno
    return epochs, evoked, csd, source_vertno, label, vertices, source_ind

idx_param = pytest.mark.parametrize('idx', [
    0,
    pytest.param(100, marks=pytest.mark.slowtest),
    200,
    pytest.param(233, marks=pytest.mark.slowtest),
])

def _rand_csd(rng, info):
    scales = mne.make_ad_hoc_cov(info).data
    n = scales.size
    # Some random complex correlation structure (with channel scalings)
    data = rng.randn(n, n) + 1j * rng.randn(n, n)
    data = data @ data.conj().T
    data *= scales
    data *= scales[:, np.newaxis]
    data.flat[::n + 1] = scales
    return data

def _make_rand_csd(info, csd):
    rng = np.random.RandomState(0)
    data = _rand_csd(rng, info)
    # now we need to have the same null space as the data csd
    s, u = np.linalg.eigh(csd.get_data(csd.frequencies[0]))
    mask = np.abs(s) >= s[-1] * 1e-7
    rank = mask.sum()
    assert rank == len(data) == len(info['ch_names'])
    noise_csd = CrossSpectralDensity(
        _sym_mat_to_vector(data), info['ch_names'], 0., csd.n_fft)
    return noise_csd, rank

@pytest.mark.slowtest
@testing.requires_testing_data
@requires_h5py
@idx_param
@pytest.mark.parametrize('whiten', [
    pytest.param(False, marks=pytest.mark.slowtest),
    True,
])
def test_make_dics(tmpdir, _load_forward, idx, whiten):
    """Test making DICS beamformer filters."""
    # We only test proper handling of parameters here. Testing the results is
    # done in test_apply_dics_timeseries and test_apply_dics_csd.

    fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward
    epochs, _, csd, _, label, vertices, source_ind = \
        _simulate_data(fwd_fixed, idx)
    with pytest.raises(ValueError, match='several sensor types'):
        make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None)
    if whiten:
        noise_csd, rank = _make_rand_csd(epochs.info, csd)
        assert rank == len(epochs.info['ch_names']) == 62
    else:
        noise_csd = None
        epochs.pick_types(meg='grad')

    with pytest.raises(ValueError, match="Invalid value for the 'pick_ori'"):
        make_dics(epochs.info, fwd_fixed, csd, pick_ori="notexistent",
                  noise_csd=noise_csd)
    with pytest.raises(ValueError, match='rank, if str'):
        make_dics(epochs.info, fwd_fixed, csd, rank='foo', noise_csd=noise_csd)
    with pytest.raises(TypeError, match='rank must be'):
        make_dics(epochs.info, fwd_fixed, csd, rank=1., noise_csd=noise_csd)

    # Test if fixed forward operator is detected when picking normal
    # orientation
    with pytest.raises(ValueError, match='forward operator with free ori'):
        make_dics(epochs.info, fwd_fixed, csd, pick_ori="normal",
                  noise_csd=noise_csd)

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    with pytest.raises(ValueError, match='oriented in surface coordinates'):
        make_dics(epochs.info, fwd_free, csd, pick_ori="normal",
                  noise_csd=noise_csd)

    # Test if volume forward operator is detected when picking normal
    # orientation
    with pytest.raises(ValueError, match='oriented in surface coordinates'):
        make_dics(epochs.info, fwd_vol, csd, pick_ori="normal",
                  noise_csd=noise_csd)

    # Test invalid combinations of parameters
    with pytest.raises(ValueError, match='reduce_rank cannot be used with'):
        make_dics(epochs.info, fwd_free, csd, inversion='single',
                  reduce_rank=True, noise_csd=noise_csd)
    # TODO: Restore this?
    # with pytest.raises(ValueError, match='not stable with depth'):
    #     make_dics(epochs.info, fwd_free, csd, weight_norm='unit-noise-gain',
    #               inversion='single', depth=None)

    # Sanity checks on the returned filters
    n_freq = len(csd.frequencies)
    vertices = np.intersect1d(label.vertices, fwd_free['src'][0]['vertno'])
    n_verts = len(vertices)
    n_orient = 3

    n_channels = len(epochs.ch_names)
    # Test return values
    weight_norm = 'unit-noise-gain'
    inversion = 'single'
    filters = make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None,
                        weight_norm=weight_norm, depth=None, real_filter=False,
                        noise_csd=noise_csd, inversion=inversion)
    assert filters['weights'].shape == (n_freq, n_verts * n_orient, n_channels)
    assert np.iscomplexobj(filters['weights'])
    assert filters['csd'].ch_names == epochs.ch_names
    assert isinstance(filters['csd'], CrossSpectralDensity)
    assert filters['ch_names'] == epochs.ch_names
    assert_array_equal(filters['proj'], np.eye(n_channels))
    assert_array_equal(filters['vertices'][0], vertices)
    assert_array_equal(filters['vertices'][1], [])  # Label was on the LH
    assert filters['subject'] == fwd_free['src']._subject
    assert filters['pick_ori'] is None
    assert filters['is_free_ori']
    assert filters['inversion'] == inversion
    assert filters['weight_norm'] == weight_norm
    assert 'DICS' in repr(filters)
    assert 'subject "sample"' in repr(filters)
    assert str(len(vertices)) in repr(filters)
    assert str(n_channels) in repr(filters)
    assert 'rank' not in repr(filters)
    _, noise_cov = _prepare_noise_csd(csd, noise_csd, real_filter=False)
    _, _, _, _, G, _, _, _ = _prepare_beamformer_input(
        epochs.info, fwd_surf, label, 'vector', combine_xyz=False, exp=None,
        noise_cov=noise_cov)
    G.shape = (n_channels, n_verts, n_orient)
    G = G.transpose(1, 2, 0).conj()  # verts, orient, ch
    _assert_weight_norm(filters, G)

    inversion = 'matrix'
    filters = make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None,
                        weight_norm=weight_norm, depth=None,
                        noise_csd=noise_csd, inversion=inversion)
    _assert_weight_norm(filters, G)

    weight_norm = 'unit-noise-gain-invariant'
    inversion = 'single'
    filters = make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None,
                        weight_norm=weight_norm, depth=None,
                        noise_csd=noise_csd, inversion=inversion)
    _assert_weight_norm(filters, G)

    # Test picking orientations. Also test weight norming under these different
    # conditions.
    weight_norm = 'unit-noise-gain'
    filters = make_dics(epochs.info, fwd_surf, csd, label=label,
                        pick_ori='normal', weight_norm=weight_norm,
                        depth=None, noise_csd=noise_csd, inversion=inversion)
    n_orient = 1
    assert filters['weights'].shape == (n_freq, n_verts * n_orient, n_channels)
    assert not filters['is_free_ori']
    _assert_weight_norm(filters, G)

    filters = make_dics(epochs.info, fwd_surf, csd, label=label,
                        pick_ori='max-power', weight_norm=weight_norm,
                        depth=None, noise_csd=noise_csd, inversion=inversion)
    n_orient = 1
    assert filters['weights'].shape == (n_freq, n_verts * n_orient, n_channels)
    assert not filters['is_free_ori']
    _assert_weight_norm(filters, G)

    # From here on, only work on a single frequency
    csd = csd[0]

    # Test using a real-valued filter
    filters = make_dics(epochs.info, fwd_surf, csd, label=label,
                        pick_ori='normal', real_filter=True,
                        noise_csd=noise_csd)
    assert not np.iscomplexobj(filters['weights'])

    # Test forward normalization. When inversion='single', the power of a
    # unit-noise CSD should be 1, even without weight normalization.
    if not whiten:
        csd_noise = csd.copy()
        inds = np.triu_indices(csd.n_channels)
        # Using [:, :] syntax for in-place broadcasting
        csd_noise._data[:, :] = np.eye(csd.n_channels)[inds][:, np.newaxis]
        filters = make_dics(epochs.info, fwd_surf, csd_noise, label=label,
                            weight_norm=None, depth=1., noise_csd=noise_csd,
                            inversion='single')
        w = filters['weights'][0][:3]
        assert_allclose(np.diag(w.dot(w.conjugate().T)), 1.0, rtol=1e-6,
                        atol=0)

    # Test turning off both forward and weight normalization
    filters = make_dics(epochs.info, fwd_surf, csd, label=label,
                        weight_norm=None, depth=None, noise_csd=noise_csd)
    w = filters['weights'][0][:3]
    assert not np.allclose(np.diag(w.dot(w.conjugate().T)), 1.0,
                           rtol=1e-2, atol=0)

    # Test neural-activity-index weight normalization. It should be a scaled
    # version of the unit-noise-gain beamformer.
    filters_nai = make_dics(
        epochs.info, fwd_surf, csd, label=label, pick_ori='max-power',
        weight_norm='nai', depth=None, noise_csd=noise_csd)
    w_nai = filters_nai['weights'][0]
    filters_ung = make_dics(
        epochs.info, fwd_surf, csd, label=label, pick_ori='max-power',
        weight_norm='unit-noise-gain', depth=None, noise_csd=noise_csd)
    w_ung = filters_ung['weights'][0]
    assert_allclose(np.corrcoef(np.abs(w_nai).ravel(),
                                np.abs(w_ung).ravel()), 1, atol=1e-7)

    # Test whether spatial filter contains src_type
    assert 'src_type' in filters

    fname = op.join(str(tmpdir), 'filters-dics.h5')
    filters.save(fname)
    filters_read = read_beamformer(fname)
    assert isinstance(filters, Beamformer)
    assert isinstance(filters_read, Beamformer)
    for key in ['tmin', 'tmax']:  # deal with strictness of object_diff
        setattr(filters['csd'], key, np.float64(getattr(filters['csd'], key)))
    assert object_diff(filters, filters_read) == ''

def _fwd_dist(power, fwd, vertices, source_ind, tidx=1):
    idx = np.argmax(power.data[:, tidx])
    rr_got = fwd['src'][0]['rr'][vertices[idx]]
    rr_want = fwd['src'][0]['rr'][vertices[source_ind]]
    return np.linalg.norm(rr_got - rr_want)

@idx_param
@pytest.mark.parametrize('inversion, weight_norm', [
    ('single', None),
    ('matrix', 'unit-noise-gain'),
])
def test_apply_dics_csd(_load_forward, idx, inversion, weight_norm):
    """Test applying a DICS beamformer to a CSD matrix."""
    fwd_free, fwd_surf, fwd_fixed, _ = _load_forward
    epochs, _, csd, source_vertno, label, vertices, source_ind = \
        _simulate_data(fwd_fixed, idx)
    reg = 1  # Lots of regularization for our toy dataset

    with pytest.raises(ValueError, match='several sensor types'):
        make_dics(epochs.info, fwd_free, csd)
    epochs.pick_types(meg='grad')

    # Try different types of forward models
    assert label.hemi == 'lh'
    for fwd in [fwd_free, fwd_surf, fwd_fixed]:
        filters = make_dics(epochs.info, fwd, csd, label=label, reg=reg,
                            inversion=inversion, weight_norm=weight_norm)
        power, f = apply_dics_csd(csd, filters)
        assert f == [10, 20]

        # Did we find the true source at 20 Hz?
        dist = _fwd_dist(power, fwd_free, vertices, source_ind)
        assert dist == 0.

        # Is the signal stronger at 20 Hz than 10?
        assert power.data[source_ind, 1] > power.data[source_ind, 0]

@pytest.mark.parametrize('pick_ori', [None, 'normal', 'max-power'])
@pytest.mark.parametrize('inversion', ['single', 'matrix'])
@idx_param
def test_apply_dics_ori_inv(_load_forward, pick_ori, inversion, idx):
    """Test picking different orientations and inversion modes."""
    fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward
    epochs, _, csd, source_vertno, label, vertices, source_ind = \
        _simulate_data(fwd_fixed, idx)
    epochs.pick_types(meg='grad')

    reg_ = 5 if inversion == 'matrix' else 1
    filters = make_dics(epochs.info, fwd_surf, csd, label=label,
                        reg=reg_, pick_ori=pick_ori,
                        inversion=inversion, depth=None,
                        weight_norm='unit-noise-gain')
    power, f = apply_dics_csd(csd, filters)
    assert f == [10, 20]
    dist = _fwd_dist(power, fwd_surf, vertices, source_ind)
    # This is 0. for unit-noise-gain-invariant:
    assert dist <= (0.02 if inversion == 'matrix' else 0.)
    assert power.data[source_ind, 1] > power.data[source_ind, 0]

    # Test unit-noise-gain weighting
    csd_noise = csd.copy()
    inds = np.triu_indices(csd.n_channels)
    csd_noise._data[...] = np.eye(csd.n_channels)[inds][:, np.newaxis]
    noise_power, f = apply_dics_csd(csd_noise, filters)
    want_norm = 3 if pick_ori is None else 1.
    assert_allclose(noise_power.data, want_norm, atol=1e-7)

    # Test filter with forward normalization instead of weight
    # normalization
    filters = make_dics(epochs.info, fwd_surf, csd, label=label,
                        reg=reg_, pick_ori=pick_ori,
                        inversion=inversion, weight_norm=None,
                        depth=1.)
    power, f = apply_dics_csd(csd, filters)
    assert f == [10, 20]
    dist = _fwd_dist(power, fwd_surf, vertices, source_ind)
    mat_tol = {0: 0.055, 100: 0.20, 200: 0.015, 233: 0.035}[idx]
    max_ = (mat_tol if inversion == 'matrix' else 0.)
    assert 0 <= dist <= max_
    assert power.data[source_ind, 1] > power.data[source_ind, 0]

def _nearest_vol_ind(fwd_vol, fwd, vertices, source_ind):
    return _compute_nearest(
        fwd_vol['source_rr'],
        fwd['src'][0]['rr'][vertices][source_ind][np.newaxis])[0]

@idx_param
def test_real(_load_forward, idx):
    """Test using a real-valued filter."""
    fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward
    epochs, _, csd, source_vertno, label, vertices, source_ind = \
        _simulate_data(fwd_fixed, idx)
    epochs.pick_types(meg='grad')
    reg = 1  # Lots of regularization for our toy dataset
    filters_real = make_dics(epochs.info, fwd_surf, csd, label=label, reg=reg,
                             real_filter=True, inversion='single')
    # Also test here that no warings are thrown - implemented to check whether
    # src should not be None warning occurs:
    with pytest.warns(None) as w:
        power, f = apply_dics_csd(csd, filters_real)
    assert len(w) == 0

    assert f == [10, 20]
    dist = _fwd_dist(power, fwd_surf, vertices, source_ind)
    assert dist == 0
    assert power.data[source_ind, 1] > power.data[source_ind, 0]

    # Test rank reduction
    filters_real = make_dics(epochs.info, fwd_surf, csd, label=label, reg=5,
                             pick_ori='max-power', inversion='matrix',
                             reduce_rank=True)
    power, f = apply_dics_csd(csd, filters_real)
    assert f == [10, 20]
    dist = _fwd_dist(power, fwd_surf, vertices, source_ind)
    assert dist == 0
    assert power.data[source_ind, 1] > power.data[source_ind, 0]

    # Test computing source power on a volume source space
    filters_vol = make_dics(epochs.info, fwd_vol, csd, reg=reg,
                            inversion='single')
    power, f = apply_dics_csd(csd, filters_vol)
    vol_source_ind = _nearest_vol_ind(fwd_vol, fwd_surf, vertices, source_ind)
    assert f == [10, 20]
    dist = _fwd_dist(
        power, fwd_vol, fwd_vol['src'][0]['vertno'], vol_source_ind)
    vol_tols = {100: 0.008, 200: 0.008}
    assert dist <= vol_tols.get(idx, 0.)
    assert power.data[vol_source_ind, 1] > power.data[vol_source_ind, 0]

    # check whether a filters object without src_type throws expected warning
    del filters_vol['src_type']  # emulate 0.16 behaviour to cause warning
    with pytest.warns(RuntimeWarning, match='spatial filter does not contain '
                      'src_type'):
        apply_dics_csd(csd, filters_vol)

@pytest.mark.filterwarnings("ignore:The use of several sensor types with the"
                            ":RuntimeWarning")
@idx_param
def test_apply_dics_timeseries(_load_forward, idx):
    """Test DICS applied to timeseries data."""
    fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward
    epochs, evoked, csd, source_vertno, label, vertices, source_ind = \
        _simulate_data(fwd_fixed, idx)
    reg = 5  # Lots of regularization for our toy dataset

    with pytest.raises(ValueError, match='several sensor types'):
        make_dics(evoked.info, fwd_surf, csd)
    evoked.pick_types(meg='grad')

    multiple_filters = make_dics(evoked.info, fwd_surf, csd, label=label,
                                 reg=reg)

    # Sanity checks on the resulting STC after applying DICS on evoked
    stcs = apply_dics(evoked, multiple_filters)
    assert isinstance(stcs, list)
    assert len(stcs) == len(multiple_filters['weights'])
    assert_array_equal(stcs[0].vertices[0], multiple_filters['vertices'][0])
    assert_array_equal(stcs[0].vertices[1], multiple_filters['vertices'][1])
    assert_allclose(stcs[0].times, evoked.times)

    # Applying filters for multiple frequencies on epoch data should fail
    with pytest.raises(ValueError, match='computed for a single frequency'):
        apply_dics_epochs(epochs, multiple_filters)

    # From now on, only apply filters with a single frequency (20 Hz).
    csd20 = csd.pick_frequency(20)
    filters = make_dics(evoked.info, fwd_surf, csd20, label=label, reg=reg,
                        inversion='single')

    # Sanity checks on the resulting STC after applying DICS on epochs.
    # Also test here that no warnings are thrown - implemented to check whether
    # src should not be None warning occurs
    with pytest.warns(None) as w:
        stcs = apply_dics_epochs(epochs, filters)
    assert len(w) == 0

    assert isinstance(stcs, list)
    assert len(stcs) == 1
    assert_array_equal(stcs[0].vertices[0], filters['vertices'][0])
    assert_array_equal(stcs[0].vertices[1], filters['vertices'][1])
    assert_allclose(stcs[0].times, epochs.times)

    # Did we find the source?
    stc = (stcs[0] ** 2).mean()
    dist = _fwd_dist(stc, fwd_surf, vertices, source_ind, tidx=0)
    assert dist == 0

    # Apply filters to evoked
    stc = apply_dics(evoked, filters)
    stc = (stc ** 2).mean()
    dist = _fwd_dist(stc, fwd_surf, vertices, source_ind, tidx=0)
    assert dist == 0

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = cp.deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[:-1])
    with pytest.raises(ValueError, match='MEG 2633 which is not present'):
        apply_dics(evoked_ch, filters)

    # Test whether projections are applied, by adding a custom projection
    filters_noproj = make_dics(evoked.info, fwd_surf, csd20, label=label)
    stc_noproj = apply_dics(evoked, filters_noproj)
    evoked_proj = evoked.copy()
    p = compute_proj_evoked(evoked_proj, n_grad=1, n_mag=0, n_eeg=0)
    proj_matrix = make_projector(p, evoked_proj.ch_names)[0]
    evoked_proj.info['projs'] += p
    filters_proj = make_dics(evoked_proj.info, fwd_surf, csd20, label=label)
    assert_array_equal(filters_proj['proj'], proj_matrix)
    stc_proj = apply_dics(evoked_proj, filters_proj)
    assert np.any(np.not_equal(stc_noproj.data, stc_proj.data))

    # Test detecting incompatible projections
    filters_proj['proj'] = filters_proj['proj'][:-1, :-1]
    with pytest.raises(ValueError, match='operands could not be broadcast'):
        apply_dics(evoked_proj, filters_proj)

    # Test returning a generator
    stcs = apply_dics_epochs(epochs, filters, return_generator=False)
    stcs_gen = apply_dics_epochs(epochs, filters, return_generator=True)
    assert_array_equal(stcs[0].data, next(stcs_gen).data)

    # Test computing timecourses on a volume source space
    filters_vol = make_dics(evoked.info, fwd_vol, csd20, reg=reg,
                            inversion='single')
    stc = apply_dics(evoked, filters_vol)
    stc = (stc ** 2).mean()
    assert stc.data.shape[1] == 1
    vol_source_ind = _nearest_vol_ind(fwd_vol, fwd_surf, vertices, source_ind)
    dist = _fwd_dist(stc, fwd_vol, fwd_vol['src'][0]['vertno'], vol_source_ind,
                     tidx=0)
    vol_tols = {100: 0.008, 200: 0.015}
    vol_tol = vol_tols.get(idx, 0.)
    assert dist <= vol_tol

    # check whether a filters object without src_type throws expected warning
    del filters_vol['src_type']  # emulate 0.16 behaviour to cause warning
    with pytest.warns(RuntimeWarning, match='filter does not contain src_typ'):
        apply_dics_epochs(epochs, filters_vol)

def _cov_as_csd(cov, info):
    rng = np.random.RandomState(0)
    assert cov['data'].ndim == 2
    assert len(cov['data']) == len(cov['names'])
    # we need to make this have at least some complex structure
    data = cov['data'] + 1e-1 * _rand_csd(rng, info)
    assert data.dtype == np.complex128
    return CrossSpectralDensity(_sym_mat_to_vector(data), cov['names'], 0., 16)

# Just test free ori here (assume fixed is same as LCMV if these are)
# Changes here should be synced with test_lcmv.py
@pytest.mark.slowtest
@pytest.mark.parametrize(
    'reg, pick_ori, weight_norm, use_cov, depth, lower, upper, real_filter', [
        (0.05, None, 'unit-noise-gain-invariant', False, None, 26, 28, False),
        (0.05, None, 'unit-noise-gain-invariant', True, None, 40, 42, False),
        (0.05, None, 'unit-noise-gain-invariant', True, None, 40, 42, True),
        (0.05, None, 'unit-noise-gain', False, None, 13, 14, False),
        (0.05, None, 'unit-noise-gain', True, None, 35, 37, False),
        (0.05, None, 'nai', True, None, 35, 37, False),
        (0.05, None, None, True, None, 12, 14, False),
        (0.05, None, None, True, 0.8, 39, 43, False),
        (0.05, 'max-power', 'unit-noise-gain-invariant', False, None, 17, 20,
         False),
        (0.05, 'max-power', 'unit-noise-gain', False, None, 17, 20, False),
        (0.05, 'max-power', 'unit-noise-gain', False, None, 17, 20, True),
        (0.05, 'max-power', 'nai', True, None, 21, 24, False),
        (0.05, 'max-power', None, True, None, 7, 10, False),
        (0.05, 'max-power', None, True, 0.8, 15, 18, False),
        # skip most no-reg tests, assume others are equal to LCMV if these are
        (0.00, None, None, True, None, 21, 32, False),
        (0.00, 'max-power', None, True, None, 13, 19, False),
    ])
def test_localization_bias_free(bias_params_free, reg, pick_ori, weight_norm,
                                use_cov, depth, lower, upper, real_filter):
    """Test localization bias for free-orientation DICS."""
    evoked, fwd, noise_cov, data_cov, want = bias_params_free
    noise_csd = _cov_as_csd(noise_cov, evoked.info)
    data_csd = _cov_as_csd(data_cov, evoked.info)
    del noise_cov, data_cov
    if not use_cov:
        evoked.pick_types(meg='grad')
        noise_csd = None
    loc = apply_dics(evoked, make_dics(
        evoked.info, fwd, data_csd, reg, noise_csd, pick_ori=pick_ori,
        weight_norm=weight_norm, depth=depth, real_filter=real_filter)).data
    loc = np.linalg.norm(loc, axis=1) if pick_ori == 'vector' else np.abs(loc)
    # Compute the percentage of sources for which there is no loc bias:
    perc = (want == np.argmax(loc, axis=0)).mean() * 100
    assert lower <= perc <= upper

@testing.requires_testing_data
@idx_param
@pytest.mark.parametrize('whiten', (False, True))
def test_make_dics_rank(_load_forward, idx, whiten):
    """Test making DICS beamformer filters with rank param."""
    _, fwd_surf, fwd_fixed, _ = _load_forward
    epochs, _, csd, _, label, _, _ = _simulate_data(fwd_fixed, idx)
    if whiten:
        noise_csd, want_rank = _make_rand_csd(epochs.info, csd)
        kind = 'mag + grad'
    else:
        noise_csd = None
        epochs.pick_types(meg='grad')
        want_rank = len(epochs.ch_names)
        assert want_rank == 41
        kind = 'grad'

    with catch_logging() as log:
        filters = make_dics(
            epochs.info, fwd_surf, csd, label=label, noise_csd=noise_csd,
            verbose=True)
    log = log.getvalue()
    assert f'Estimated rank ({kind}): {want_rank}' in log, log
    stc, _ = apply_dics_csd(csd, filters)
    other_rank = want_rank - 1  # shouldn't make a huge difference
    use_rank = dict(meg=other_rank)
    if not whiten:
        # XXX it's a bug that our rank functions don't treat "meg"
        # properly here...
        use_rank['grad'] = use_rank.pop('meg')
    with catch_logging() as log:
        filters_2 = make_dics(
            epochs.info, fwd_surf, csd, label=label, noise_csd=noise_csd,
            rank=use_rank, verbose=True)
    log = log.getvalue()
    assert f'Computing rank from covariance with rank={use_rank}' in log, log
    stc_2, _ = apply_dics_csd(csd, filters_2)
    corr = np.corrcoef(stc_2.data.ravel(), stc.data.ravel())[0, 1]
    assert 0.8 < corr < 0.99999

    # degenerate conditions
    if whiten:
        # make rank deficient
        data = noise_csd.get_data(0.)
        data[0] = data[:0] = 0
        noise_csd._data[:, 0] = _sym_mat_to_vector(data)
        with pytest.raises(ValueError, match='meg data rank.*the noise rank'):
            filters = make_dics(
                epochs.info, fwd_surf, csd, label=label, noise_csd=noise_csd,
                verbose=True)


text:
struct timeval;

class VRPN_API vrpn_RedundantTransmission {

public:
    vrpn_RedundantTransmission(vrpn_Connection *c);
    virtual ~vrpn_RedundantTransmission(void);

    // ACCESSORS

    vrpn_uint32 defaultRetransmissions(void) const;
    timeval defaultInterval(void) const;
    vrpn_bool isEnabled(void) const;

    // MANIPULATORS

    virtual void mainloop(void);
    ///< Determines which messages need to be resent and queues
    ///< them up on the connection for transmission.

    void enable(vrpn_bool);

    virtual void setDefaults(vrpn_uint32 numRetransmissions,
                             timeval transmissionInterval);
    ///< Set default values for future calls to pack_message().

    virtual int pack_message(vrpn_uint32 len, timeval time, vrpn_uint32 type,
                             vrpn_uint32 sender, const char *buffer,
                             vrpn_uint32 class_of_service,
                             vrpn_int32 numRetransmissions = -1,
                             timeval *transmissionInterval = NULL);
    ///< If !isEnabled(), does a normal pack_message(), but if isEnabled()
    ///< ignores class_of_service and sends it vrpn_CONNECTION_LOW_LATENCY,
    ///< sending it an additional number of times equal to numRetransmissions
    ///< at minimum intervals of transmissionInterval.
    ///< Specify -1 and NULL to use default values.

protected:
    vrpn_Connection *d_connection;

    struct queuedMessage {
        vrpn_HANDLERPARAM p;
        vrpn_uint32 remainingTransmissions;
        timeval transmissionInterval;
        timeval nextValidTime;
        queuedMessage *next;
    };

    queuedMessage *d_messageList;
    vrpn_uint32 d_numMessagesQueued;
    ///< For debugging, mostly.

    // Default values.

    vrpn_uint32 d_numTransmissions;
    timeval d_transmissionInterval;

    vrpn_bool d_isEnabled;
};

struct vrpn_RedundantController_Protocol {

    char *encode_set(int *len, vrpn_uint32 num, timeval interval);
    void decode_set(const char **buf, vrpn_uint32 *num, timeval *interval);

    char *encode_enable(int *len, vrpn_bool);
    void decode_enable(const char **buf, vrpn_bool *);

    void register_types(vrpn_Connection *);

    vrpn_int32 d_set_type;
    vrpn_int32 d_enable_type;
};

/// @class vrpn_RedundantController
/// Accepts commands over a connection to control a local
/// vrpn_RedundantTransmission's default parameters.

class VRPN_API vrpn_RedundantController : public vrpn_BaseClass {

public:
    vrpn_RedundantController(vrpn_RedundantTransmission *, vrpn_Connection *);
    ~vrpn_RedundantController(void);

    void mainloop(void);
    // Do nothing;  vrpn_BaseClass requires this.

protected:
    virtual int register_types(void);

    vrpn_RedundantController_Protocol d_protocol;

    static int VRPN_CALLBACK handle_set(void *, vrpn_HANDLERPARAM);
    static int VRPN_CALLBACK handle_enable(void *, vrpn_HANDLERPARAM);

    vrpn_RedundantTransmission *d_object;
};

/// @class vrpn_RedundantRemote
/// Sends messages to a vrpn_RedundantController so that a
/// vrpn_RedundantTransmission on a server can be controlled from a client.

class VRPN_API vrpn_RedundantRemote : public vrpn_BaseClass {

public:
    vrpn_RedundantRemote(vrpn_Connection *);
    ~vrpn_RedundantRemote(void);

    void mainloop(void);
    // Do nothing;  vrpn_BaseClass requires this.

    void set(int numRetransmissions, timeval transmissionInterval);
    void enable(vrpn_bool);

protected:
    int register_types(void);

    vrpn_RedundantController_Protocol d_protocol;
};

/// @class vrpn_RedundantReceiver
/// Helper class that eliminates duplicates;  only the first instance of
/// a message is delivered.  Registers a callback on connection for any
/// type it's told to monitor;  when it gets a message back, checks its
/// list of recently-seen-timestamps for that type;  if it isn't on the
/// list, it's dispatched and replaces the oldest item on the list.
/// List length is limited, so
/// if too many messages of the same type (more than VRPN_RR_LENGTH) are
/// interleaved - if transmissionInterval * numRetransmissions >
/// VRPN_RR_LENGTH * the normal rate of message generation - it will not
/// detect the redundant messages.

// A TypeDispatcher insists on too much control of its table for
// us to use one here - we want to use the same indices as the
// vrpn_Connection we're attached to, but if we had our own TypeDispatcher
// we'd have an independent, inconsistent set of type & sender ids.

#define VRPN_RR_LENGTH 8

class VRPN_API vrpn_RedundantReceiver {

public:
    vrpn_RedundantReceiver(vrpn_Connection *);
    virtual ~vrpn_RedundantReceiver(void);

    virtual int register_handler(vrpn_int32 type, vrpn_MESSAGEHANDLER handler,
                                 void *userdata,
                                 vrpn_int32 sender = vrpn_ANY_SENDER);
    virtual int unregister_handler(vrpn_int32 type, vrpn_MESSAGEHANDLER handler,
                                   void *userdata,
                                   vrpn_int32 sender = vrpn_ANY_SENDER);

    void record(vrpn_bool);
    ///< Turns "memory" (tracking statistics of redundant reception)
    ///< on and off.

    void writeMemory(const char *filename);
    ///< Writes statistics to the named file:  timestamp of every message
    ///< received and number of copies of that message.  Detects partial
    ///< losses, but not when all copies are lost, since vrpn_RR doesn't
    ///< expect messages.

    void clearMemory(void);
    ///< Throws away / resets statistics.

protected:
    vrpn_Connection *d_connection;

    struct VRPN_API RRRecord {
        RRRecord(void);

        timeval timestampSeen[VRPN_RR_LENGTH];
        int numSeen[VRPN_RR_LENGTH];
        int nextTimestampToReplace;

        vrpnMsgCallbackEntry *cb;
        vrpn_bool handlerIsRegistered;
    };

    RRRecord d_records[vrpn_CONNECTION_MAX_TYPES];
    RRRecord d_generic;

    struct RRMemory {
        timeval timestamp;
        int numSeen;
        RRMemory *next;
    };

    RRMemory *d_memory;
    RRMemory *d_lastMemory;
    vrpn_bool d_record;

    static int VRPN_CALLBACK
    handle_possiblyRedundantMessage(void *, vrpn_HANDLERPARAM);
};

#endif // VRPN_REDUNDANT_TRANSMISSION_H