text:
import numpy as np

from . import stereonet_math

def fit_girdle(*args, **kwargs):
    """
    Fits a plane to a scatter of points on a stereonet (a.k.a. a "girdle").

    Input arguments will be interpreted as poles, lines, rakes, or "raw"
    longitudes and latitudes based on the ``measurement`` keyword argument.
    (Defaults to ``"poles"``.)

    Parameters
    ----------

    *args : 2 or 3 sequences of measurements
        By default, this will be expected to be ``strikes`` & ``dips``, both
        array-like sequences representing poles to planes.  (Rake measurements
        require three parameters, thus the variable number of arguments.) The
        *measurement* kwarg controls how these arguments are interpreted.

    measurement : {'poles', 'lines', 'rakes', 'radians'}, optional
        Controls how the input arguments are interpreted. Defaults to
        ``"poles"``.  May be one of the following:

            ``"poles"`` : Arguments are assumed to be sequences of strikes and
                dips of planes. Poles to these planes are used for density
                contouring.
            ``"lines"`` : Arguments are assumed to be sequences of plunges and
                bearings of linear features.
            ``"rakes"`` : Arguments are assumed to be sequences of strikes,
                dips, and rakes along the plane.
            ``"radians"`` : Arguments are assumed to be "raw" longitudes and
                latitudes in the underlying projection's coordinate system.

    bidirectional : boolean, optional
        Whether or not the antipode of each measurement will be used in the
        calculation. For almost all use cases, it should. Defaults to True.

    Returns
    -------
    strike, dip: floats
        The strike and dip of the plane.

    Notes
    -----
    The pole to the best-fit plane is extracted by calculating the smallest
    eigenvector of the covariance matrix of the input measurements in cartesian
    3D space.

    Examples
    --------
    Calculate the plunge of a cylindrical fold axis from a series of strike/dip
    measurements of bedding from the limbs:

        >>> strike = [270, 334, 270, 270]
        >>> dip = [20, 15, 80, 78]
        >>> s, d = mplstereonet.fit_girdle(strike, dip)
        >>> plunge, bearing = mplstereonet.pole2plunge_bearing(s, d)

    """
    vec = 0 # Smallest eigenvector will be the pole
    return _sd_of_eigenvector(args, vec=vec, **kwargs)

def fit_pole(*args, **kwargs):
    """
    Fits the pole to a plane to a "bullseye" of points on a stereonet.

    Input arguments will be interpreted as poles, lines, rakes, or "raw"
    longitudes and latitudes based on the ``measurement`` keyword argument.
    (Defaults to ``"poles"``.)

    Parameters
    ----------

    *args : 2 or 3 sequences of measurements
        By default, this will be expected to be ``strike`` & ``dip``, both
        array-like sequences representing poles to planes.  (Rake measurements
        require three parameters, thus the variable number of arguments.) The
        *measurement* kwarg controls how these arguments are interpreted.

    measurement : {'poles', 'lines', 'rakes', 'radians'}, optional
        Controls how the input arguments are interpreted. Defaults to
        ``"poles"``.  May be one of the following:

            ``"poles"`` : Arguments are assumed to be sequences of strikes and
                dips of planes. Poles to these planes are used for density
                contouring.
            ``"lines"`` : Arguments are assumed to be sequences of plunges and
                bearings of linear features.
            ``"rakes"`` : Arguments are assumed to be sequences of strikes,
                dips, and rakes along the plane.
            ``"radians"`` : Arguments are assumed to be "raw" longitudes and
                latitudes in the underlying projection's coordinate system.

    bidirectional : boolean, optional
        Whether or not the antipode of each measurement will be used in the
        calculation. For almost all use cases, it should. Defaults to True.

    Returns
    -------

    strike, dip: floats
        The strike and dip of the plane.

    Notes
    -----

    The pole to the best-fit plane is extracted by calculating the largest
    eigenvector of the covariance matrix of the input measurements in cartesian
    3D space.

    Examples
    --------

    Find the average strike/dip of a series of bedding measurements

        >>> strike = [270, 65, 280, 300]
        >>> dip = [20, 15, 10, 5]
        >>> strike0, dip0 = mplstereonet.fit_pole(strike, dip)

    """
    vec = -1 # Largest eigenvector will be the pole
    return _sd_of_eigenvector(args, vec=vec, **kwargs)

def _sd_of_eigenvector(data, vec, measurement='poles', bidirectional=True):
    """Unifies ``fit_pole`` and ``fit_girdle``."""
    lon, lat = _convert_measurements(data, measurement)
    vals, vecs = cov_eig(lon, lat, bidirectional)
    x, y, z = vecs[:, vec]
    s, d = stereonet_math.geographic2pole(*stereonet_math.cart2sph(x, y, z))
    return s[0], d[0]

def eigenvectors(*args, **kwargs):
    """
    Finds the 3 eigenvectors and eigenvalues of the 3D covariance matrix of a
    series of geometries.  This can be used to fit a plane/pole to a dataset or
    for shape fabric analysis (e.g. Flinn/Hsu plots).

    Input arguments will be interpreted as poles, lines, rakes, or "raw"
    longitudes and latitudes based on the *measurement* keyword argument.
    (Defaults to ``"poles"``.)

    Parameters
    ----------

    *args : 2 or 3 sequences of measurements
        By default, this will be expected to be ``strike`` & ``dip``, both
        array-like sequences representing poles to planes.  (Rake measurements
        require three parameters, thus the variable number of arguments.) The
        *measurement* kwarg controls how these arguments are interpreted.

    measurement : {'poles', 'lines', 'rakes', 'radians'}, optional
        Controls how the input arguments are interpreted. Defaults to
        ``"poles"``.  May be one of the following:

            ``"poles"`` : Arguments are assumed to be sequences of strikes and
                dips of planes. Poles to these planes are used for density
                contouring.
            ``"lines"`` : Arguments are assumed to be sequences of plunges and
                bearings of linear features.
            ``"rakes"`` : Arguments are assumed to be sequences of strikes,
                dips, and rakes along the plane.
            ``"radians"`` : Arguments are assumed to be "raw" longitudes and
                latitudes in the underlying projection's coordinate system.

    bidirectional : boolean, optional
        Whether or not the antipode of each measurement will be used in the
        calculation. For almost all use cases, it should. Defaults to True.

    Returns
    -------

    plunges, bearings, values : sequences of 3 floats each
        The plunges, bearings, and eigenvalues of the three eigenvectors of the
        covariance matrix of the input data.  The measurements are returned
        sorted in descending order relative to the eigenvalues. (i.e. The
        largest eigenvector/eigenvalue is first.)

    Examples
    --------

    Find the eigenvectors as plunge/bearing and eigenvalues of the 3D
    covariance matrix of a series of planar measurements:

        >>> strikes = [270, 65, 280, 300]
        >>> dips = [20, 15, 10, 5]
        >>> plu, azi, vals = mplstereonet.eigenvectors(strikes, dips)
    """
    lon, lat = _convert_measurements(args, kwargs.get('measurement', 'poles'))
    vals, vecs = cov_eig(lon, lat, kwargs.get('bidirectional', True))
    lon, lat = stereonet_math.cart2sph(*vecs)
    plunges, bearings = stereonet_math.geographic2plunge_bearing(lon, lat)
    # Largest eigenvalue first...
    return plunges[::-1], bearings[::-1], vals[::-1]

def cov_eig(lon, lat, bidirectional=True):
    lon = np.atleast_1d(np.squeeze(lon))
    lat = np.atleast_1d(np.squeeze(lat))
    if bidirectional:
        # Include antipodes in calculation...
        lon2, lat2 = stereonet_math.antipode(lon, lat)
        lon, lat = np.hstack([lon, lon2]), np.hstack([lat, lat2])
    xyz = np.column_stack(stereonet_math.sph2cart(lon, lat))
    cov = np.cov(xyz.T)
    eigvals, eigvecs = np.linalg.eigh(cov)
    order = eigvals.argsort()
    return eigvals[order], eigvecs[:, order]

def _convert_measurements(data, measurement):
    def do_nothing(x, y):
        return x, y
    func = {'poles':stereonet_math.pole,
            'lines':stereonet_math.line,
            'rakes':stereonet_math.rake,
            'radians':do_nothing}[measurement]
    return func(*data)

def find_mean_vector(*args, **kwargs):
    """
    Returns the mean vector for a set of measurments. By default, this expects
    the input to be plunges and bearings, but the type of input can be
    controlled through the ``measurement`` kwarg.

    Parameters
    ----------

    *args : 2 or 3 sequences of measurements
        By default, this will be expected to be ``plunge`` & ``bearing``, both
        array-like sequences representing linear features.  (Rake measurements
        require three parameters, thus the variable number of arguments.) The
        *measurement* kwarg controls how these arguments are interpreted.

    measurement : string, optional
        Controls how the input arguments are interpreted. Defaults to
        ``"lines"``.  May be one of the following:

            ``"poles"`` : strikes, dips
                Arguments are assumed to be sequences of strikes and dips of
                planes. Poles to these planes are used for analysis.
            ``"lines"`` : plunges, bearings
                Arguments are assumed to be sequences of plunges and bearings
                of linear features.
            ``"rakes"`` : strikes, dips, rakes
                Arguments are assumed to be sequences of strikes, dips, and
                rakes along the plane.
            ``"radians"`` : lon, lat
                Arguments are assumed to be "raw" longitudes and latitudes in
                the stereonet's underlying coordinate system.

    Returns
    -------

    mean_vector : tuple of two floats
        The plunge and bearing of the mean vector (in degrees).

    r_value : float
        The length of the mean vector (a value between 0 and 1).
    """
    lon, lat = _convert_measurements(args, kwargs.get('measurement', 'lines'))
    vector, r_value = stereonet_math.mean_vector(lon, lat)
    plunge, bearing = stereonet_math.geographic2plunge_bearing(*vector)
    return (plunge[0], bearing[0]), r_value

def find_fisher_stats(*args, **kwargs):
    """
    Returns the mean vector and summary statistics for a set of measurements.
    By default, this expects the input to be plunges and bearings, but the type
    of input can be controlled through the ``measurement`` kwarg.

    Parameters
    ----------
    *args : 2 or 3 sequences of measurements
        By default, this will be expected to be ``plunge`` & ``bearing``, both
        array-like sequences representing linear features.  (Rake measurements
        require three parameters, thus the variable number of arguments.) The
        *measurement* kwarg controls how these arguments are interpreted.

    conf : number
        The confidence level (0-100). Defaults to 95%, similar to 2 sigma.

    measurement : string, optional
        Controls how the input arguments are interpreted. Defaults to
        ``"lines"``.  May be one of the following:

            ``"poles"`` : strikes, dips
                Arguments are assumed to be sequences of strikes and dips of
                planes. Poles to these planes are used for analysis.
            ``"lines"`` : plunges, bearings
                Arguments are assumed to be sequences of plunges and bearings
                of linear features.
            ``"rakes"`` : strikes, dips, rakes
                Arguments are assumed to be sequences of strikes, dips, and
                rakes along the plane.
            ``"radians"`` : lon, lat
                Arguments are assumed to be "raw" longitudes and latitudes in
                the stereonet's underlying coordinate system.

    Returns
    -------

    mean_vector: tuple of two floats
        A set consisting of the plunge and bearing of the mean vector (in
        degrees).

    stats : tuple of three floats
        ``(r_value, confidence, kappa)``
        The ``r_value`` is the magnitude of the mean vector as a number between
        0 and 1.
        The ``confidence`` radius is the opening angle of a small circle that
        corresponds to the confidence in the calculated direction, and is
        dependent on the input ``conf``.
        The ``kappa`` value is the dispersion factor that quantifies the amount
        of dispersion of the given vectors, analgous to a variance/stddev.
    """
    # How the heck did this wind up as a separate function?
    lon, lat = _convert_measurements(args, kwargs.get('measurement', 'lines'))
    conf = kwargs.get('conf', 95)
    center, stats = stereonet_math.fisher_stats(lon, lat, conf)
    plunge, bearing = stereonet_math.geographic2plunge_bearing(*center)
    mean_vector = (plunge[0], bearing[0])
    return mean_vector, stats

def kmeans(*args, **kwargs):
    """
    Find centers of multi-modal clusters of data using a kmeans approach
    modified for spherical measurements.

    Parameters
    ----------

    *args : 2 or 3 sequences of measurements
        By default, this will be expected to be ``strike`` & ``dip``, both
        array-like sequences representing poles to planes.  (Rake measurements
        require three parameters, thus the variable number of arguments.) The
        ``measurement`` kwarg controls how these arguments are interpreted.

    num : int
        The number of clusters to find. Defaults to 2.

    bidirectional : bool
        Whether or not the measurements are bi-directional linear/planar
        features or directed vectors. Defaults to True.

    tolerance : float
        Iteration will continue until the centers have not changed by more
        than this amount. Defaults to 1e-5.

    measurement : string, optional
        Controls how the input arguments are interpreted. Defaults to
        ``"poles"``.  May be one of the following:

            ``"poles"`` : strikes, dips
                Arguments are assumed to be sequences of strikes and dips of
                planes. Poles to these planes are used for analysis.
            ``"lines"`` : plunges, bearings
                Arguments are assumed to be sequences of plunges and bearings
                of linear features.
            ``"rakes"`` : strikes, dips, rakes
                Arguments are assumed to be sequences of strikes, dips, and
                rakes along the plane.
            ``"radians"`` : lon, lat
                Arguments are assumed to be "raw" longitudes and latitudes in
                the stereonet's underlying coordinate system.

    Returns
    -------

    centers : An Nx2 array-like
        Longitude and latitude in radians of the centers of each cluster.
    """
    lon, lat = _convert_measurements(args, kwargs.get('measurement', 'poles'))
    num = kwargs.get('num', 2)
    bidirectional = kwargs.get('bidirectional', True)
    tolerance = kwargs.get('tolerance', 1e-5)

    points = lon, lat
    dist = lambda x: stereonet_math.angular_distance(x, points, bidirectional)

    center_lon = np.random.choice(lon, num)
    center_lat = np.random.choice(lat, num)
    centers = np.column_stack([center_lon, center_lat])

    while True:
        dists = np.array([dist(item) for item in centers]).T
        closest = dists.argmin(axis=1)

        new_centers = []
        for i in range(num):
            mask = mask = closest == i
            _, vecs = cov_eig(lon[mask], lat[mask], bidirectional)
            new_centers.append(stereonet_math.cart2sph(*vecs[:,-1]))

        if np.allclose(centers, new_centers, atol=tolerance):
            break
        else:
            centers = new_centers

    return centers

def apparent_dip(true_dip, azimuth_diff):
    """
    Calculate the apparent dip angle(s), given the true dip angle(s) and the
    azimuth (i.e. bearing) difference between the apparent dip direction(s) and
    true dip direction(s). All in degrees.

    Parameters
    ----------
    true_dip : number or sequence of numbers
        true dip angle(s) in degrees
    azimuth_diff : number or sequence of numbers
        azimuth difference between the apparent dip direction(s) and true dip
        direction(s), in degrees

    Returns
    -------
    apparent_dip : array
        apparent dip angle(s) in degrees
    """
    true_dip, azimuth_diff = np.atleast_1d(true_dip, azimuth_diff)
    azimuth_diff = np.radians(np.abs(azimuth_diff))
    true_dip = np.radians(true_dip)
    apparent_dip = np.arctan(np.cos(azimuth_diff)*np.tan(true_dip))
    return np.degrees(apparent_dip)

def azimuth_diff(true_dip, apparent_dip):
    """
    Calculate the absolute difference in azimuth (i.e. bearing) between true
    dip direction(s) and apparent dip direction(s), given the true dip angle(s)
    and the apparent dip angle(s). All in degrees.

    Parameters
    ----------
    true_dip : number or sequence of numbers
        true dip angle(s) in degrees
    apparent_dip : number or sequence of numbers
        apparent dip angle(s) in degrees

    Returns
    -------
    azimuth_diff : array
        azimuth difference between the apparent dip direction(s) and true dip
        direction(s)
    """
    true_dip, apparent_dip = np.atleast_1d(true_dip, apparent_dip)
    true_dip = np.radians(true_dip)
    apparent_dip = np.radians(apparent_dip)
    azimuth_diff = np.arccos(np.tan(apparent_dip)/np.tan(true_dip))
    return np.degrees(azimuth_diff)


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class S_EditDateBut : MonoBehaviour {
	public RectTransform labelPanel;
	public RectTransform inputPanel;
	public Sprite saveIcon;
	public Sprite editIcon;

	private RectTransform monthInput;
	private RectTransform dateInput;
	private RectTransform yearInput;

	private Text monthLabel;
	private Text dateLabel;
	private Text yearLabel;

	bool isEditMode = false;

	public void editDateClicked(){
		if(isEditMode){
			isEditMode = false;
			transform.FindChild("Icon").GetComponent<Image>().sprite = editIcon;
			this.GetComponent<Image>().color = new Color(1,1,1);
			labelPanel.gameObject.SetActive(true);
			inputPanel.gameObject.SetActive(false);

			establishRefToDateUIs();
			monthLabel.text = monthInput.GetComponent<InputField>().text;
			dateLabel.text = dateInput.GetComponent<InputField>().text;
			yearLabel.text = yearInput.GetComponent<InputField>().text;

			//save changes to the database
			SunLightWidget.Instance.InputData.updateDateMonYear(int.Parse(dateLabel.text), int.Parse(monthLabel.text), int.Parse(yearLabel.text));
			//save changes to xml
			SunLightWidget.Instance.saveDataToXML();
			//recalc sun angle
			SunLightWidget.Instance.calcSunCoordination();

		}else{//was not in edit mode, now in editmode
			isEditMode = true;

			transform.FindChild("Icon").GetComponent<Image>().sprite = saveIcon;
			this.GetComponent<Image>().color = new Color(0.67f, 0.67f, 0.67f);
			labelPanel.gameObject.SetActive(false);
			inputPanel.gameObject.SetActive(true);

			establishRefToDateUIs();
			monthInput.GetComponent<InputField>().text = monthLabel.text;
			dateInput.GetComponent<InputField>().text = dateLabel.text;
			yearInput.GetComponent<InputField>().text = yearLabel.text;

		}

	}

	//find the reference to the date input fields and date labels, run only once in each game
	void establishRefToDateUIs(){
		if(monthInput == null || dateInput == null || yearInput == null){
			monthInput = inputPanel.FindChild("MonthInput") as RectTransform;
			dateInput = inputPanel.FindChild("DateInput") as RectTransform;
			yearInput = inputPanel.FindChild("YearInput") as RectTransform;
		}

		if(monthLabel == null || dateLabel == null || yearLabel == null){
			monthLabel = labelPanel.FindChild("Month").GetComponent<Text>();
			dateLabel = labelPanel.FindChild("Date").GetComponent<Text>();
			yearLabel = labelPanel.FindChild("Year").GetComponent<Text>();
		}

		return;
	}
}

redpajama_set_name: RedPajamaGithub


text:
//Modify the solution of the previous problem to replace only whole words (not strings).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;

namespace _08.ReplaceWholeWord
{
    class ReplaceWholeWord
    {
        static void Main()
        {
            Regex wordRgx = new Regex("\bstart\b", RegexOptions.IgnoreCase);

            using (StreamReader sr = new StreamReader("../../input.txt"))
            {
                using (StreamWriter sw = new StreamWriter("../../output.txt"))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        sw.WriteLine(wordRgx.Replace(line, "finish"));
                    }
                }
            }
        }
    }
}


text:
package gw.plugin.ij.util.transform.java.Visitor;

import java.util.*;

public class SymbolTable {
  private LinkedList<Scope> globals;
  private LinkedList<Scope> locals;
  private HashSet<String> reservedWords;
  int counter;
  private String[] reserved = {"true", "false", "NaN", "Infinity", "and", "or", "not", "null", "length", "exists",
                              "in", "startswith", "contains", "where", "find", "var", "delegate", "represents",
                              "as", "typeof", "statictypeof", "typeis", "typeas", "package", "uses", "if", "else",
                              "except", "unless", "foreach", "for", "index", "iterator", "while", "do",
                              "continue", "break", "return", "construct", "function", "property", "get", "set",
                              "try", "catch", "finally", "this", "throw", "new", "switch", "case", "default",
                              "eval", "private", "internal", "protected", "public", "abstract", "override",
                              "hide", "final", "static", "extends", "transient", "implements", "readonly",
                              "class", "interface", "structure", "enum", "super", "outer", "execution", "request", "session",
                              "application", "void", "block", "enhancement", "classpath", "typeloader", "using", "now"};

  private class Scope {
    String clazz;
    Set<String> idents;
    Map<String, String> conversions;

    Scope() {
      idents = new HashSet<String>();
      conversions = new HashMap<String, String>();
    }

    Scope(String clazz) {
      this.clazz = clazz;
      idents = new HashSet<String>();
      conversions = new HashMap<String, String>();
    }
  }

  public SymbolTable() {
    counter = 0;
    globals = new LinkedList<Scope>();
    locals = new LinkedList<Scope>();
    reservedWords = new HashSet<String>();
    for(String word : reserved) {
      reservedWords.add(word);
    }
  }

  void pushGlobalScope(String clazz) {
    globals.add(new Scope(clazz));
  }

  void pushLocalScope() {
    locals.add(new Scope());
  }

  public String convertLocalSymbol(String ident) {
    Scope s;
    int end = locals.size() - 1;
    String converted = null;

    while (end >= 0) {
      s = locals.get(end);
      converted = s.conversions.get(ident);
      if (converted != null) {
        break;
      }
      end--;
    }
    return converted == null ? ident : converted;
  }

  String addLocally(String ident) {
    String original = ident;
    int i = 0;
    while (isDefinedLocally(ident) || isDefinedGlobally(ident) || isReserved(ident)) {
      ident = original + "_" + i;
      i++;
    }
    Scope last;
    try {
      last = locals.getLast();
    } catch (NoSuchElementException ex) {
      throw new RuntimeException("Error: adding a new identifier in an empty scope." +
              "Have you forgotten to pushNewScope() first?");
    }
    last.idents.add(ident);
    if (!original.equals(ident)) {
      last.conversions.put(original, ident);
    }
    return ident;
  }

  private boolean isReserved(String ident) {
    return reservedWords.contains(ident);
  }

  void popLocalScope() {
    try {
      locals.removeLast();
    } catch (NoSuchElementException ex) {
      throw new RuntimeException("Error: the scope's stack is empty." +
              "Have you forgotten to pushNewScope() first?");
    }
  }

  void popGlobalScope() {
    try {
      globals.removeLast();
    } catch (NoSuchElementException ex) {
      throw new RuntimeException("Error: the scope's stack is empty." +
              "Have you forgotten to pushNewScope() first?");
    }
  }

  private boolean isDefinedLocally(String ident) {
    int end = locals.size() - 1;
    while (end >= 0) {
      Scope s = locals.get(end);
      if (s.idents.contains(ident)) {
        return true;
      }
      end--;
    }
    return false;
  }

  private boolean isDefinedGlobally(String ident) {
    int end = globals.size() - 1;
    while (end >= 0) {
      Scope s = globals.get(end);
      if (s.idents.contains(ident)) {
        return true;
      }
      end--;
    }
    return false;
  }

  public int getClassLevelFromCurrent(String clazz) {
    int end = globals.size() - 1;
    int level = end;
    while (end >= 0) {
      Scope s = globals.get(end);
      if (s.clazz.equals(clazz)) {
        level -= end;
        break;
      }
      end--;
    }
    return level;
  }

  public String addGlobally(String ident) {
    Scope last;
    try {
      last = globals.getLast();
    } catch (NoSuchElementException ex) {
      throw new RuntimeException("Error: adding a new identifier in an empty scope." +
              "Have you forgotten to pushNewScope() first?");
    }
    last.idents.add(ident);
    return ident;
  }
}


text:
/*jshint node:true */
/*global describe:false, it:false */
"use strict";

var Orchestrator = require('../');
var should = require('chai').should();

describe('orchestrator', function () {
  describe('_resetSpecificTasks()', function () {

    it('should set done = false on specified done tasks', function (done) {
      var orchestrator, task1, task2;

      // Arrange
      task1 = {
        name: 'test1',
        fn: function () {
        },
        done: true
      };
      task2 = {
        name: 'test2',
        fn: function () {
        },
        done: true
      };

      // the thing under test
      orchestrator = new Orchestrator();
      orchestrator.tasks = {
        test1: task1,
        test2: task2
      };

      // Act
      orchestrator._resetSpecificTasks(['test1', 'test2']);

      // Assert
      task1.done.should.equal(false);
      task2.done.should.equal(false);
      done();
    });

    it('should not set done = false if done does not exist', function (done) {
      var orchestrator, task1, task2;

      // Arrange
      task1 = {
        name: 'test1',
        fn: function () {
        }
        // no done
      };
      task2 = {
        name: 'test2',
        fn: function () {
        }
        // no done
      };

      // the thing under test
      orchestrator = new Orchestrator();
      orchestrator.tasks = {
        test1: task1,
        test2: task2
      };

      // Act
      orchestrator._resetSpecificTasks(['test1', 'test2']);

      // Assert
      should.not.exist(task1.done);
      should.not.exist(task2.done);
      done();
    });

    it('should set done = false on done dependency', function (done) {
      var orchestrator, task, dep;

      // Arrange
      task = {
        name: 'test',
        dep: ['dep'],
        fn: function () {
        }
        // no done though irrelevant to current test
      };
      dep = {
        name: 'dep',
        fn: function () {
        },
        done: true
      };

      // the thing under test
      orchestrator = new Orchestrator();
      orchestrator.tasks = {
        test: task,
        dep: dep
      };

      // Act
      orchestrator._resetSpecificTasks(['test']);

      // Assert
      dep.done.should.equal(false);
      done();
    });

    it('should not set done on irrelevant tasks', function (done) {
      var orchestrator, task, irrelevant;

      // Arrange
      task = {
        name: 'test',
        fn: function () {
        }
        // no done though irrelevant to current test
      };
      irrelevant = {
        name: 'irrelevant',
        fn: function () {
        },
        done: true
      };

      // the thing under test
      orchestrator = new Orchestrator();
      orchestrator.tasks = {
        test: task,
        irrelevant: irrelevant
      };

      // Act
      orchestrator._resetSpecificTasks(['test']);

      // Assert
      irrelevant.done.should.equal(true);
      done();
    });

    it('should not die if dependency does not exist', function (done) {
      var orchestrator, task;

      // Arrange
      task = {
        name: 'test',
        dep: ['dep'], // dep doesn't exist
        fn: function () {
        }
        // no done though irrelevant to current test
      };

      // the thing under test
      orchestrator = new Orchestrator();
      orchestrator.tasks = {
        test: task
      };

      // Act
      orchestrator._resetSpecificTasks(['test']);

      // Assert
      // we're still here so it worked
      done();
    });

  });
});


text:
default['nginx']['fastcgi_cache']['enabled'] = false
default['nginx']['fastcgi_cache']['path'] = "/tmp/nginx/cache"
default['nginx']['fastcgi_cache']['keys_zone_name'] = "NGINX_CACHE"
default['nginx']['fastcgi_cache']['keys_zone_size'] = "100"
default['nginx']['fastcgi_cache']['key_scheme'] = "$scheme$request_method$host$request_uri"


text:
class GURL;

namespace base {
class Histogram;
class TimeTicks;
}  // namespace base

namespace net {

class CookieList;

// The cookie monster is the system for storing and retrieving cookies. It has
// an in-memory list of all cookies, and synchronizes non-session cookies to an
// optional permanent storage that implements the PersistentCookieStore
// interface.
//
// This class IS thread-safe. Normally, it is only used on the I/O thread, but
// is also accessed directly through Automation for UI testing.
//
// All cookie tasks are handled asynchronously. Tasks may be deferred if
// all affected cookies are not yet loaded from the backing store. Otherwise,
// the callback may be invoked immediately (prior to return of the asynchronous
// function).
//
// A cookie task is either pending loading of the entire cookie store, or
// loading of cookies for a specfic domain key(eTLD+1). In the former case, the
// cookie task will be queued in queue_ while PersistentCookieStore chain loads
// the cookie store on DB thread. In the latter case, the cookie task will be
// queued in tasks_queued_ while PermanentCookieStore loads cookies for the
// specified domain key(eTLD+1) on DB thread.
//
// Callbacks are guaranteed to be invoked on the calling thread.
//
// TODO(deanm) Implement CookieMonster, the cookie database.
//  - Verify that our domain enforcement and non-dotted handling is correct
class NET_EXPORT CookieMonster : public CookieStore {
 public:
  class CanonicalCookie;
  class Delegate;
  class ParsedCookie;
  class PersistentCookieStore;

  // Terminology:
  //    * The 'top level domain' (TLD) of an internet domain name is
  //      the terminal "." free substring (e.g. "com" for google.com
  //      or world.std.com).
  //    * The 'effective top level domain' (eTLD) is the longest
  //      "." initiated terminal substring of an internet domain name
  //      that is controlled by a general domain registrar.
  //      (e.g. "co.uk" for news.bbc.co.uk).
  //    * The 'effective top level domain plus one' (eTLD+1) is the
  //      shortest "." delimited terminal substring of an internet
  //      domain name that is not controlled by a general domain
  //      registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
  //      "google.com" for news.google.com).  The general assumption
  //      is that all hosts and domains under an eTLD+1 share some
  //      administrative control.

  // CookieMap is the central data structure of the CookieMonster.  It
  // is a map whose values are pointers to CanonicalCookie data
  // structures (the data structures are owned by the CookieMonster
  // and must be destroyed when removed from the map).  There are two
  // possible keys for the map, controlled on a per-CookieMonster basis
  // by expiry_and_key_scheme_/SetExpiryAndKeyScheme()
  // (defaulted by expiry_and_key_default_):

  // If expiry_and_key_scheme_ is EKS_KEEP_RECENT_AND_PURGE_ETLDP1
  // (default), then the key is based on the effective domain of the
  // cookies.  If the domain of the cookie has an eTLD+1, that is the
  // key for the map.  If the domain of the cookie does not have an eTLD+1,
  // the key of the map is the host the cookie applies to (it is not
  // legal to have domain cookies without an eTLD+1).  This rule
  // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
  // This behavior is the same as the behavior in Firefox v 3.6.10.

  // If use_effective_domain_key_scheme_ is EKS_DISCARD_RECENT_AND_PURGE_DOMAIN,
  // then the key is just the domain of the cookie.  Eventually, this
  // option will be removed.

  // NOTE(deanm):
  // I benchmarked hash_multimap vs multimap.  We're going to be query-heavy
  // so it would seem like hashing would help.  However they were very
  // close, with multimap being a tiny bit faster.  I think this is because
  // our map is at max around 1000 entries, and the additional complexity
  // for the hashing might not overcome the O(log(1000)) for querying
  // a multimap.  Also, multimap is standard, another reason to use it.
  // TODO(rdsmith): This benchmark should be re-done now that we're allowing
  // subtantially more entries in the map.
  typedef std::multimap<std::string, CanonicalCookie*> CookieMap;
  typedef std::pair<CookieMap::iterator, CookieMap::iterator> CookieMapItPair;

  // The key and expiry scheme to be used by the monster.
  // EKS_KEEP_RECENT_AND_PURGE_ETLDP1 means to use
  // the new key scheme based on effective domain and save recent cookies
  // in global garbage collection.  EKS_DISCARD_RECENT_AND_PURGE_DOMAIN
  // means to use the old key scheme based on full domain and be ruthless
  // about purging.
  enum ExpiryAndKeyScheme {
    EKS_KEEP_RECENT_AND_PURGE_ETLDP1,
    EKS_DISCARD_RECENT_AND_PURGE_DOMAIN,
    EKS_LAST_ENTRY
  };

  // The store passed in should not have had Init() called on it yet. This
  // class will take care of initializing it. The backing store is NOT owned by
  // this class, but it must remain valid for the duration of the cookie
  // monster's existence. If |store| is NULL, then no backing store will be
  // updated. If |delegate| is non-NULL, it will be notified on
  // creation/deletion of cookies.
  CookieMonster(PersistentCookieStore* store, Delegate* delegate);

  // Only used during unit testing.
  CookieMonster(PersistentCookieStore* store,
                Delegate* delegate,
                int last_access_threshold_milliseconds);

  // Parses the string with the cookie time (very forgivingly).
  static base::Time ParseCookieTime(const std::string& time_string);

  // Helper function that adds all cookies from |list| into this instance.
  bool InitializeFrom(const CookieList& list);

  typedef base::Callback<void(const CookieList& cookies)> GetCookieListCallback;
  typedef base::Callback<void(bool success)> DeleteCookieCallback;

  // Sets a cookie given explicit user-provided cookie attributes. The cookie
  // name, value, domain, etc. are each provided as separate strings. This
  // function expects each attribute to be well-formed. It will check for
  // disallowed characters (e.g. the ';' character is disallowed within the
  // cookie value attribute) and will return false without setting the cookie
  // if such characters are found.
  void SetCookieWithDetailsAsync(const GURL& url,
                                 const std::string& name,
                                 const std::string& value,
                                 const std::string& domain,
                                 const std::string& path,
                                 const base::Time& expiration_time,
                                 bool secure, bool http_only,
                                 const SetCookiesCallback& callback);

  // Returns all the cookies, for use in management UI, etc. This does not mark
  // the cookies as having been accessed.
  // The returned cookies are ordered by longest path, then by earliest
  // creation date.
  void GetAllCookiesAsync(const GetCookieListCallback& callback);

  // Returns all the cookies, for use in management UI, etc. Filters results
  // using given url scheme, host / domain and path and options. This does not
  // mark the cookies as having been accessed.
  // The returned cookies are ordered by longest path, then earliest
  // creation date.
  void GetAllCookiesForURLWithOptionsAsync(
      const GURL& url,
      const CookieOptions& options,
      const GetCookieListCallback& callback);

  // Invokes GetAllCookiesForURLWithOptions with options set to include HTTP
  // only cookies.
  void GetAllCookiesForURLAsync(const GURL& url,
                                const GetCookieListCallback& callback);

  // Deletes all of the cookies.
  void DeleteAllAsync(const DeleteCallback& callback);

  // Deletes all cookies that match the host of the given URL
  // regardless of path.  This includes all http_only and secure cookies,
  // but does not include any domain cookies that may apply to this host.
  // Returns the number of cookies deleted.
  void DeleteAllForHostAsync(const GURL& url,
                             const DeleteCallback& callback);

  // Deletes one specific cookie.
  void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
                                  const DeleteCookieCallback& callback);

  // Override the default list of schemes that are allowed to be set in
  // this cookie store.  Calling his overrides the value of
  // "enable_file_scheme_".
  // If this this method is called, it must be called before first use of
  // the instance (i.e. as part of the instance initialization process).
  void SetCookieableSchemes(const char* schemes[], size_t num_schemes);

  // Overrides the default key and expiry scheme.  See comments
  // before CookieMap and Garbage collection constants for details.  This
  // function must be called before initialization.
  void SetExpiryAndKeyScheme(ExpiryAndKeyScheme key_scheme);

  // Instructs the cookie monster to not delete expired cookies. This is used
  // in cases where the cookie monster is used as a data structure to keep
  // arbitrary cookies.
  void SetKeepExpiredCookies();

  // Delegates the call to set the |clear_local_store_on_exit_| flag of the
  // PersistentStore if it exists.
  void SetClearPersistentStoreOnExit(bool clear_local_store);

  // There are some unknowns about how to correctly handle file:// cookies,
  // and our implementation for this is not robust enough. This allows you
  // to enable support, but it should only be used for testing. Bug 1157243.
  // Must be called before creating a CookieMonster instance.
  static void EnableFileScheme();

  // Flush the backing store (if any) to disk and post the given callback when
  // done.
  // WARNING: THE CALLBACK WILL RUN ON A RANDOM THREAD. IT MUST BE THREAD SAFE.
  // It may be posted to the current thread, or it may run on the thread that
  // actually does the flushing. Your Task should generally post a notification
  // to the thread you actually want to be notified on.
  void FlushStore(const base::Closure& callback);

  // CookieStore implementation.

  // Sets the cookies specified by |cookie_list| returned from |url|
  // with options |options| in effect.
  virtual void SetCookieWithOptionsAsync(
      const GURL& url,
      const std::string& cookie_line,
      const CookieOptions& options,
      const SetCookiesCallback& callback) OVERRIDE;

  // Gets all cookies that apply to |url| given |options|.
  // The returned cookies are ordered by longest path, then earliest
  // creation date.
  virtual void GetCookiesWithOptionsAsync(
      const GURL& url,
      const CookieOptions& options,
      const GetCookiesCallback& callback) OVERRIDE;

  virtual void GetCookiesWithInfoAsync(
      const GURL& url,
      const CookieOptions& options,
      const GetCookieInfoCallback& callback) OVERRIDE;

  // Deletes all cookies with that might apply to |url| that has |cookie_name|.
  virtual void DeleteCookieAsync(
      const GURL& url, const std::string& cookie_name,
      const base::Closure& callback) OVERRIDE;

  // Deletes all of the cookies that have a creation_date greater than or equal
  // to |delete_begin| and less than |delete_end|
  // Returns the number of cookies that have been deleted.
  virtual void DeleteAllCreatedBetweenAsync(
      const base::Time& delete_begin,
      const base::Time& delete_end,
      const DeleteCallback& callback) OVERRIDE;

  virtual CookieMonster* GetCookieMonster() OVERRIDE;

  // Enables writing session cookies into the cookie database. If this this
  // method is called, it must be called before first use of the instance
  // (i.e. as part of the instance initialization process).
  void SetPersistSessionCookies(bool persist_session_cookies);

  // Protects session cookies from deletion on shutdown.
  void SaveSessionCookies();

  // Debugging method to perform various validation checks on the map.
  // Currently just checking that there are no null CanonicalCookie pointers
  // in the map.
  // Argument |arg| is to allow retaining of arbitrary data if the CHECKs
  // in the function trip.  TODO(rdsmith):Remove hack.
  void ValidateMap(int arg);

  // The default list of schemes the cookie monster can handle.
  static const char* kDefaultCookieableSchemes[];
  static const int kDefaultCookieableSchemesCount;

 private:
  // For queueing the cookie monster calls.
  class CookieMonsterTask;
  class DeleteAllCreatedBetweenTask;
  class DeleteAllForHostTask;
  class DeleteAllTask;
  class DeleteCookieTask;
  class DeleteCanonicalCookieTask;
  class GetAllCookiesForURLWithOptionsTask;
  class GetAllCookiesTask;
  class GetCookiesWithOptionsTask;
  class GetCookiesWithInfoTask;
  class SetCookieWithDetailsTask;
  class SetCookieWithOptionsTask;

  // Testing support.
  // For SetCookieWithCreationTime.
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
                           TestCookieDeleteAllCreatedBetweenTimestamps);

  // For gargage collection constants.
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);

  // For validation of key values.
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);

  // For FindCookiesForKey.
  FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);

  // Internal reasons for deletion, used to populate informative histograms
  // and to provide a public cause for onCookieChange notifications.
  //
  // If you add or remove causes from this list, please be sure to also update
  // the Delegate::ChangeCause mapping inside ChangeCauseMapping. Moreover,
  // these are used as array indexes, so avoid reordering to keep the
  // histogram buckets consistent. New items (if necessary) should be added
  // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
  enum DeletionCause {
    DELETE_COOKIE_EXPLICIT = 0,
    DELETE_COOKIE_OVERWRITE,
    DELETE_COOKIE_EXPIRED,
    DELETE_COOKIE_EVICTED,
    DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
    DELETE_COOKIE_DONT_RECORD,  // e.g. For final cleanup after flush to store.
    DELETE_COOKIE_EVICTED_DOMAIN,
    DELETE_COOKIE_EVICTED_GLOBAL,

    // Cookies evicted during domain level garbage collection that
    // were accessed longer ago than kSafeFromGlobalPurgeDays
    DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,

    // Cookies evicted during domain level garbage collection that
    // were accessed more recently than kSafeFromGlobalPurgeDays
    // (and thus would have been preserved by global garbage collection).
    DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,

    // A common idiom is to remove a cookie by overwriting it with an
    // already-expired expiration date. This captures that case.
    DELETE_COOKIE_EXPIRED_OVERWRITE,

    DELETE_COOKIE_LAST_ENTRY
  };

  // Cookie garbage collection thresholds.  Based off of the Mozilla defaults.
  // When the number of cookies gets to k{Domain,}MaxCookies
  // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
  // It might seem scary to have a high purge value, but really it's not.
  // You just make sure that you increase the max to cover the increase
  // in purge, and we would have been purging the same amount of cookies.
  // We're just going through the garbage collection process less often.
  // Note that the DOMAIN values are per eTLD+1; see comment for the
  // CookieMap typedef.  So, e.g., the maximum number of cookies allowed for
  // google.com and all of its subdomains will be 150-180.
  //
  // If the expiry and key scheme follows firefox standards (default,
  // set by SetExpiryAndKeyScheme()), any cookies accessed more recently
  // than kSafeFromGlobalPurgeDays will not be evicted by global garbage
  // collection, even if we have more than kMaxCookies.  This does not affect
  // domain garbage collection.
  //
  // Present in .h file to make accessible to tests through FRIEND_TEST.
  // Actual definitions are in cookie_monster.cc.
  static const size_t kDomainMaxCookies;
  static const size_t kDomainPurgeCookies;
  static const size_t kMaxCookies;
  static const size_t kPurgeCookies;

  // The number of days since last access that cookies will not be subject
  // to global garbage collection.
  static const int kSafeFromGlobalPurgeDays;

  // Default value for key and expiry scheme scheme.
  static const ExpiryAndKeyScheme expiry_and_key_default_ =
      EKS_KEEP_RECENT_AND_PURGE_ETLDP1;

  // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
  static const int kRecordStatisticsIntervalSeconds = 10 * 60;

  virtual ~CookieMonster();

  // The following are synchronous calls to which the asynchronous methods
  // delegate either immediately (if the store is loaded) or through a deferred
  // task (if the store is not yet loaded).
  bool SetCookieWithDetails(const GURL& url,
                            const std::string& name,
                            const std::string& value,
                            const std::string& domain,
                            const std::string& path,
                            const base::Time& expiration_time,
                            bool secure, bool http_only);

  CookieList GetAllCookies();

  CookieList GetAllCookiesForURLWithOptions(const GURL& url,
                                            const CookieOptions& options);

  CookieList GetAllCookiesForURL(const GURL& url);

  int DeleteAll(bool sync_to_store);

  int DeleteAllCreatedBetween(const base::Time& delete_begin,
                              const base::Time& delete_end);

  int DeleteAllForHost(const GURL& url);

  bool DeleteCanonicalCookie(const CanonicalCookie& cookie);

  bool SetCookieWithOptions(const GURL& url,
                            const std::string& cookie_line,
                            const CookieOptions& options);

  std::string GetCookiesWithOptions(const GURL& url,
                                    const CookieOptions& options);

  void GetCookiesWithInfo(const GURL& url,
                          const CookieOptions& options,
                          std::string* cookie_line,
                          std::vector<CookieInfo>* cookie_infos);

  void DeleteCookie(const GURL& url, const std::string& cookie_name);

  bool SetCookieWithCreationTime(const GURL& url,
                                 const std::string& cookie_line,
                                 const base::Time& creation_time);

  // Called by all non-static functions to ensure that the cookies store has
  // been initialized. This is not done during creating so it doesn't block
  // the window showing.
  // Note: this method should always be called with lock_ held.
  void InitIfNecessary() {
    if (!initialized_) {
      if (store_) {
        InitStore();
      } else {
        loaded_ = true;
      }
      initialized_ = true;
    }
  }

  // Initializes the backing store and reads existing cookies from it.
  // Should only be called by InitIfNecessary().
  void InitStore();

  // Stores cookies loaded from the backing store and invokes any deferred
  // calls. |beginning_time| should be the moment PersistentCookieStore::Load
  // was invoked and is used for reporting histogram_time_blocked_on_load_.
  // See PersistentCookieStore::Load for details on the contents of cookies.
  void OnLoaded(base::TimeTicks beginning_time,
                const std::vector<CanonicalCookie*>& cookies);

  // Stores cookies loaded from the backing store and invokes the deferred
  // task(s) pending loading of cookies associated with the domain key
  // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
  // loaded from DB. See PersistentCookieStore::Load for details on the contents
  // of cookies.
  void OnKeyLoaded(
    const std::string& key,
    const std::vector<CanonicalCookie*>& cookies);

  // Stores the loaded cookies.
  void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);

  // Invokes deferred calls.
  void InvokeQueue();

  // Checks that |cookies_| matches our invariants, and tries to repair any
  // inconsistencies. (In other words, it does not have duplicate cookies).
  void EnsureCookiesMapIsValid();

  // Checks for any duplicate cookies for CookieMap key |key| which lie between
  // |begin| and |end|. If any are found, all but the most recent are deleted.
  // Returns the number of duplicate cookies that were deleted.
  int TrimDuplicateCookiesForKey(const std::string& key,
                                 CookieMap::iterator begin,
                                 CookieMap::iterator end);

  void SetDefaultCookieableSchemes();

  void FindCookiesForHostAndDomain(const GURL& url,
                                   const CookieOptions& options,
                                   bool update_access_time,
                                   std::vector<CanonicalCookie*>* cookies);

  void FindCookiesForKey(const std::string& key,
                         const GURL& url,
                         const CookieOptions& options,
                         const base::Time& current,
                         bool update_access_time,
                         std::vector<CanonicalCookie*>* cookies);

  // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
  // If |skip_httponly| is true, httponly cookies will not be deleted.  The
  // return value with be true if |skip_httponly| skipped an httponly cookie.
  // |key| is the key to find the cookie in cookies_; see the comment before
  // the CookieMap typedef for details.
  // NOTE: There should never be more than a single matching equivalent cookie.
  bool DeleteAnyEquivalentCookie(const std::string& key,
                                 const CanonicalCookie& ecc,
                                 bool skip_httponly,
                                 bool already_expired);

  // Takes ownership of *cc.
  void InternalInsertCookie(const std::string& key,
                            CanonicalCookie* cc,
                            bool sync_to_store);

  // Helper function that sets cookies with more control.
  // Not exposed as we don't want callers to have the ability
  // to specify (potentially duplicate) creation times.
  bool SetCookieWithCreationTimeAndOptions(const GURL& url,
                                           const std::string& cookie_line,
                                           const base::Time& creation_time,
                                           const CookieOptions& options);

  // Helper function that sets a canonical cookie, deleting equivalents and
  // performing garbage collection.
  bool SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
                          const base::Time& creation_time,
                          const CookieOptions& options);

  void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
                                      const base::Time& current_time);

  // |deletion_cause| argument is used for collecting statistics and choosing
  // the correct Delegate::ChangeCause for OnCookieChanged notifications.
  void InternalDeleteCookie(CookieMap::iterator it, bool sync_to_store,
                            DeletionCause deletion_cause);

  // If the number of cookies for CookieMap key |key|, or globally, are
  // over the preset maximums above, garbage collect, first for the host and
  // then globally.  See comments above garbage collection threshold
  // constants for details.
  //
  // Returns the number of cookies deleted (useful for debugging).
  int GarbageCollect(const base::Time& current, const std::string& key);

  // Helper for GarbageCollect(); can be called directly as well.  Deletes
  // all expired cookies in |itpair|.  If |cookie_its| is non-NULL, it is
  // populated with all the non-expired cookies from |itpair|.
  //
  // Returns the number of cookies deleted.
  int GarbageCollectExpired(const base::Time& current,
                            const CookieMapItPair& itpair,
                            std::vector<CookieMap::iterator>* cookie_its);

  // Helper for GarbageCollect().  Deletes all cookies in the list
  // that were accessed before |keep_accessed_after|, using DeletionCause
  // |cause|.  If |keep_accessed_after| is null, deletes all cookies in the
  // list.  Returns the number of cookies deleted.
  int GarbageCollectDeleteList(const base::Time& current,
                               const base::Time& keep_accessed_after,
                               DeletionCause cause,
                               std::vector<CookieMap::iterator>& cookie_its);

  // Find the key (for lookup in cookies_) based on the given domain.
  // See comment on keys before the CookieMap typedef.
  std::string GetKey(const std::string& domain) const;

  bool HasCookieableScheme(const GURL& url);

  // Statistics support

  // This function should be called repeatedly, and will record
  // statistics if a sufficient time period has passed.
  void RecordPeriodicStats(const base::Time& current_time);

  // Initialize the above variables; should only be called from
  // the constructor.
  void InitializeHistograms();

  // The resolution of our time isn't enough, so we do something
  // ugly and increment when we've seen the same time twice.
  base::Time CurrentTime();

  // Runs the task if, or defers the task until, the full cookie database is
  // loaded.
  void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);

  // Runs the task if, or defers the task until, the cookies for the given URL
  // are loaded.
  void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
    const GURL& url);

  // Histogram variables; see CookieMonster::InitializeHistograms() in
  // cookie_monster.cc for details.
  base::Histogram* histogram_expiration_duration_minutes_;
  base::Histogram* histogram_between_access_interval_minutes_;
  base::Histogram* histogram_evicted_last_access_minutes_;
  base::Histogram* histogram_count_;
  base::Histogram* histogram_domain_count_;
  base::Histogram* histogram_etldp1_count_;
  base::Histogram* histogram_domain_per_etldp1_count_;
  base::Histogram* histogram_number_duplicate_db_cookies_;
  base::Histogram* histogram_cookie_deletion_cause_;
  base::Histogram* histogram_time_get_;
  base::Histogram* histogram_time_mac_;
  base::Histogram* histogram_time_blocked_on_load_;

  CookieMap cookies_;

  // Indicates whether the cookie store has been initialized. This happens
  // lazily in InitStoreIfNecessary().
  bool initialized_;

  // Indicates whether loading from the backend store is completed and
  // calls may be immediately processed.
  bool loaded_;

  // List of domain keys that have been loaded from the DB.
  std::set<std::string> keys_loaded_;

  // Map of domain keys to their associated task queues. These tasks are blocked
  // until all cookies for the associated domain key eTLD+1 are loaded from the
  // backend store.
  std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask> > >
    tasks_queued_;

  // Queues tasks that are blocked until all cookies are loaded from the backend
  // store.
  std::queue<scoped_refptr<CookieMonsterTask> > queue_;

  // Indicates whether this cookie monster uses the new effective domain
  // key scheme or not.
  ExpiryAndKeyScheme expiry_and_key_scheme_;

  scoped_refptr<PersistentCookieStore> store_;

  base::Time last_time_seen_;

  // Minimum delay after updating a cookie's LastAccessDate before we will
  // update it again.
  const base::TimeDelta last_access_threshold_;

  // Approximate date of access time of least recently accessed cookie
  // in |cookies_|.  Note that this is not guaranteed to be accurate, only a)
  // to be before or equal to the actual time, and b) to be accurate
  // immediately after a garbage collection that scans through all the cookies.
  // This value is used to determine whether global garbage collection might
  // find cookies to purge.
  // Note: The default Time() constructor will create a value that compares
  // earlier than any other time value, which is wanted.  Thus this
  // value is not initialized.
  base::Time earliest_access_time_;

  // During loading, holds the set of all loaded cookie creation times. Used to
  // avoid ever letting cookies with duplicate creation times into the store;
  // that way we don't have to worry about what sections of code are safe
  // to call while it's in that state.
  std::set<int64> creation_times_;

  std::vector<std::string> cookieable_schemes_;

  scoped_refptr<Delegate> delegate_;

  // Lock for thread-safety
  base::Lock lock_;

  base::Time last_statistic_record_time_;

  bool keep_expired_cookies_;
  bool persist_session_cookies_;

  static bool enable_file_scheme_;

  DISALLOW_COPY_AND_ASSIGN(CookieMonster);
};

class NET_EXPORT CookieMonster::CanonicalCookie {
 public:

  // These constructors do no validation or canonicalization of their inputs;
  // the resulting CanonicalCookies should not be relied on to be canonical
  // unless the caller has done appropriate validation and canonicalization
  // themselves.
  CanonicalCookie();
  CanonicalCookie(const GURL& url,
                  const std::string& name,
                  const std::string& value,
                  const std::string& domain,
                  const std::string& path,
                  const std::string& mac_key,
                  const std::string& mac_algorithm,
                  const base::Time& creation,
                  const base::Time& expiration,
                  const base::Time& last_access,
                  bool secure,
                  bool httponly,
                  bool has_expires,
                  bool is_persistent);

  // This constructor does canonicalization but not validation.
  // The result of this constructor should not be relied on in contexts
  // in which pre-validation of the ParsedCookie has not been done.
  CanonicalCookie(const GURL& url, const ParsedCookie& pc);

  ~CanonicalCookie();

  // Supports the default copy constructor.

  // Creates a canonical cookie from parsed cookie.
  // Canonicalizes and validates inputs.  May return NULL if an attribute
  // value is invalid.
  static CanonicalCookie* Create(const GURL& url,
                                 const ParsedCookie& pc);

  // Creates a canonical cookie from unparsed attribute values.
  // Canonicalizes and validates inputs.  May return NULL if an attribute
  // value is invalid.
  static CanonicalCookie* Create(const GURL& url,
                                 const std::string& name,
                                 const std::string& value,
                                 const std::string& domain,
                                 const std::string& path,
                                 const std::string& mac_key,
                                 const std::string& mac_algorithm,
                                 const base::Time& creation,
                                 const base::Time& expiration,
                                 bool secure,
                                 bool http_only,
                                 bool is_persistent);

  const std::string& Source() const { return source_; }
  const std::string& Name() const { return name_; }
  const std::string& Value() const { return value_; }
  const std::string& Domain() const { return domain_; }
  const std::string& Path() const { return path_; }
  const std::string& MACKey() const { return mac_key_; }
  const std::string& MACAlgorithm() const { return mac_algorithm_; }
  const base::Time& CreationDate() const { return creation_date_; }
  const base::Time& LastAccessDate() const { return last_access_date_; }
  bool DoesExpire() const { return has_expires_; }
#if defined(OS_ANDROID)
  // Android can shut down our app at any time, so we persist session cookies.
  bool IsPersistent() const { return true; }
#else
  bool IsPersistent() const { return is_persistent_; }
#endif
  bool IsSessionCookie() const { return !DoesExpire(); }
  const base::Time& ExpiryDate() const { return expiry_date_; }
  bool IsSecure() const { return secure_; }
  bool IsHttpOnly() const { return httponly_; }
  bool IsDomainCookie() const {
    return !domain_.empty() && domain_[0] == '.'; }
  bool IsHostCookie() const { return !IsDomainCookie(); }

  bool IsExpired(const base::Time& current) {
    return has_expires_ && current >= expiry_date_;
  }

  // Are the cookies considered equivalent in the eyes of RFC 2965.
  // The RFC says that name must match (case-sensitive), domain must
  // match (case insensitive), and path must match (case sensitive).
  // For the case insensitive domain compare, we rely on the domain
  // having been canonicalized (in
  // GetCookieDomainWithString->CanonicalizeHost).
  bool IsEquivalent(const CanonicalCookie& ecc) const {
    // It seems like it would make sense to take secure and httponly into
    // account, but the RFC doesn't specify this.
    // NOTE: Keep this logic in-sync with TrimDuplicateCookiesForHost().
    return (name_ == ecc.Name() && domain_ == ecc.Domain()
            && path_ == ecc.Path());
  }

  void SetLastAccessDate(const base::Time& date) {
    last_access_date_ = date;
  }

  bool IsOnPath(const std::string& url_path) const;
  bool IsDomainMatch(const std::string& scheme, const std::string& host) const;

  std::string DebugString() const;

  // Returns the cookie source when cookies are set for |url|.  This function
  // is public for unit test purposes only.
  static std::string GetCookieSourceFromURL(const GURL& url);

 private:
  // Gives the session cookie an expiration time if needed
  void SetSessionCookieExpiryTime();

  // The source member of a canonical cookie is the origin of the URL that tried
  // to set this cookie, minus the port number if any.  This field is not
  // persistent though; its only used in the in-tab cookies dialog to show the
  // user the source URL. This is used for both allowed and blocked cookies.
  // When a CanonicalCookie is constructed from the backing store (common case)
  // this field will be null.  CanonicalCookie consumers should not rely on
  // this field unless they guarantee that the creator of those
  // CanonicalCookies properly initialized the field.
  // TODO(abarth): We might need to make this field persistent for MAC cookies.
  std::string source_;
  std::string name_;
  std::string value_;
  std::string domain_;
  std::string path_;
  std::string mac_key_;  // TODO(abarth): Persist to disk.
  std::string mac_algorithm_;  // TODO(abarth): Persist to disk.
  base::Time creation_date_;
  base::Time expiry_date_;
  base::Time last_access_date_;
  bool secure_;
  bool httponly_;
  bool has_expires_;
  bool is_persistent_;
};

class CookieMonster::Delegate
    : public base::RefCountedThreadSafe<CookieMonster::Delegate> {
 public:
  // The publicly relevant reasons a cookie might be changed.
  enum ChangeCause {
    // The cookie was changed directly by a consumer's action.
    CHANGE_COOKIE_EXPLICIT,
    // The cookie was automatically removed due to an insert operation that
    // overwrote it.
    CHANGE_COOKIE_OVERWRITE,
    // The cookie was automatically removed as it expired.
    CHANGE_COOKIE_EXPIRED,
    // The cookie was automatically evicted during garbage collection.
    CHANGE_COOKIE_EVICTED,
    // The cookie was overwritten with an already-expired expiration date.
    CHANGE_COOKIE_EXPIRED_OVERWRITE
  };

  // Will be called when a cookie is added or removed. The function is passed
  // the respective |cookie| which was added to or removed from the cookies.
  // If |removed| is true, the cookie was deleted, and |cause| will be set
  // to the reason for it's removal. If |removed| is false, the cookie was
  // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
  //
  // As a special case, note that updating a cookie's properties is implemented
  // as a two step process: the cookie to be updated is first removed entirely,
  // generating a notification with cause CHANGE_COOKIE_OVERWRITE.  Afterwards,
  // a new cookie is written with the updated values, generating a notification
  // with cause CHANGE_COOKIE_EXPLICIT.
  virtual void OnCookieChanged(const CookieMonster::CanonicalCookie& cookie,
                               bool removed,
                               ChangeCause cause) = 0;
 protected:
  friend class base::RefCountedThreadSafe<CookieMonster::Delegate>;
  virtual ~Delegate() {}
};

class NET_EXPORT CookieMonster::ParsedCookie {
 public:
  typedef std::pair<std::string, std::string> TokenValuePair;
  typedef std::vector<TokenValuePair> PairList;

  // The maximum length of a cookie string we will try to parse
  static const size_t kMaxCookieSize = 4096;
  // The maximum number of Token/Value pairs.  Shouldn't have more than 8.
  static const int kMaxPairs = 16;

  // Construct from a cookie string like "BLAH=1; path=/; domain=.google.com"
  ParsedCookie(const std::string& cookie_line);
  ~ParsedCookie();

  // You should not call any other methods on the class if !IsValid
  bool IsValid() const { return is_valid_; }

  const std::string& Name() const { return pairs_[0].first; }
  const std::string& Token() const { return Name(); }
  const std::string& Value() const { return pairs_[0].second; }

  bool HasPath() const { return path_index_ != 0; }
  const std::string& Path() const { return pairs_[path_index_].second; }
  bool HasDomain() const { return domain_index_ != 0; }
  const std::string& Domain() const { return pairs_[domain_index_].second; }
  bool HasMACKey() const { return mac_key_index_ != 0; }
  const std::string& MACKey() const { return pairs_[mac_key_index_].second; }
  bool HasMACAlgorithm() const { return mac_algorithm_index_ != 0; }
  const std::string& MACAlgorithm() const {
    return pairs_[mac_algorithm_index_].second;
  }
  bool HasExpires() const { return expires_index_ != 0; }
  const std::string& Expires() const { return pairs_[expires_index_].second; }
  bool HasMaxAge() const { return maxage_index_ != 0; }
  const std::string& MaxAge() const { return pairs_[maxage_index_].second; }
  bool IsSecure() const { return secure_index_ != 0; }
  bool IsHttpOnly() const { return httponly_index_ != 0; }

  // Returns the number of attributes, for example, returning 2 for:
  //   "BLAH=hah; path=/; domain=.google.com"
  size_t NumberOfAttributes() const { return pairs_.size() - 1; }

  // For debugging only!
  std::string DebugString() const;

  // Returns an iterator pointing to the first terminator character found in
  // the given string.
  static std::string::const_iterator FindFirstTerminator(const std::string& s);

  // Given iterators pointing to the beginning and end of a string segment,
  // returns as output arguments token_start and token_end to the start and end
  // positions of a cookie attribute token name parsed from the segment, and
  // updates the segment iterator to point to the next segment to be parsed.
  // If no token is found, the function returns false.
  static bool ParseToken(std::string::const_iterator* it,
                         const std::string::const_iterator& end,
                         std::string::const_iterator* token_start,
                         std::string::const_iterator* token_end);

  // Given iterators pointing to the beginning and end of a string segment,
  // returns as output arguments value_start and value_end to the start and end
  // positions of a cookie attribute value parsed from the segment, and updates
  // the segment iterator to point to the next segment to be parsed.
  static void ParseValue(std::string::const_iterator* it,
                         const std::string::const_iterator& end,
                         std::string::const_iterator* value_start,
                         std::string::const_iterator* value_end);

  // Same as the above functions, except the input is assumed to contain the
  // desired token/value and nothing else.
  static std::string ParseTokenString(const std::string& token);
  static std::string ParseValueString(const std::string& value);

 private:
  static const char kTerminator[];
  static const int  kTerminatorLen;
  static const char kWhitespace[];
  static const char kValueSeparator[];
  static const char kTokenSeparator[];

  void ParseTokenValuePairs(const std::string& cookie_line);
  void SetupAttributes();

  PairList pairs_;
  bool is_valid_;
  // These will default to 0, but that should never be valid since the
  // 0th index is the user supplied token/value, not an attribute.
  // We're really never going to have more than like 8 attributes, so we
  // could fit these into 3 bits each if we're worried about size...
  size_t path_index_;
  size_t domain_index_;
  size_t mac_key_index_;
  size_t mac_algorithm_index_;
  size_t expires_index_;
  size_t maxage_index_;
  size_t secure_index_;
  size_t httponly_index_;

  DISALLOW_COPY_AND_ASSIGN(ParsedCookie);
};

typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
    RefcountedPersistentCookieStore;

class CookieMonster::PersistentCookieStore
    : public RefcountedPersistentCookieStore {
 public:
  virtual ~PersistentCookieStore() {}

  typedef base::Callback<void(const std::vector<
      CookieMonster::CanonicalCookie*>&)> LoadedCallback;

  // Initializes the store and retrieves the existing cookies. This will be
  // called only once at startup. The callback will return all the cookies
  // that are not yet returned to CookieMonster by previous priority loads.
  virtual void Load(const LoadedCallback& loaded_callback) = 0;

  // Does a priority load of all cookies for the domain key (eTLD+1). The
  // callback will return all the cookies that are not yet returned by previous
  // loads, which includes cookies for the requested domain key if they are not
  // already returned, plus all cookies that are chain-loaded and not yet
  // returned to CookieMonster.
  virtual void LoadCookiesForKey(const std::string& key,
    const LoadedCallback& loaded_callback) = 0;

  virtual void AddCookie(const CanonicalCookie& cc) = 0;
  virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
  virtual void DeleteCookie(const CanonicalCookie& cc) = 0;

  // Sets the value of the user preference whether the persistent storage
  // must be deleted upon destruction.
  virtual void SetClearLocalStateOnExit(bool clear_local_state) = 0;

  // Flushes the store and posts |callback| when complete.
  virtual void Flush(const base::Closure& callback) = 0;

 protected:
  PersistentCookieStore() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
};

class CookieList : public std::vector<CookieMonster::CanonicalCookie> {
};

}  // namespace net

#endif  // NET_BASE_COOKIE_MONSTER_H_


text:
<!DOCTYPE doctype PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">

    <META name="generator" content=
    "HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net">

    <TITLE>Debugger: Memory Regions</TITLE>
    <META http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <LINK rel="stylesheet" type="text/css" href="../../shared/Frontpage.css">

Debugger: Memory Regions

Regions refer to ranges of allocated or reserved memory reported by the target. The precise
    meaning of these regions may vary depending on the nature of the target. For user-mode
    applications, this is generally pages of memory allocated for image sections, the stack, the
    heap, etc. The regions manager allows the user to rename pages and modify the recorded
    permissions. Note that such modifications do not affect the target; but only the
    recording.

Table Columns

The table has the following columns:

Name - the name given to the region by the target. This field is user modifiable.

Lifespan - the creation and destruction time of the region.

Start - the minimum address of the region. Double-clicking this field navigates to the
      address.

End - the maximum address of the region. Double-clicking this field navigates to the
      address.

Length - the length of the region in bytes.

Read,Write,Execute,Volatile - various flags of the region. These flags only affect local
      analysis. Toggling these do not affect the target.

Actions

Other than modifications enabled by the table, the Regions window provides the following
    actions:

Map Regions

This action is analogous to the Map Modules and Map Sections actions from the Modules window. It searches
    the tool's open programs for blocks matching the selected regions and proposes new mappings.
    Users who prefer this should also consider using the Map Regions debugger bot. For the
    best result, the selection regions should comprise a complete module. In particular, it should
    include the region containing the module's image base, as the offset from this base is used in
    scoring the best-matched blocks. Additionally, the region names must include the module's file
    name, otherwise the matcher has no means to identify a corresponding program.

Map Regions to Current Program

This action is available from the pop-up menu, when there is a selection of regions and
    there is an open program. It behaves like Map Regions, except that it will attempt to map the
    selected regions to blocks in the current program only. This is useful if the regions are not
    named according to the module filename. The selected regions should still comprise a complete
    module for best results.

Map Region to Current Block

This action is available from a single region's pop-up menu, when there is an open program.
    It behaves like Map Regions, except that it will propose the selected region be mapped to the
    block containing the cursor in the static listing.

Select Addresses

This action is available when at least one region is selected. It selects all addresses in
    the dynamic listing contained by the selected regions.

Select Rows

This action is available when the dynamic listing's cursor is at a valid location. It
    selects the region containing that cursor. If the dynamic listing has a selection, it selects
    all regions intersecting that selection.

Force Full View

This action is available when a trace is active. It forces all physical address spaces into
    the view. Ordinarily, only those addresses contained in a region at the active snap are
    presented in the listing and memory windows. When this toggle is on, regions are ignored.
    Instead, all physical addresses are presented. (Here "physical" includes all memory spaces
    except OTHER.) This toggle applies only to the current trace for the duration it
    is open.


text:
package com.hannesdorfmann.mosby3.mvp;

import com.hannesdorfmann.mosby3.mvp.test.data.TestData;
import com.hannesdorfmann.mosby3.mvp.test.presenter.ParameterlessConstructorMvpPresenter;
import com.hannesdorfmann.mosby3.mvp.test.presenter.SubMvpPresenter;
import com.hannesdorfmann.mosby3.mvp.test.presenter.SubParameterlessConstructorMvpPresenter;
import com.hannesdorfmann.mosby3.mvp.test.presenter.UselessGenericParamsMvpPresenter;
import com.hannesdorfmann.mosby3.mvp.test.view.SubMvpView;
import com.hannesdorfmann.mosby3.mvp.test.view.TestMvpView;
import com.hannesdorfmann.mosby3.mvp.test.view.TestMvpViewWithMultipleInterfaces;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author Hannes Dorfmann
 */
public class MvpNullObjectBasePresenterTest {

  @Test public void throwsExceptionWhenInteractingWithPresenterButNoViewHasEverAttached() {

    MvpNullObjectBasePresenter<MvpView> presenter = new MvpNullObjectBasePresenter<MvpView>() {
    };

    try {
      presenter.getView();
      Assert.fail("Exception should be thrown");
    } catch (IllegalStateException e) {
      // Expected exception
    }
  }

  @Test @SuppressWarnings("unchecked") public void uselessGenericsParamsPresenter() {
    TestMvpView view = newTestView();
    UselessGenericParamsMvpPresenter presenter = new UselessGenericParamsMvpPresenter<>();

    testPickingCorrectViewInterface(presenter);
    testAttachDetachView(presenter, view);

    presenter.attachView(view);
    presenter.viewShowThat();
    presenter.detachView();
    presenter.destroy();
    presenter.viewShowThat();
  }

  @Test public void constructorGenericParameterless() {
    ParameterlessConstructorMvpPresenter<TestData> presenter =
        new ParameterlessConstructorMvpPresenter<>();
    TestMvpView view = newTestView();

    testPickingCorrectViewInterface(presenter);
    testAttachDetachView(presenter, view);

    presenter.attachView(view);
    presenter.viewShowThat();
    presenter.detachView();
    presenter.destroy();
    presenter.viewShowThat();
  }

  @Test public void constructorDirectlyBaseClass() {
    MvpNullObjectBasePresenter<TestMvpView> presenter =
        new MvpNullObjectBasePresenter<TestMvpView>() {
        };
    TestMvpView view = newTestView();

    testPickingCorrectViewInterface(presenter);
    testAttachDetachView(presenter, view);
  }

  @Test public void constructorSubClass() {
    SubParameterlessConstructorMvpPresenter presenter =
        new SubParameterlessConstructorMvpPresenter();
    TestMvpView view = newTestView();

    testPickingCorrectViewInterface(presenter);
    testAttachDetachView(presenter, view);

    presenter.attachView(view);
    presenter.viewShowThat();
    presenter.detachView();
    presenter.destroy();
    presenter.viewShowThat();
  }

  @Test public void subviewInterface() {
    SubMvpPresenter presenter = new SubMvpPresenter();
    SubMvpView view = newSubTestView();

    testAttachDetachView(presenter, view);

    presenter.attachView(view);
    presenter.invokeShowThat();
    presenter.detachView();
    presenter.destroy();
    presenter.invokeShowThat();
  }

  private <V extends MvpView> void testAttachDetachView(
      final MvpNullObjectBasePresenter<V> presenter, final V view) {

    testAttachView(presenter, view);
    testDetachNonRetain(presenter, view);
    testAttachView(presenter, view);
    testDetachRetain(presenter, view);
  }

  private <V extends MvpView> void testAttachView(final MvpNullObjectBasePresenter<V> presenter,
      final V view) {
    presenter.attachView(view);
    Assert.assertNotNull(presenter.getView());
    Assert.assertTrue(presenter.getView() == view);
  }

  private <V extends MvpView> void testDetachNonRetain(
      final MvpNullObjectBasePresenter<V> presenter, final V view) {
    presenter.detachView();
    presenter.destroy();
    Assert.assertNotNull(presenter.getView());
    Assert.assertTrue(presenter.getView() != view); // Null Object view;
  }

  private <V extends MvpView> void testDetachRetain(final MvpNullObjectBasePresenter<V> presenter,
      final V view) {
    presenter.detachView();
    Assert.assertNotNull(presenter.getView());
    Assert.assertTrue(presenter.getView() != view); // Null Object view;
  }

  private void testPickingCorrectViewInterface(
      final MvpNullObjectBasePresenter<TestMvpView> presenter) {
    TestMvpViewWithMultipleInterfaces view = new TestMvpViewWithMultipleInterfaces();

    presenter.attachView(view);
    Assert.assertNotNull(presenter.getView());
    Assert.assertTrue(view == presenter.getView());

    presenter.detachView();
    presenter.destroy();
    Assert.assertNotNull(presenter.getView());
    Assert.assertFalse(presenter.getView() == view);

    // Invoke methods on null object
    presenter.getView().showFoo(new TestData());
    presenter.getView().showThat();
  }

  private TestMvpView newTestView() {
    return new TestMvpView() {
      @Override public void showFoo(TestData data) {
      }

      @Override public void showThat() {
      }
    };
  }

  private SubMvpView newSubTestView() {
    return new SubMvpView() {
      @Override public void showFoo(TestData data) {
      }

      @Override public void showThat() {

      }
    };
  }
}