text:
id: 5d68c3b1e0696bdec46938e8
title: Step 41
challengeType: 0
dashedName: step-41
---

# --description--

`location["button text"]` is an array with three elements. Use only the first element of the array by adding `[0]` at the end.

# --hints--

See description above for instructions.

```js
assert(
  update
    .toString()
    .match(
      /button1\.innerText\s*\=\s*location\[[\'\"\`]button text[\'\"\`]\]\[0\]/
    )
);
```

# --seed--

## --before-user-code--

```html
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>RPG - Dragon Repeller</title>
  <style>
    body {
      background-color: darkblue;
    }
    #text {
      background-color: black;
      color: white;
      padding: 10px;
    }
    #game {
      max-width: 500px;
      max-height: 400px;
      background-color: lightgray;
      color: white;
      margin: 0 auto;
      padding: 10px;
    }
    #controls {
      border: 1px black solid;
      padding: 5px;
    }
    #stats {
      border: 1px black solid;
      color: black;
      padding: 5px;
    }
    #monsterStats {
      display: none;
      border: 1px black solid;
      color: white;
      padding: 5px;
      background-color: red;
    }
    .stat {
      padding-right: 10px;
    }
  </style>
</head>
<body>
<div id="game">
  <div id="stats">
    <span class="stat">XP: <strong><span id="xpText">0</span></strong></span>
    <span class="stat">Health: <strong><span id="healthText">100</span></strong></span>
    <span class="stat">Gold: <strong><span id="goldText">50</span></strong></span>
  </div>
  <div id="controls">
    <button id="button1">Go to store</button>
    <button id="button2">Go to cave</button>
    <button id="button3">Fight dragon</button>
  </div>
  <div id="monsterStats">
    <span class="stat">Monster Name: <strong><span id="monsterName"></span></strong></span>
    <span class="stat">Health: <strong><span id="monsterHealth"></span></strong></span>
  </div>
  <div id="text">Welcome to Dragon Repeller. You must defeat the dragon that is preventing people from leaving the town. You are in the town square. Where do you want to go? Use the buttons above.</div>
</div>
```

## --after-user-code--

```html
</body>
</html>
```

## --seed-contents--

```html
<script>
let xp = 0;
let health = 100;
let gold = 50;
let currentWeapon = 0;
let fighting;
let monsterHealth;
let inventory = ["stick"];

const button1 = document.querySelector('#button1');
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const text = document.querySelector("#text");
const xpText = document.querySelector("#xpText");
const healthText = document.querySelector("#healthText");
const goldText = document.querySelector("#goldText");
const monsterStats = document.querySelector("#monsterStats");
const monsterNameText = document.querySelector("#monsterName");
const monsterHealthText = document.querySelector("#monsterHealth");

const locations = [
  {
    name: "town square",
    "button text": ["Go to store", "Go to cave", "Fight dragon"],
    "button functions": [goStore, goCave, fightDragon],
    text: "You are in the town square. You see a sign that says \"Store.\""
  },
  {
    name: "store",
    "button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
    "button functions": [buyHealth, buyWeapon, goTown],
    text: "You enter the store."
  }
];

// initialize buttons
button1.onclick = goStore;
button2.onclick = goCave;
button3.onclick = fightDragon;

function update(location) {
  button1.innerText = location["button text"];
  button2.innerText = "Go to cave";
  button3.innerText = "Fight dragon";
  button1.onclick = goStore;
  button2.onclick = goCave;
  button3.onclick = fightDragon;
  text.innerText = "You are in the town square. You see a sign that says \"Store\".";
}

function goTown() {
  update(locations[0]);
}

function goStore() {
}

function goCave() {
  console.log("Going to cave.");
}

function fightDragon() {
  console.log("Fighting dragon.");
}

function buyHealth() {
}

function buyWeapon() {
}

</script>
```

# --solutions--

```html
<script>
let xp = 0;
let health = 100;
let gold = 50;
let currentWeapon = 0;
let fighting;
let monsterHealth;
let inventory = ["stick"];

const button1 = document.querySelector('#button1');
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const text = document.querySelector("#text");
const xpText = document.querySelector("#xpText");
const healthText = document.querySelector("#healthText");
const goldText = document.querySelector("#goldText");
const monsterStats = document.querySelector("#monsterStats");
const monsterNameText = document.querySelector("#monsterName");
const monsterHealthText = document.querySelector("#monsterHealth");

const locations = [
  {
    name: "town square",
    "button text": ["Go to store", "Go to cave", "Fight dragon"],
    "button functions": [goStore, goCave, fightDragon],
    text: "You are in the town square. You see a sign that says \"Store.\""
  },
  {
    name: "store",
    "button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
    "button functions": [buyHealth, buyWeapon, goTown],
    text: "You enter the store."
  }
];

// initialize buttons
button1.onclick = goStore;
button2.onclick = goCave;
button3.onclick = fightDragon;

function update(location) {
  button1.innerText = location["button text"][0];
  button2.innerText = "Go to cave";
  button3.innerText = "Fight dragon";
  button1.onclick = goStore;
  button2.onclick = goCave;
  button3.onclick = fightDragon;
  text.innerText = "You are in the town square. You see a sign that says \"Store\".";
}

function goTown() {
  update(locations[0]);
}

function goStore() {
}

function goCave() {
  console.log("Going to cave.");
}

function fightDragon() {
  console.log("Fighting dragon.");
}

function buyHealth() {
}

function buyWeapon() {
}
</script>
```


text:
package com.study.design.factorymethod.c1.idcard;

import com.study.design.factorymethod.c1.framework.Factory;
import com.study.design.factorymethod.c1.framework.Product;

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

/**
 * @author chenyao
 * @date 2017/11/1 15:45
 */
public class IDCardFactory extends Factory {
    private List<String> owners = new ArrayList<>();

    @Override
    public Product createProduct(String owner) {
        return new IDCard(owner);
    }

    @Override
    public void registerProduct(Product product) {
        owners.add(((IDCard) product).getOwner());
    }

    public List<String> getOwners() {
        return owners;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Tests for open_spiel.python.egt.visualization."""

from absl import logging
from absl.testing import absltest

# pylint: disable=g-import-not-at-top
try:
  from matplotlib.figure import Figure
  from matplotlib.quiver import Quiver
  from matplotlib.streamplot import StreamplotSet
except ImportError as e:
  logging.info("If your tests failed with the error 'ImportError: No module "
               "named functools_lru_cache', this is a known bug in matplotlib "
               "and there is a workaround (run sudo apt install "
               "python-backports.functools-lru-cache. See: "
               "https://github.com/matplotlib/matplotlib/issues/9344.")
  raise e

import numpy as np

from open_spiel.python.egt import dynamics
from open_spiel.python.egt import utils
from open_spiel.python.egt import visualization
import pyspiel

def _build_dynamics2x2():
  """Build multi-population dynamics."""
  game = pyspiel.load_game("matrix_pd")
  payoff_tensor = utils.game_payoffs_array(game)
  return dynamics.MultiPopulationDynamics(payoff_tensor, dynamics.replicator)

def _build_dynamics3x3():
  """Build single-population dynamics."""
  game = pyspiel.load_game("matrix_rps")
  payoff_tensor = utils.game_payoffs_array(game)
  return dynamics.SinglePopulationDynamics(payoff_tensor, dynamics.replicator)

def _identity_dynamics(x):
  """Returns same input as output."""
  return x

class VisualizationTest(absltest.TestCase):

  def test_meshgrid(self):
    n = 10
    payoff_tensor = np.ones(shape=(2, 2, 2))
    identity = lambda x, f: x
    allzero = lambda x, f: np.zeros(x.shape)
    dyn = dynamics.MultiPopulationDynamics(payoff_tensor, (identity, allzero))
    x, y, u, v = visualization._eval_dynamics_2x2_grid(dyn, n)
    np.testing.assert_allclose(x, u)
    np.testing.assert_allclose(v, np.zeros(shape=(n, n)))

    dyn = dynamics.MultiPopulationDynamics(payoff_tensor, (allzero, identity))
    x, y, u, v = visualization._eval_dynamics_2x2_grid(dyn, n)
    np.testing.assert_allclose(u, np.zeros(shape=(n, n)))
    np.testing.assert_allclose(y, v)

  def test_quiver2x2(self):
    """Test 2x2 quiver plot."""
    dyn = _build_dynamics2x2()
    fig = Figure(figsize=(4, 4))
    ax = fig.add_subplot(111, projection="2x2")
    res = ax.quiver(dyn)
    self.assertIsInstance(res, Quiver)

  def test_streamplot2x2(self):
    """Test 2x2 quiver plot."""
    dyn = _build_dynamics2x2()
    fig = Figure(figsize=(4, 4))
    ax = fig.add_subplot(111, projection="2x2")
    res = ax.streamplot(dyn)
    self.assertIsInstance(res, StreamplotSet)

  def test_quiver3x3(self):
    """Test 3x3 quiver plot."""
    dyn = _build_dynamics3x3()
    fig = Figure(figsize=(4, 4))
    ax = fig.add_subplot(111, projection="3x3")
    res = ax.quiver(dyn)
    self.assertIsInstance(res, Quiver)

  def test_streamplot3x3(self):
    """Test 3x3 quiver plot."""
    dyn = _build_dynamics3x3()
    fig = Figure(figsize=(4, 4))
    ax = fig.add_subplot(111, projection="3x3")
    res = ax.streamplot(dyn)
    self.assertIsInstance(res, visualization.SimplexStreamMask)

if __name__ == "__main__":
  absltest.main()


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
using Zabavnov.Sudoku;

namespace Sudoku.Tests
{
    public class GridTests
    {
        [Theory]
        [MemberData("TestLoadSource")]
        public void TestLoad(string text)
        {
            var grid = Grid.Load(text);

            var rows = text.Split('\n');
            for (int r = 0; r < 9; r++)
            {
                var row = rows[r];
                Assert.True(row.Length >= 9);

                for (int c = 0; c < 9; c++)
                {
                    int value;
                    if (int.TryParse(row[c].ToString(), out value))
                    {
                        Assert.Equal(value, grid.Cells[r, c].Value);
                    }
                    else
                    {
                        Assert.Null(grid.Cells[r, c].Value);
                    }
                }
            }
        }

        public static IEnumerable<object[]> TestLoadSource()
        {
            var files = new[] { "easy.txt", "Hard.txt", "Medium.txt", "Samurai.txt" };

            return files.Select(File.ReadAllText).Select(text => new object[] {text});
        }
    }
}


text:
CC            = gcc
CXX           = g++
DEFINES       = -DQT_WEBKIT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED
CFLAGS        = -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES)
CXXFLAGS      = -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES)
INCPATH       = -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. -I.
LINK          = g++
LFLAGS        = -Wl,-O1
LIBS          = $(SUBLIBS)  -L/usr/lib/i386-linux-gnu -lQtGui -lQtCore -lpthread
AR            = ar cqs
RANLIB        =
QMAKE         = /usr/bin/qmake-qt4
TAR           = tar -cf
COMPRESS      = gzip -9f
COPY          = cp -f
SED           = sed
COPY_FILE     = $(COPY)
COPY_DIR      = $(COPY) -r
STRIP         = strip
INSTALL_FILE  = install -m 644 -p
INSTALL_DIR   = $(COPY_DIR)
INSTALL_PROGRAM = install -m 755 -p
DEL_FILE      = rm -f
SYMLINK       = ln -f -s
DEL_DIR       = rmdir
MOVE          = mv -f
CHK_DIR_EXISTS= test -d
MKDIR         = mkdir -p

####### Output directory

OBJECTS_DIR   = ./

####### Files

SOURCES       = main.cpp \
		mainwindow.cpp \
		../../qcustomplot.cpp moc_mainwindow.cpp \
		moc_qcustomplot.cpp
OBJECTS       = main.o \
		mainwindow.o \
		qcustomplot.o \
		moc_mainwindow.o \
		moc_qcustomplot.o
DIST          = /usr/share/qt4/mkspecs/common/unix.conf \
		/usr/share/qt4/mkspecs/common/linux.conf \
		/usr/share/qt4/mkspecs/common/gcc-base.conf \
		/usr/share/qt4/mkspecs/common/gcc-base-unix.conf \
		/usr/share/qt4/mkspecs/common/g++-base.conf \
		/usr/share/qt4/mkspecs/common/g++-unix.conf \
		/usr/share/qt4/mkspecs/qconfig.pri \
		/usr/share/qt4/mkspecs/modules/qt_phonon.pri \
		/usr/share/qt4/mkspecs/modules/qt_webkit_version.pri \
		/usr/share/qt4/mkspecs/features/qt_functions.prf \
		/usr/share/qt4/mkspecs/features/qt_config.prf \
		/usr/share/qt4/mkspecs/features/exclusive_builds.prf \
		/usr/share/qt4/mkspecs/features/default_pre.prf \
		/usr/share/qt4/mkspecs/features/release.prf \
		/usr/share/qt4/mkspecs/features/default_post.prf \
		/usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf \
		/usr/share/qt4/mkspecs/features/warn_on.prf \
		/usr/share/qt4/mkspecs/features/qt.prf \
		/usr/share/qt4/mkspecs/features/unix/thread.prf \
		/usr/share/qt4/mkspecs/features/moc.prf \
		/usr/share/qt4/mkspecs/features/resources.prf \
		/usr/share/qt4/mkspecs/features/uic.prf \
		/usr/share/qt4/mkspecs/features/yacc.prf \
		/usr/share/qt4/mkspecs/features/lex.prf \
		/usr/share/qt4/mkspecs/features/include_source_dir.prf \
		plot-examples.pro
QMAKE_TARGET  = plot-examples
DESTDIR       =
TARGET        = plot-examples

first: all
####### Implicit rules

.SUFFIXES: .o .c .cpp .cc .cxx .C

.cpp.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.cc.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.cxx.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.C.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.c.o:
	$(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<"

####### Build rules

all: Makefile $(TARGET)

$(TARGET): ui_mainwindow.h $(OBJECTS)
	$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)

Makefile: plot-examples.pro  /usr/share/qt4/mkspecs/linux-g++/qmake.conf /usr/share/qt4/mkspecs/common/unix.conf \
		/usr/share/qt4/mkspecs/common/linux.conf \
		/usr/share/qt4/mkspecs/common/gcc-base.conf \
		/usr/share/qt4/mkspecs/common/gcc-base-unix.conf \
		/usr/share/qt4/mkspecs/common/g++-base.conf \
		/usr/share/qt4/mkspecs/common/g++-unix.conf \
		/usr/share/qt4/mkspecs/qconfig.pri \
		/usr/share/qt4/mkspecs/modules/qt_phonon.pri \
		/usr/share/qt4/mkspecs/modules/qt_webkit_version.pri \
		/usr/share/qt4/mkspecs/features/qt_functions.prf \
		/usr/share/qt4/mkspecs/features/qt_config.prf \
		/usr/share/qt4/mkspecs/features/exclusive_builds.prf \
		/usr/share/qt4/mkspecs/features/default_pre.prf \
		/usr/share/qt4/mkspecs/features/release.prf \
		/usr/share/qt4/mkspecs/features/default_post.prf \
		/usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf \
		/usr/share/qt4/mkspecs/features/warn_on.prf \
		/usr/share/qt4/mkspecs/features/qt.prf \
		/usr/share/qt4/mkspecs/features/unix/thread.prf \
		/usr/share/qt4/mkspecs/features/moc.prf \
		/usr/share/qt4/mkspecs/features/resources.prf \
		/usr/share/qt4/mkspecs/features/uic.prf \
		/usr/share/qt4/mkspecs/features/yacc.prf \
		/usr/share/qt4/mkspecs/features/lex.prf \
		/usr/share/qt4/mkspecs/features/include_source_dir.prf \
		/usr/lib/i386-linux-gnu/libQtGui.prl \
		/usr/lib/i386-linux-gnu/libQtCore.prl
	$(QMAKE) -spec /usr/share/qt4/mkspecs/linux-g++ -o Makefile plot-examples.pro
/usr/share/qt4/mkspecs/common/unix.conf:
/usr/share/qt4/mkspecs/common/linux.conf:
/usr/share/qt4/mkspecs/common/gcc-base.conf:
/usr/share/qt4/mkspecs/common/gcc-base-unix.conf:
/usr/share/qt4/mkspecs/common/g++-base.conf:
/usr/share/qt4/mkspecs/common/g++-unix.conf:
/usr/share/qt4/mkspecs/qconfig.pri:
/usr/share/qt4/mkspecs/modules/qt_phonon.pri:
/usr/share/qt4/mkspecs/modules/qt_webkit_version.pri:
/usr/share/qt4/mkspecs/features/qt_functions.prf:
/usr/share/qt4/mkspecs/features/qt_config.prf:
/usr/share/qt4/mkspecs/features/exclusive_builds.prf:
/usr/share/qt4/mkspecs/features/default_pre.prf:
/usr/share/qt4/mkspecs/features/release.prf:
/usr/share/qt4/mkspecs/features/default_post.prf:
/usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf:
/usr/share/qt4/mkspecs/features/warn_on.prf:
/usr/share/qt4/mkspecs/features/qt.prf:
/usr/share/qt4/mkspecs/features/unix/thread.prf:
/usr/share/qt4/mkspecs/features/moc.prf:
/usr/share/qt4/mkspecs/features/resources.prf:
/usr/share/qt4/mkspecs/features/uic.prf:
/usr/share/qt4/mkspecs/features/yacc.prf:
/usr/share/qt4/mkspecs/features/lex.prf:
/usr/share/qt4/mkspecs/features/include_source_dir.prf:
/usr/lib/i386-linux-gnu/libQtGui.prl:
/usr/lib/i386-linux-gnu/libQtCore.prl:
qmake:  FORCE
	@$(QMAKE) -spec /usr/share/qt4/mkspecs/linux-g++ -o Makefile plot-examples.pro

dist:
	@$(CHK_DIR_EXISTS) .tmp/plot-examples1.0.0 || $(MKDIR) .tmp/plot-examples1.0.0
	$(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/plot-examples1.0.0/ && $(COPY_FILE) --parents mainwindow.h ../../qcustomplot.h .tmp/plot-examples1.0.0/ && $(COPY_FILE) --parents main.cpp mainwindow.cpp ../../qcustomplot.cpp .tmp/plot-examples1.0.0/ && $(COPY_FILE) --parents mainwindow.ui .tmp/plot-examples1.0.0/ && (cd `dirname .tmp/plot-examples1.0.0` && $(TAR) plot-examples1.0.0.tar plot-examples1.0.0 && $(COMPRESS) plot-examples1.0.0.tar) && $(MOVE) `dirname .tmp/plot-examples1.0.0`/plot-examples1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/plot-examples1.0.0

clean:compiler_clean
	-$(DEL_FILE) $(OBJECTS)
	-$(DEL_FILE) *~ core *.core

####### Sub-libraries

distclean: clean
	-$(DEL_FILE) $(TARGET)
	-$(DEL_FILE) Makefile

check: first

mocclean: compiler_moc_header_clean compiler_moc_source_clean

mocables: compiler_moc_header_make_all compiler_moc_source_make_all

compiler_moc_header_make_all: moc_mainwindow.cpp moc_qcustomplot.cpp
compiler_moc_header_clean:
	-$(DEL_FILE) moc_mainwindow.cpp moc_qcustomplot.cpp
moc_mainwindow.cpp: ../../qcustomplot.h \
		mainwindow.h
	/usr/bin/moc-qt4 $(DEFINES) $(INCPATH) mainwindow.h -o moc_mainwindow.cpp

moc_qcustomplot.cpp: ../../qcustomplot.h
	/usr/bin/moc-qt4 $(DEFINES) $(INCPATH) ../../qcustomplot.h -o moc_qcustomplot.cpp

compiler_rcc_make_all:
compiler_rcc_clean:
compiler_image_collection_make_all: qmake_image_collection.cpp
compiler_image_collection_clean:
	-$(DEL_FILE) qmake_image_collection.cpp
compiler_moc_source_make_all:
compiler_moc_source_clean:
compiler_uic_make_all: ui_mainwindow.h
compiler_uic_clean:
	-$(DEL_FILE) ui_mainwindow.h
ui_mainwindow.h: mainwindow.ui \
		../../qcustomplot.h
	/usr/bin/uic-qt4 mainwindow.ui -o ui_mainwindow.h

compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean: compiler_moc_header_clean compiler_uic_clean

####### Compile

main.o: main.cpp mainwindow.h \
		../../qcustomplot.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o main.cpp

mainwindow.o: mainwindow.cpp mainwindow.h \
		../../qcustomplot.h \
		ui_mainwindow.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o mainwindow.o mainwindow.cpp

qcustomplot.o: ../../qcustomplot.cpp ../../qcustomplot.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o qcustomplot.o ../../qcustomplot.cpp

moc_mainwindow.o: moc_mainwindow.cpp
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_mainwindow.o moc_mainwindow.cpp

moc_qcustomplot.o: moc_qcustomplot.cpp
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_qcustomplot.o moc_qcustomplot.cpp

####### Install

install:   FORCE

uninstall:   FORCE

FORCE:


text:
var Graph = function(canvas, dataset) {
    this.canvas = this.readElementString(canvas);
    this.dataset = dataset;
    this.points = [];
    this.drawPoints = [];
    this.position = {
        x: 0,
        y: 0
    };
    this.min = 0;
    this.max = 0;
    this.highlight = "";
    this.point = {};
    this.ratio = 1;
    this.realWidth;
    this.tooltip = {x: this.canvas.width/2, y: this.canvas.height/2, radius: 0, oldx: 0};

    this.makeHighRes();      //Instantiate the graph it self.
    this.convert();   //Convert the dataset to usable pixel points
}

//########## INSTANTIATE THE GRAPH AND DRAWS IT ######
Graph.prototype.init = function() {
  var self = this;
  var timer=setInterval(function(){self.draw();},20);
  this.listen();    //Listen for Mouse or Touch Events
}

//######### LISTEN FOR MOUSE EVENTS ON THE GRAPH ######
Graph.prototype.listen = function() {
    var self = this;
    this.canvas.addEventListener('mousemove', function(evt) {
        self.position = self.getMousePos(evt);
      //  self.draw();
    }, false);

    this.canvas.addEventListener('touchmove', function(evt) {
        self.position = self.getMousePos(evt);
      //  self.draw();
    }, false);

    this.canvas.addEventListener('touchstart', function(evt) {
        self.position = self.getMousePos(evt);
      //  self.draw();
    }, false);
}

//### Convert the dataset in to usable points on the graph ####//
Graph.prototype.convert = function(){
  var padding = this.canvas.width /10;
  var largestX = 0;
  var largestY = 0;

  this.dataset.forEach(function(value){
    if(value.x > largestX){
      largestX = value.x;
    }

    if(value.y > largestY){
      largestY = value.y;
    }
  });

  var smallestX = largestX;
  var smallestY = largestY;

  this.dataset.forEach(function(value){
    if(value.x < smallestX){
      smallestX = value.x;
    }

    if(value.y < smallestY){
      smallestY = value.y;
    }
  });

  var diffX = Math.abs(largestX - smallestX);
  var diffY = Math.abs(largestY - smallestY);

  //var NewMax = this.canvas.Width * this.ratio;
  var NewMax = this.canvas.width - padding;
  var NewMin = padding;
  this.min = NewMin;
  this.max = NewMax;
  if(diffX > diffY){
    var OldMax = largestX;
    var OldMin = smallestX;
  }else{
    var OldMax = largestY;
    var OldMin = smallestY;
  }

  var OldRange = (OldMax - OldMin);
  var NewRange = (NewMax - NewMin);
  var self = this;
  this.dataset.forEach(function(value, index){
    var obj = {
      x: Math.round((((value.x - OldMin) * NewRange) / OldRange) + NewMin),
      y: Math.round((self.canvas.width-20) - ((((value.y - OldMin) * NewRange) / OldRange) + NewMin))
    };
    self.drawPoints.push(obj);
    if(self.drawPoints[index-1]){
    var prevobj = {x:self.drawPoints[index -1].x, y: self.drawPoints[index-1].y};
    self.points.push(prevobj);
  }else{
    console.log('this happens');
    self.points.push({x: 0, y:0});
  }
  });
  this.points[0] = {x:this.drawPoints[0].x, y:this.drawPoints[0].y};
  console.log(this.points);
  console.log(this.drawPoints);
}

Graph.prototype.drawAxis = function(){
  ctx = this.canvas.getContext('2d');
  var padding = this.canvas.width /10;
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(padding/2, this.canvas.height-(padding/2));
  ctx.lineTo(this.canvas.width, this.canvas.height-(padding/2));
  ctx.moveTo(padding/2, 0);
  ctx.lineTo(padding/2, this.canvas.height-(padding/2));
  ctx.strokeStyle = "#777777";
  ctx.stroke();
  ctx.restore();

  ctx.save();
  ctx.beginPath();
  ctx.fillStyle = "#000";
  ctx.font = "12px Arial";
  ctx.fillText("X", (padding/4), this.canvas.height-(padding/2)+3);
  ctx.fillText("Y", (padding/2)-5, this.canvas.height-(padding/4)+5);
  ctx.fill();
  ctx.restore();

}

Graph.prototype.draw = function(e) {
    var canvas = this.canvas
    this.canvas.style.cursor = "crosshair";
    var ctx = canvas.getContext("2d");
    var point = "";
    var i = 0;
    var divisible = this.realWidth / this.points.length;
    ctx.clearRect(0, 0, canvas.width, canvas.height); //Simple stuff to fill out our canvas
    ctx.fillStyle = "#FFF";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#FFF";
    var padding = this.canvas.width /10;

    ctx.beginPath();
    ctx.save();
    var self = this;
    ctx.moveTo(this.points[0].x, this.points[0].y);
    var i = 0;
    while(i < this.points.length){
    if(this.points[i].x == this.drawPoints[i].x && this.points[i].y == this.drawPoints[i].y){
      ctx.lineTo(this.points[i].x, this.points[i].y);
      if(i == this.points.length-1 && this.position.x == 0 && this.position.y == 0){
        this.position = {x: 1, y:1};
      }
    }else{
        var xdiff = Math.abs(this.drawPoints[i].x - this.points[i].x);
        var ydiff = Math.abs(this.drawPoints[i].y - this.points[i].y);
        //Here is where we determine the speed of the graph being drawn
        var mindiffx = this.canvas.width /100;
        var mindiffy = this.canvas.height /100;
        //console.log(xdiff);
        if(xdiff > mindiffx){
        xdiff = xdiff/6;
        }
        if(ydiff > mindiffy){
        ydiff = ydiff /6;
        }
        if(this.points[i].x < this.drawPoints[i].x){
          this.points[i].x +=xdiff;
        }else if(this.points[i].x > this.drawPoints[i].x){
          this.points[i].x -=xdiff;
        }

        if(this.points[i].y < this.drawPoints[i].y){
          this.points[i].y +=ydiff;
        }else if(this.points[i].y > this.drawPoints[i].y){
          this.points[i].y -=ydiff;
        }
        ctx.lineTo(this.points[i].x, this.points[i].y);
        i = this.points.length+1;
      }
      i++;
    }
    ctx.strokeStyle = '#00C853';
    ctx.lineWidth = 2 * this.ratio;
    ctx.shadowColor = '#999';
    ctx.shadowBlur = 1;
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    ctx.stroke();
    ctx.restore();

    if(this.position.x){
      var closest = closest(this.position.x, this.points);
      if(closest.x != this.tooltip.oldx){
        this.tooltip.oldx = closest.x;
        this.tooltip.radius = 0;
      }
      //Draw Line
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(closest.x, 0);
      ctx.lineTo(closest.x, canvas.height-padding/2);
      ctx.strokeStyle = "#777777";
      ctx.stroke();
      ctx.restore();
      //Draw cirlce
      ctx.save();
      ctx.beginPath();
      ctx.arc(closest.x, closest.y, this.tooltip.radius*this.ratio, 0, 2 * Math.PI, false);
      if(this.tooltip.radius < 5){
        this.tooltip.radius += 0.25;
      }
      ctx.fillStyle = "#00C853";
      ctx.shadowColor = '#999';
      ctx.shadowBlur = 10;
      ctx.shadowOffsetX = 2;
      ctx.shadowOffsetY = 2;
      ctx.fill();
      ctx.lineWidth = 2;
      ctx.strokeStyle = '#333';
      ctx.stroke();
      ctx.restore();
      //Make the axis and labels
      this.drawAxis();
      //Make the tooltip
      this.drawTooltip(closest);
    }

    function closest(num, arr) {
                    var curr = arr[0];
                    var diff = Math.abs (num - curr.x);
                    for (var val = 0; val < arr.length; val++) {
                        var newdiff = Math.abs (num - arr[val].x);
                        if (newdiff < diff) {
                            diff = newdiff;
                            curr = arr[val];
                            curr.index = val;
                        }
                    }
                    return curr;
                }
};

Graph.prototype.drawTooltip = function(closest){
  //Draw tooltip
  var ctx = this.canvas.getContext("2d");
  if(closest.index == undefined){
    closest.index = 0;
  }
  var toolTipText = "X:"+this.dataset[closest.index].x+" Y:"+this.dataset[closest.index].y;
  ctx.font = "15px Arial";
  var toolTip = ctx.measureText(toolTipText).width +15;
  //console.log(toolTip);
  var displacement = 20*this.ratio;
  if(this.position.x > closest.x){
    displacement = -(20 + toolTip)*this.ratio;
  }
  var rest = {x: closest.x+displacement, y: closest.y-10};
  var dif = {x: Math.abs(this.tooltip.x - rest.x)/15, y: Math.abs(this.tooltip.y - rest.y)/15};
  if(this.tooltip.x != rest.x ){
    if(rest.x > this.tooltip.x){
      this.tooltip.x += dif.x;
    }else{
      this.tooltip.x -= dif.x;
    }
  }

  if(this.tooltip.y != rest.y ){
    if(rest.y > this.tooltip.y){
      this.tooltip.y += dif.y;
    }else{
      this.tooltip.y -= dif.y;
    }
  }

  ctx.save();
  ctx.beginPath();
  ctx.rect(this.tooltip.x, this.tooltip.y, toolTip*this.ratio, 20*this.ratio);
  ctx.fillStyle = "#cccccc";
  ctx.shadowColor = '#999';
  ctx.shadowBlur = 10;
  ctx.shadowOffsetX = 5;
  ctx.shadowOffsetY = 5;
  ctx.fill();
  ctx.restore();

  //Draw up the text for the tooltip.
  ctx.save();
  ctx.beginPath();
  ctx.fillStyle = "#000";
  ctx.font = "15px Arial";
  ctx.fillText(toolTipText,this.tooltip.x+5,this.tooltip.y+15);
  ctx.fill();
  ctx.restore();
}

///###### This is where we will store our helper functions ######//

//####### Get the mouse postion on the canvas ########
Graph.prototype.getMousePos = function(evt) {
    evt.preventDefault();
    var rect = this.canvas.getBoundingClientRect();
    if (window.event.touches) {
        return {
            x: (window.event.touches[0].pageX - rect.left) * this.ratio,
            y: (window.event.touches[0].pageY - rect.top) * this.ratio
        };
    } else {
        return {
            x: (evt.clientX - rect.left) * this.ratio,
            y: (evt.clientY - rect.top) * this.ratio
        };
    }
}

//########### Make the graph high resolution ###########
Graph.prototype.makeHighRes = function() {
    var ctx = this.canvas.getContext('2d');
    // finally query the various pixel ratios
    var devicePixelRatio = window.devicePixelRatio || 1;
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
        ctx.mozBackingStorePixelRatio ||
        ctx.msBackingStorePixelRatio ||
        ctx.oBackingStorePixelRatio ||
        ctx.backingStorePixelRatio || 1;
    var ratio = devicePixelRatio / backingStoreRatio;
    // upscale canvas if the two ratios don't match
    if (devicePixelRatio !== backingStoreRatio) {

        var oldWidth = this.canvas.width;
        var oldHeight = this.canvas.height;
        this.canvas.width = Math.round(oldWidth * ratio);
        this.canvas.height = Math.round(oldHeight * ratio);
        this.canvas.style.width = oldWidth + 'px';
        this.canvas.style.height = oldHeight + 'px';
        // now scale the context to counter
        // the fact that we've manually scaled
        // our canvas element
        ctx.save();
        ctx.scale(ratio, ratio);
        this.ratio = ratio;
        ctx.restore();
    }
}

//########## Used to parse a string in to an element using jquery notation ########//
Graph.prototype.readElementString = function(data){
  var string = data; // The reason why we do this is because now string has all the methods prototyped to it
  var type = string.charAt(0);
  var name = string.substr(1);
  if(type == "#"){
    var element = document.getElementById(name);
  }else if(type == "."){
    var element = document.getElementsByClassName(name)[0];
  }else{
    var element = document.getElementsByTagName(string)[0];
  }

  return element;
}


text:
RSpec.shared_examples 'detects style' do |source, detected_style|
  it 'generates a todo based on the detected style' do
    inspect_source(cop, source, 'foo_spec.rb')

    expect(cop.config_to_allow_offenses)
      .to eq('EnforcedStyle' => detected_style)
  end
end


text:
package de.otto.edison.togglz.configuration;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import de.otto.edison.mongo.configuration.MongoConfiguration;
import de.otto.edison.mongo.configuration.MongoProperties;
import de.otto.edison.togglz.FeatureClassProvider;
import de.otto.edison.togglz.RemoteTogglzConfig;
import de.otto.edison.togglz.mongo.MongoTogglzRepository;
import org.slf4j.Logger;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.core.repository.StateRepository;
import org.togglz.core.user.UserProvider;

import static org.slf4j.LoggerFactory.getLogger;

@Configuration
@AutoConfigureAfter(MongoConfiguration.class)
@ConditionalOnProperty(prefix = "edison.togglz", name = "mongo.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnClass(MongoClient.class)
public class MongoTogglzConfiguration implements RemoteTogglzConfig {

    private static final Logger LOG = getLogger(MongoTogglzConfiguration.class);

    @Bean
    StateRepository stateRepository(final MongoDatabase mongoDatabase,
                                    final FeatureClassProvider featureClassProvider,
                                    final UserProvider userProvider,
                                    final MongoProperties mongoProperties) {
        LOG.info("===============================");
        LOG.info("Using MongoTogglzRepository with " + mongoDatabase.getClass().getSimpleName() + " MongoDatabase impl.");
        LOG.info("===============================");
        return new MongoTogglzRepository(mongoDatabase, featureClassProvider, userProvider, mongoProperties);
    }
}


text:
package com.hazelcast.projection;

import com.hazelcast.nio.serialization.impl.BinaryInterface;

import java.io.Serializable;

/**
 * Enables transforming object into other objects.
 * Exemplary usage scenario is the project() method of the {@link com.hazelcast.core.IMap}
 *

 * Only 1:1 transformations allowed. Use an Aggregator to perform N:1 or N:M aggregations.
 *

 *

 *
 *      IMap<String, Employee> employees = instance.getMap("employees");
 *
 *      Collection<String> names = employees.project(new Projection<Map.Entry<String,Employee>,String>(){
 *          @Override
 *          public String transform(Map.Entry<String, Employee>entry){
 *              return entry.getValue().getName();
 *          }
 *      });
 *
 *

 *
 * @param  input type
 * @param <O> output type
 * @since 3.8
 */
@BinaryInterface
public abstract class Projection implements Serializable {

    /**
     * Transforms the input object into the output object.
     *
     * @param input object.
     * @return the output object.
     */
    public abstract O transform(I input);

}


text:
set -o errexit

CMD="/usr/bin/swift-account-server"
ARGS="/etc/swift/account-server.conf --verbose"

# Loading common functions.
source /opt/kolla/kolla-common.sh

# Execute config strategy
set_configs

exec $CMD $ARGS


text:
require 'rubygems'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'echonest'
require 'highline'

include EchoNest

EchoNest.api_key = "CREDOYO7GFJ9OW3TV"

HighLine.track_eof = false
highline = HighLine.new

artist_name = highline.ask "Please type an artist name? "
artist_search = Artist.find artist_name
search_names = artist_search.map(&:name)
highline.say "Found #{search_names.length}"
choice = highline.choose do |menu|
  menu.select_by = :index
  menu.choices(*search_names)
end
idx = search_names.index choice
highline.say "Finding audio for #{artist_search[idx].name} - #{artist_search[idx].id}"
artist = Artist.new artist_search[idx].id
audio = artist.audio
highline.say "Found #{audio.found}, retrieved #{audio.length}"
highline.say highline.list( audio.map(&:title) )
while highline.agree "Next?"
  audio.next_page
  highline.say highline.list( audio.map(&:title) )
end


text:
#define USE_ERROR
//#define USE_TRACE

#include "Ports.h"
#include "PLATFORM_API_LinuxOS_ALSA_CommonUtils.h"
#include <alsa/asoundlib.h>

#if USE_PORTS == TRUE

#define MAX_ELEMS (300)
#define MAX_CONTROLS (MAX_ELEMS * 4)

#define CHANNELS_MONO (SND_MIXER_SCHN_LAST + 1)
#define CHANNELS_STEREO (SND_MIXER_SCHN_LAST + 2)

typedef struct {
    snd_mixer_elem_t* elem;
    INT32 portType; /* one of PORT_XXX_xx */
    char* controlType; /* one of CONTROL_TYPE_xx */
    /* Values: either SND_MIXER_SCHN_FRONT_xx, CHANNELS_MONO or CHANNELS_STEREO.
       For SND_MIXER_SCHN_FRONT_xx, exactly this channel is set/retrieved directly.
       For CHANNELS_MONO, ALSA channel SND_MIXER_SCHN_MONO is set/retrieved directly.
       For CHANNELS_STEREO, ALSA channels SND_MIXER_SCHN_FRONT_LEFT and SND_MIXER_SCHN_FRONT_RIGHT
       are set after a calculation that takes balance into account. Retrieved? Average of both
       channels? (Using a cached value is not a good idea since the value in the HW may have been
       altered.) */
    INT32 channel;
} PortControl;

typedef struct tag_PortMixer {
    snd_mixer_t* mixer_handle;
    /* Number of array elements used in elems and types. */
    int numElems;
    snd_mixer_elem_t** elems;
    /* Array of port types (PORT_SRC_UNKNOWN etc.). Indices are the same as in elems. */
    INT32* types;
    /* Number of array elements used in controls. */
    int numControls;
    PortControl* controls;
} PortMixer;

///// implemented functions of Ports.h

INT32 PORT_GetPortMixerCount() {
    INT32 mixerCount;
    int card;
    char devname[16];
    int err;
    snd_ctl_t *handle;
    snd_ctl_card_info_t* info;

    TRACE0("> PORT_GetPortMixerCount\n");

    initAlsaSupport();

    snd_ctl_card_info_malloc(&info);
    card = -1;
    mixerCount = 0;
    if (snd_card_next(&card) >= 0) {
        while (card >= 0) {
            sprintf(devname, ALSA_HARDWARE_CARD, card);
            TRACE1("PORT_GetPortMixerCount: Opening alsa device \"%s\"...\n", devname);
            err = snd_ctl_open(&handle, devname, 0);
            if (err < 0) {
                ERROR2("ERROR: snd_ctl_open, card=%d: %s\n", card, snd_strerror(err));
            } else {
                mixerCount++;
                snd_ctl_close(handle);
            }
            if (snd_card_next(&card) < 0) {
                break;
            }
        }
    }
    snd_ctl_card_info_free(info);
    TRACE0("< PORT_GetPortMixerCount\n");
    return mixerCount;
}

INT32 PORT_GetPortMixerDescription(INT32 mixerIndex, PortMixerDescription* description) {
    snd_ctl_t* handle;
    snd_ctl_card_info_t* card_info;
    char devname[16];
    int err;
    char buffer[100];

    TRACE0("> PORT_GetPortMixerDescription\n");
    snd_ctl_card_info_malloc(&card_info);

    sprintf(devname, ALSA_HARDWARE_CARD, (int) mixerIndex);
    TRACE1("Opening alsa device \"%s\"...\n", devname);
    err = snd_ctl_open(&handle, devname, 0);
    if (err < 0) {
        ERROR2("ERROR: snd_ctl_open, card=%d: %s\n", (int) mixerIndex, snd_strerror(err));
        return FALSE;
    }
    err = snd_ctl_card_info(handle, card_info);
    if (err < 0) {
        ERROR2("ERROR: snd_ctl_card_info, card=%d: %s\n", (int) mixerIndex, snd_strerror(err));
    }
    strncpy(description->name, snd_ctl_card_info_get_id(card_info), PORT_STRING_LENGTH - 1);
    sprintf(buffer, " [%s]", devname);
    strncat(description->name, buffer, PORT_STRING_LENGTH - 1 - strlen(description->name));
    strncpy(description->vendor, "ALSA (http://www.alsa-project.org)", PORT_STRING_LENGTH - 1);
    strncpy(description->description, snd_ctl_card_info_get_name(card_info), PORT_STRING_LENGTH - 1);
    strncat(description->description, ", ", PORT_STRING_LENGTH - 1 - strlen(description->description));
    strncat(description->description, snd_ctl_card_info_get_mixername(card_info), PORT_STRING_LENGTH - 1 - strlen(description->description));
    getALSAVersion(description->version, PORT_STRING_LENGTH - 1);

    snd_ctl_close(handle);
    snd_ctl_card_info_free(card_info);
    TRACE0("< PORT_GetPortMixerDescription\n");
    return TRUE;
}

void* PORT_Open(INT32 mixerIndex) {
    char devname[16];
    snd_mixer_t* mixer_handle;
    int err;
    PortMixer* handle;

    TRACE0("> PORT_Open\n");
    sprintf(devname, ALSA_HARDWARE_CARD, (int) mixerIndex);
    if ((err = snd_mixer_open(&mixer_handle, 0)) < 0) {
        ERROR2("Mixer %s open error: %s", devname, snd_strerror(err));
        return NULL;
    }
    if ((err = snd_mixer_attach(mixer_handle, devname)) < 0) {
        ERROR2("Mixer attach %s error: %s", devname, snd_strerror(err));
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    if ((err = snd_mixer_selem_register(mixer_handle, NULL, NULL)) < 0) {
        ERROR1("Mixer register error: %s", snd_strerror(err));
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    err = snd_mixer_load(mixer_handle);
    if (err < 0) {
        ERROR2("Mixer %s load error: %s", devname, snd_strerror(err));
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    handle = (PortMixer*) calloc(1, sizeof(PortMixer));
    if (handle == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    handle->numElems = 0;
    handle->elems = (snd_mixer_elem_t**) calloc(MAX_ELEMS, sizeof(snd_mixer_elem_t*));
    if (handle->elems == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        free(handle);
        return NULL;
    }
    handle->types = (INT32*) calloc(MAX_ELEMS, sizeof(INT32));
    if (handle->types == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        free(handle->elems);
        free(handle);
        return NULL;
    }
    handle->controls = (PortControl*) calloc(MAX_CONTROLS, sizeof(PortControl));
    if (handle->controls == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        free(handle->elems);
        free(handle->types);
        free(handle);
        return NULL;
    }
    handle->mixer_handle = mixer_handle;
    // necessary to initialize data structures
    PORT_GetPortCount(handle);
    TRACE0("< PORT_Open\n");
    return handle;
}

void PORT_Close(void* id) {
    TRACE0("> PORT_Close\n");
    if (id != NULL) {
        PortMixer* handle = (PortMixer*) id;
        if (handle->mixer_handle != NULL) {
            snd_mixer_close(handle->mixer_handle);
        }
        if (handle->elems != NULL) {
            free(handle->elems);
        }
        if (handle->types != NULL) {
            free(handle->types);
        }
        if (handle->controls != NULL) {
            free(handle->controls);
        }
        free(handle);
    }
    TRACE0("< PORT_Close\n");
}

INT32 PORT_GetPortCount(void* id) {
    PortMixer* portMixer;
    snd_mixer_elem_t *elem;

    TRACE0("> PORT_GetPortCount\n");
    if (id == NULL) {
        // $$mp: Should become a descriptive error code (invalid handle).
        return -1;
    }
    portMixer = (PortMixer*) id;
    if (portMixer->numElems == 0) {
        for (elem = snd_mixer_first_elem(portMixer->mixer_handle); elem; elem = snd_mixer_elem_next(elem)) {
            if (!snd_mixer_selem_is_active(elem))
                continue;
            TRACE2("Simple mixer control '%s',%i\n",
                   snd_mixer_selem_get_name(elem),
                   snd_mixer_selem_get_index(elem));
            if (snd_mixer_selem_has_playback_volume(elem)) {
                portMixer->elems[portMixer->numElems] = elem;
                portMixer->types[portMixer->numElems] = PORT_DST_UNKNOWN;
                portMixer->numElems++;
            }
            // to prevent buffer overflow
            if (portMixer->numElems >= MAX_ELEMS) {
                break;
            }
            /* If an element has both playback an capture volume, it is put into the arrays
               twice. */
            if (snd_mixer_selem_has_capture_volume(elem)) {
                portMixer->elems[portMixer->numElems] = elem;
                portMixer->types[portMixer->numElems] = PORT_SRC_UNKNOWN;
                portMixer->numElems++;
            }
            // to prevent buffer overflow
            if (portMixer->numElems >= MAX_ELEMS) {
                break;
            }
        }
    }
    TRACE0("< PORT_GetPortCount\n");
    return portMixer->numElems;
}

INT32 PORT_GetPortType(void* id, INT32 portIndex) {
    PortMixer* portMixer;
    INT32 type;
    TRACE0("> PORT_GetPortType\n");
    if (id == NULL) {
        // $$mp: Should become a descriptive error code (invalid handle).
        return -1;
    }
    portMixer = (PortMixer*) id;
    if (portIndex < 0 || portIndex >= portMixer->numElems) {
        // $$mp: Should become a descriptive error code (index out of bounds).
        return -1;
    }
    type = portMixer->types[portIndex];
    TRACE0("< PORT_GetPortType\n");
    return type;
}

INT32 PORT_GetPortName(void* id, INT32 portIndex, char* name, INT32 len) {
    PortMixer* portMixer;
    const char* nam;

    TRACE0("> PORT_GetPortName\n");
    if (id == NULL) {
        // $$mp: Should become a descriptive error code (invalid handle).
        return -1;
    }
    portMixer = (PortMixer*) id;
    if (portIndex < 0 || portIndex >= portMixer->numElems) {
        // $$mp: Should become a descriptive error code (index out of bounds).
        return -1;
    }
    nam = snd_mixer_selem_get_name(portMixer->elems[portIndex]);
    strncpy(name, nam, len - 1);
    name[len - 1] = 0;
    TRACE0("< PORT_GetPortName\n");
    return TRUE;
}

static int isPlaybackFunction(INT32 portType) {
        return (portType & PORT_DST_MASK);
}

/* Sets portControl to a pointer to the next free array element in the PortControl (pointer)
   array of the passed portMixer. Returns TRUE if successful. May return FALSE if there is no
   free slot. In this case, portControl is not altered */
static int getControlSlot(PortMixer* portMixer, PortControl** portControl) {
    if (portMixer->numControls >= MAX_CONTROLS) {
        return FALSE;
    } else {
        *portControl = &(portMixer->controls[portMixer->numControls]);
        portMixer->numControls++;
        return TRUE;
    }
}

/* Protect against illegal min-max values, preventing divisions by zero.
 */
inline static long getRange(long min, long max) {
    if (max > min) {
        return max - min;
    } else {
        return 1;
    }
}

/* Idea: we may specify that if unit is an empty string, the values are linear and if unit is "dB",
   the values are logarithmic.
*/
static void* createVolumeControl(PortControlCreator* creator,
                                 PortControl* portControl,
                                 snd_mixer_elem_t* elem, int isPlayback) {
    void* control;
    float precision;
    long min, max;

    if (isPlayback) {
        snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
    } else {
        snd_mixer_selem_get_capture_volume_range(elem, &min, &max);
    }
    /* $$mp: The volume values retrieved with the ALSA API are strongly supposed to be logarithmic.
       So the following calculation is wrong. However, there is no correct calculation, since
       for equal-distant logarithmic steps, the precision expressed in linear varies over the
       scale. */
    precision = 1.0F / getRange(min, max);
    control = (creator->newFloatControl)(creator, portControl, CONTROL_TYPE_VOLUME, 0.0F, +1.0F, precision, "");
    return control;
}

void PORT_GetControls(void* id, INT32 portIndex, PortControlCreator* creator) {
    PortMixer* portMixer;
    snd_mixer_elem_t* elem;
    void* control;
    PortControl* portControl;
    void* controls[10];
    int numControls;
    char* portName;
    int isPlayback;
    int isMono;
    int isStereo;
    char* type;
    snd_mixer_selem_channel_id_t channel;

    TRACE0("> PORT_GetControls\n");
    if (id == NULL) {
        ERROR0("Invalid handle!");
        // $$mp: an error code should be returned.
        return;
    }
    portMixer = (PortMixer*) id;
    if (portIndex < 0 || portIndex >= portMixer->numElems) {
        ERROR0("Port index out of range!");
        // $$mp: an error code should be returned.
        return;
    }
    numControls = 0;
    elem = portMixer->elems[portIndex];
    if (snd_mixer_selem_has_playback_volume(elem) || snd_mixer_selem_has_capture_volume(elem)) {
        /* Since we've splitted/duplicated elements with both playback and capture on the recovery
           of elements, we now can assume that we handle only to deal with either playback or
           capture. */
        isPlayback = isPlaybackFunction(portMixer->types[portIndex]);
        isMono = (isPlayback && snd_mixer_selem_is_playback_mono(elem)) ||
            (!isPlayback && snd_mixer_selem_is_capture_mono(elem));
        isStereo = (isPlayback &&
                    snd_mixer_selem_has_playback_channel(elem, SND_MIXER_SCHN_FRONT_LEFT) &&
                    snd_mixer_selem_has_playback_channel(elem, SND_MIXER_SCHN_FRONT_RIGHT)) ||
            (!isPlayback &&
             snd_mixer_selem_has_capture_channel(elem, SND_MIXER_SCHN_FRONT_LEFT) &&
             snd_mixer_selem_has_capture_channel(elem, SND_MIXER_SCHN_FRONT_RIGHT));
        // single volume control
        if (isMono || isStereo) {
            if (getControlSlot(portMixer, &portControl)) {
                portControl->elem = elem;
                portControl->portType = portMixer->types[portIndex];
                portControl->controlType = CONTROL_TYPE_VOLUME;
                if (isMono) {
                    portControl->channel = CHANNELS_MONO;
                } else {
                    portControl->channel = CHANNELS_STEREO;
                }
                control = createVolumeControl(creator, portControl, elem, isPlayback);
                if (control != NULL) {
                    controls[numControls++] = control;
                }
            }
        } else { // more than two channels, each channels has its own control.
            for (channel = SND_MIXER_SCHN_FRONT_LEFT; channel <= SND_MIXER_SCHN_LAST; channel++) {
                if (isPlayback && snd_mixer_selem_has_playback_channel(elem, channel) ||
                    !isPlayback && snd_mixer_selem_has_capture_channel(elem, channel)) {
                    if (getControlSlot(portMixer, &portControl)) {
                        portControl->elem = elem;
                        portControl->portType = portMixer->types[portIndex];
                        portControl->controlType = CONTROL_TYPE_VOLUME;
                        portControl->channel = channel;
                        control = createVolumeControl(creator, portControl, elem, isPlayback);
                        // We wrap in a compound control to provide the channel name.
                        if (control != NULL) {
                            /* $$mp 2003-09-14: The following cast shouln't be necessary. Instead, the
                               declaration of PORT_NewCompoundControlPtr in Ports.h should be changed
                               to take a const char* parameter. */
                            control = (creator->newCompoundControl)(creator, (char*) snd_mixer_selem_channel_name(channel), &control, 1);
                        }
                        if (control != NULL) {
                            controls[numControls++] = control;
                        }
                    }
                }
            }
        }
        // BALANCE control
        if (isStereo) {
            if (getControlSlot(portMixer, &portControl)) {
                portControl->elem = elem;
                portControl->portType = portMixer->types[portIndex];
                portControl->controlType = CONTROL_TYPE_BALANCE;
                portControl->channel = CHANNELS_STEREO;
                /* $$mp: The value for precision is chosen more or less arbitrarily. */
                control = (creator->newFloatControl)(creator, portControl, CONTROL_TYPE_BALANCE, -1.0F, 1.0F, 0.01F, "");
                if (control != NULL) {
                    controls[numControls++] = control;
                }
            }
        }
    }
    if (snd_mixer_selem_has_playback_switch(elem) || snd_mixer_selem_has_capture_switch(elem)) {
        if (getControlSlot(portMixer, &portControl)) {
            type = isPlayback ? CONTROL_TYPE_MUTE : CONTROL_TYPE_SELECT;
            portControl->elem = elem;
            portControl->portType = portMixer->types[portIndex];
            portControl->controlType = type;
            control = (creator->newBooleanControl)(creator, portControl, type);
            if (control != NULL) {
                controls[numControls++] = control;
            }
        }
    }
    /* $$mp 2003-09-14: The following cast shouln't be necessary. Instead, the
       declaration of PORT_NewCompoundControlPtr in Ports.h should be changed
       to take a const char* parameter. */
    portName = (char*) snd_mixer_selem_get_name(elem);
    control = (creator->newCompoundControl)(creator, portName, controls, numControls);
    if (control != NULL) {
        (creator->addControl)(creator, control);
    }
    TRACE0("< PORT_GetControls\n");
}

INT32 PORT_GetIntValue(void* controlIDV) {
    PortControl* portControl = (PortControl*) controlIDV;
    int value = 0;
    snd_mixer_selem_channel_id_t channel;

    if (portControl != NULL) {
        switch (portControl->channel) {
        case CHANNELS_MONO:
            channel = SND_MIXER_SCHN_MONO;
            break;

        case CHANNELS_STEREO:
            channel = SND_MIXER_SCHN_FRONT_LEFT;
            break;

        default:
            channel = portControl->channel;
        }
        if (portControl->controlType == CONTROL_TYPE_MUTE ||
            portControl->controlType == CONTROL_TYPE_SELECT) {
            if (isPlaybackFunction(portControl->portType)) {
                snd_mixer_selem_get_playback_switch(portControl->elem, channel, &value);
            } else {
                snd_mixer_selem_get_capture_switch(portControl->elem, channel, &value);
            }
            if (portControl->controlType == CONTROL_TYPE_MUTE) {
                value = ! value;
            }
        } else {
            ERROR1("PORT_GetIntValue(): inappropriate control type: %s\n",
                   portControl->controlType);
        }
    }
    return (INT32) value;
}

void PORT_SetIntValue(void* controlIDV, INT32 value) {
    PortControl* portControl = (PortControl*) controlIDV;
    snd_mixer_selem_channel_id_t channel;

    if (portControl != NULL) {
        if (portControl->controlType == CONTROL_TYPE_MUTE) {
            value = ! value;
        }
        if (portControl->controlType == CONTROL_TYPE_MUTE ||
            portControl->controlType == CONTROL_TYPE_SELECT) {
            if (isPlaybackFunction(portControl->portType)) {
                snd_mixer_selem_set_playback_switch_all(portControl->elem, value);
            } else {
                snd_mixer_selem_set_capture_switch_all(portControl->elem, value);
            }
        } else {
            ERROR1("PORT_SetIntValue(): inappropriate control type: %s\n",
                   portControl->controlType);
        }
    }
}

static float scaleVolumeValueToNormalized(long value, long min, long max) {
    return (float) (value - min) / getRange(min, max);
}

static long scaleVolumeValueToHardware(float value, long min, long max) {
    return (long)(value * getRange(min, max) + min);
}

float getRealVolume(PortControl* portControl,
                    snd_mixer_selem_channel_id_t channel) {
    float fValue;
    long lValue = 0;
    long min = 0;
    long max = 0;

    if (isPlaybackFunction(portControl->portType)) {
        snd_mixer_selem_get_playback_volume_range(portControl->elem,
                                                  &min, &max);
        snd_mixer_selem_get_playback_volume(portControl->elem,
                                            channel, &lValue);
    } else {
        snd_mixer_selem_get_capture_volume_range(portControl->elem,
                                                 &min, &max);
        snd_mixer_selem_get_capture_volume(portControl->elem,
                                           channel, &lValue);
    }
    fValue = scaleVolumeValueToNormalized(lValue, min, max);
    return fValue;
}

void setRealVolume(PortControl* portControl,
                   snd_mixer_selem_channel_id_t channel, float value) {
    long lValue = 0;
    long min = 0;
    long max = 0;

    if (isPlaybackFunction(portControl->portType)) {
        snd_mixer_selem_get_playback_volume_range(portControl->elem,
                                                  &min, &max);
        lValue = scaleVolumeValueToHardware(value, min, max);
        snd_mixer_selem_set_playback_volume(portControl->elem,
                                            channel, lValue);
    } else {
        snd_mixer_selem_get_capture_volume_range(portControl->elem,
                                                 &min, &max);
        lValue = scaleVolumeValueToHardware(value, min, max);
        snd_mixer_selem_set_capture_volume(portControl->elem,
                                           channel, lValue);
    }
}

static float getFakeBalance(PortControl* portControl) {
    float volL, volR;

    // pan is the ratio of left and right
    volL = getRealVolume(portControl, SND_MIXER_SCHN_FRONT_LEFT);
    volR = getRealVolume(portControl, SND_MIXER_SCHN_FRONT_RIGHT);
    if (volL > volR) {
        return -1.0f + (volR / volL);
    }
    else if (volR > volL) {
        return 1.0f - (volL / volR);
    }
    return 0.0f;
}

static float getFakeVolume(PortControl* portControl) {
    float valueL;
    float valueR;
    float value;

    valueL = getRealVolume(portControl, SND_MIXER_SCHN_FRONT_LEFT);
    valueR = getRealVolume(portControl, SND_MIXER_SCHN_FRONT_RIGHT);
    // volume is the greater value of both
    value = valueL > valueR ? valueL : valueR ;
    return value;
}

/*
 * sets the unsigned values for left and right volume according to
 * the given volume (0...1) and balance (-1..0..+1)
 */
static void setFakeVolume(PortControl* portControl, float vol, float bal) {
    float volumeLeft;
    float volumeRight;

    if (bal < 0.0f) {
        volumeLeft = vol;
        volumeRight = vol * (bal + 1.0f);
    } else {
        volumeLeft = vol * (1.0f - bal);
        volumeRight = vol;
    }
    setRealVolume(portControl, SND_MIXER_SCHN_FRONT_LEFT, volumeLeft);
    setRealVolume(portControl, SND_MIXER_SCHN_FRONT_RIGHT, volumeRight);
}

float PORT_GetFloatValue(void* controlIDV) {
    PortControl* portControl = (PortControl*) controlIDV;
    float value = 0.0F;

    if (portControl != NULL) {
        if (portControl->controlType == CONTROL_TYPE_VOLUME) {
            switch (portControl->channel) {
            case CHANNELS_MONO:
                value = getRealVolume(portControl, SND_MIXER_SCHN_MONO);
                break;

            case CHANNELS_STEREO:
                value = getFakeVolume(portControl);
                break;

            default:
                value = getRealVolume(portControl, portControl->channel);
            }
        } else if (portControl->controlType == CONTROL_TYPE_BALANCE) {
            if (portControl->channel == CHANNELS_STEREO) {
                value = getFakeBalance(portControl);
            } else {
                ERROR0("PORT_GetFloatValue(): Balance only allowed for stereo channels!\n");
            }
        } else {
            ERROR1("PORT_GetFloatValue(): inappropriate control type: %s!\n",
                   portControl->controlType);
        }
    }
    return value;
}

void PORT_SetFloatValue(void* controlIDV, float value) {
    PortControl* portControl = (PortControl*) controlIDV;

    if (portControl != NULL) {
        if (portControl->controlType == CONTROL_TYPE_VOLUME) {
            switch (portControl->channel) {
            case CHANNELS_MONO:
                setRealVolume(portControl, SND_MIXER_SCHN_MONO, value);
                break;

            case CHANNELS_STEREO:
                setFakeVolume(portControl, value, getFakeBalance(portControl));
                break;

            default:
                setRealVolume(portControl, portControl->channel, value);
            }
        } else if (portControl->controlType == CONTROL_TYPE_BALANCE) {
            if (portControl->channel == CHANNELS_STEREO) {
                setFakeVolume(portControl, getFakeVolume(portControl), value);
            } else {
                ERROR0("PORT_SetFloatValue(): Balance only allowed for stereo channels!\n");
            }
        } else {
            ERROR1("PORT_SetFloatValue(): inappropriate control type: %s!\n",
                   portControl->controlType);
        }
    }
}

#endif // USE_PORTS


text:
package services

import (
	"fmt"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/gravitational/trace"
	"github.com/stretchr/testify/require"

	apidefaults "github.com/gravitational/teleport/api/defaults"
	"github.com/gravitational/teleport/api/types"
	"github.com/gravitational/teleport/lib/defaults"
)

// TestServersCompare tests comparing two servers
func TestServersCompare(t *testing.T) {
	t.Parallel()

	node := &types.ServerV2{
		Kind:    types.KindNode,
		Version: types.V2,
		Metadata: types.Metadata{
			Name:      "node1",
			Namespace: apidefaults.Namespace,
			Labels:    map[string]string{"a": "b"},
		},
		Spec: types.ServerSpecV2{
			Addr:      "localhost:3022",
			CmdLabels: map[string]types.CommandLabelV2{"a": {Period: types.Duration(time.Minute), Command: []string{"ls", "-l"}}},
			Version:   "4.0.0",
		},
	}
	node.SetExpiry(time.Date(2018, 1, 2, 3, 4, 5, 6, time.UTC))
	// Server is equal to itself
	require.Equal(t, CompareServers(node, node), Equal)

	// Only timestamps are different
	node2 := *node
	node2.SetExpiry(time.Date(2018, 1, 2, 3, 4, 5, 8, time.UTC))
	require.Equal(t, CompareServers(node, &node2), OnlyTimestampsDifferent)

	// Labels are different
	node2 = *node
	node2.Metadata.Labels = map[string]string{"a": "d"}
	require.Equal(t, CompareServers(node, &node2), Different)

	// Command labels are different
	node2 = *node
	node2.Spec.CmdLabels = map[string]types.CommandLabelV2{"a": {Period: types.Duration(time.Minute), Command: []string{"ls", "-lR"}}}
	require.Equal(t, CompareServers(node, &node2), Different)

	// Address has changed
	node2 = *node
	node2.Spec.Addr = "localhost:3033"
	require.Equal(t, CompareServers(node, &node2), Different)

	// Public addr has changed
	node2 = *node
	node2.Spec.PublicAddr = "localhost:3033"
	require.Equal(t, CompareServers(node, &node2), Different)

	// Hostname has changed
	node2 = *node
	node2.Spec.Hostname = "luna2"
	require.Equal(t, CompareServers(node, &node2), Different)

	// TeleportVersion has changed
	node2 = *node
	node2.Spec.Version = "5.0.0"
	require.Equal(t, CompareServers(node, &node2), Different)

	// Rotation has changed
	node2 = *node
	node2.Spec.Rotation = types.Rotation{
		State:       types.RotationStateInProgress,
		Phase:       types.RotationPhaseUpdateClients,
		CurrentID:   "1",
		Started:     time.Date(2018, 3, 4, 5, 6, 7, 8, time.UTC),
		GracePeriod: types.Duration(3 * time.Hour),
		LastRotated: time.Date(2017, 2, 3, 4, 5, 6, 7, time.UTC),
		Schedule: types.RotationSchedule{
			UpdateClients: time.Date(2018, 3, 4, 5, 6, 7, 8, time.UTC),
			UpdateServers: time.Date(2018, 3, 4, 7, 6, 7, 8, time.UTC),
			Standby:       time.Date(2018, 3, 4, 5, 6, 13, 8, time.UTC),
		},
	}
	require.Equal(t, CompareServers(node, &node2), Different)
}

// TestGuessProxyHostAndVersion checks that the GuessProxyHostAndVersion
// correctly guesses the public address of the proxy (Teleport Cluster).
func TestGuessProxyHostAndVersion(t *testing.T) {
	t.Parallel()

	// No proxies passed in.
	host, version, err := GuessProxyHostAndVersion(nil)
	require.Equal(t, host, "")
	require.Equal(t, version, "")
	require.True(t, trace.IsNotFound(err))

	// No proxies have public address set.
	proxyA := types.ServerV2{}
	proxyA.Spec.Hostname = "test-A"
	proxyA.Spec.Version = "test-A"

	host, version, err = GuessProxyHostAndVersion([]types.Server{&proxyA})
	require.Equal(t, host, fmt.Sprintf("%v:%v", proxyA.Spec.Hostname, defaults.HTTPListenPort))
	require.Equal(t, version, proxyA.Spec.Version)
	require.NoError(t, err)

	// At least one proxy has public address set.
	proxyB := types.ServerV2{}
	proxyB.Spec.PublicAddr = "test-B"
	proxyB.Spec.Version = "test-B"

	host, version, err = GuessProxyHostAndVersion([]types.Server{&proxyA, &proxyB})
	require.Equal(t, host, proxyB.Spec.PublicAddr)
	require.Equal(t, version, proxyB.Spec.Version)
	require.NoError(t, err)
}

func TestUnmarshalServerKubernetes(t *testing.T) {
	t.Parallel()

	// Regression test for
	// https://github.com/gravitational/teleport/issues/4862
	//
	// Verifies unmarshaling succeeds, when provided a 4.4 server JSON
	// definition.
	tests := []struct {
		desc string
		in   string
		want *types.ServerV2
	}{
		{
			desc: "4.4 kubernetes_clusters field",
			in: `{
	"version": "v2",
	"kind": "kube_service",
	"metadata": {
		"name": "foo"
	},
	"spec": {
		"kubernetes_clusters": ["a", "b", "c"]
	}
}`,
			want: &types.ServerV2{
				Version: types.V2,
				Kind:    types.KindKubeService,
				Metadata: types.Metadata{
					Name:      "foo",
					Namespace: apidefaults.Namespace,
				},
			},
		},
		{
			desc: "5.0 kubernetes_clusters field",
			in: `{
	"version": "v2",
	"kind": "kube_service",
	"metadata": {
		"name": "foo"
	},
	"spec": {
		"kube_clusters": [{"name": "a"}, {"name": "b"}, {"name": "c"}]
	}
}`,
			want: &types.ServerV2{
				Version: types.V2,
				Kind:    types.KindKubeService,
				Metadata: types.Metadata{
					Name:      "foo",
					Namespace: apidefaults.Namespace,
				},
				Spec: types.ServerSpecV2{
					KubernetesClusters: []*types.KubernetesCluster{
						{Name: "a"},
						{Name: "b"},
						{Name: "c"},
					},
				},
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.desc, func(t *testing.T) {
			got, err := UnmarshalServer([]byte(tt.in), types.KindKubeService)
			require.NoError(t, err)
			require.Empty(t, cmp.Diff(got, tt.want))
		})
	}
}

// TestOnlyTimestampsDifferent tests that OnlyTimestampsDifferent is returned
// after checking that whether KubernetesClusters and Apps are different.
func TestOnlyTimestampsDifferent(t *testing.T) {
	t.Parallel()

	now := time.Now()
	later := now.Add(time.Minute)

	tests := []struct {
		desc   string
		a      types.Resource
		b      types.Resource
		expect int
	}{
		{
			desc: "Kube cluster change returns Different",
			a: &types.ServerV2{
				Spec: types.ServerSpecV2{KubernetesClusters: []*types.KubernetesCluster{}},
				Metadata: types.Metadata{
					Expires: &now,
				},
			},
			b: &types.ServerV2{
				Spec: types.ServerSpecV2{KubernetesClusters: []*types.KubernetesCluster{{
					Name: "test-cluster",
				}}},
				Metadata: types.Metadata{
					Expires: &later,
				},
			},
			expect: Different,
		},
		{
			desc: "No kube cluster change returns OnlyTimestampsDifferent",
			a: &types.ServerV2{
				Spec: types.ServerSpecV2{KubernetesClusters: []*types.KubernetesCluster{}},
				Metadata: types.Metadata{
					Expires: &now,
				},
			},
			b: &types.ServerV2{
				Spec: types.ServerSpecV2{KubernetesClusters: []*types.KubernetesCluster{}},
				Metadata: types.Metadata{
					Expires: &later,
				},
			},
			expect: OnlyTimestampsDifferent,
		},
		{
			desc: "Apps change returns Different",
			a: &types.ServerV2{
				Spec: types.ServerSpecV2{Apps: []*types.App{}},
				Metadata: types.Metadata{
					Expires: &now,
				},
			},
			b: &types.ServerV2{
				Spec: types.ServerSpecV2{Apps: []*types.App{{
					Name: "test-app",
				}}},
				Metadata: types.Metadata{
					Expires: &later,
				},
			},
			expect: Different,
		},
		{
			desc: "No apps change returns OnlyTimestampsDifferent",
			a: &types.ServerV2{
				Spec: types.ServerSpecV2{Apps: []*types.App{}},
				Metadata: types.Metadata{
					Expires: &now,
				},
			},
			b: &types.ServerV2{
				Spec: types.ServerSpecV2{Apps: []*types.App{}},
				Metadata: types.Metadata{
					Expires: &later,
				},
			},
			expect: OnlyTimestampsDifferent,
		},
	}

	for _, tc := range tests {
		got := CompareServers(tc.a, tc.b)
		require.Equal(t, tc.expect, got, tc.desc)
	}
}


text:
Note:
=====
This has not been maintained and/or updated since 2011.
Perhaps consider [corbym/gocrest](https://github.com/corbym/gocrest), instead.

Introduction
============

Hamcrest is a fluent framework for declarative Matcher objects
that, when applied to input values, produce self-describing
results.

Installation:
========

To install, run `make install` from the same directory as this
`README.md` file.

Packages
========

`hamcrest.go` comes in several packages that you assemble to fit your needs:

*   `hamcrest/base`:  Defines the types `Matcher`, `Result` and `SelfDescribing`
    and provides factory functions to create them.  (Unless you want to define
    your own custom Matchers, you'll only use this indirectly.)

*   `hamcrest/core`:  Defines a set of Matchers for doing basic comparisons,
    equality testing, nil checking, and grouping/composition matchers.

*   `hamcrest/slices`:  Matchers on slices, such as `EachElem`, `AnyElem`,
    `ToLen`, `Empty`.

*   `hamcrest/reflect`:  Matchers using type reflection, such as `ToType`,
    `SameTypeAs`, `SliceOf`, `MapOf`, etc.

*   `hamcrest/strings`:  Matchers for strings.

*   `hamcrest/asserter`:  Defines an `Asserter` that can be used in conjunction
    with Hamcrest Matchers to produce helpful logging messages at runtime
    (to stdout, stderr, or any object that implements io.Writer) or in
    unit tests (using `testing.T` from Go's standard `testing` package).

    Note: the `asserter` package isn't *really* part of Hamcrest:  it's just
    a handy way of using the Hamcrest results in conjunction with the
    standard Go testing package.

You may also choose to write your own Matchers (see *Custom matchers*, below).

How to use hamcrest for testing:
================================

To use Hamcrest matchers, create an `Asserter` and use it to
`Check` or `Assert` that values meet the criteria of those
matchers:

	func TestPoint(t *testing.T) {
		p := Point(3, 4)
		we := asserter.Using(t)
		we.AssertThat(p.X, EqualTo(3).Comment("x coord"))
		we.AssertThat(p.Y, EqualTo(4).Comment("y coord"))
		we.CheckThat(p, ToString(EqualTo("[3, 4]")))
		we.CheckThat(p.Magnitude(), EqualTo(5).Comment("magnitude"))
	}

(`Assert` methods fail immediately, as `testing.T.FailNow()` does,
while `Check` methods defer failure, as `testing.T.Fail()` does.)

The `AssertThat` and `CheckThat` functions are designed to create
conditional checks that read fluently as self-commenting code, and
are self-describing when failures occur.  For example, the above
test might fail with this message:

	FAILURE on input &Point{X:3, Y:4}
		Did not match ToString(EqualTo([3, 4]))
		Because: String() was "[4, 3]"
			Did not match EqualTo[[3, 4]]
			Because: "[4, 3]" was not equal to "[3, 4]"

Or:
	FAILURE on input 5
		Did not match EqualTo(5)
		Because: uint 5 could not be compared to int 5
		Comment: magnitude

Note that the majority of the text descriptions are generated
automatically by the matchers.  For typical uses of Hamcrest
matchers, the code is largely self-documenting, and the error
messages are detailed.

Effort invested in good self-describing matchers can be leveraged
across many tests.

Examples of using Hamcrest at runtime:
======================================

Just as in the testing example, create an `Asserter`, but use a factory
method such as `UsingStderr()`, which returns an `Asserter` that logs
problems to stderr and calls `panic` on `FailNow`:

	import (
		"github.com/rdrdr/hamcrest/asserter"
	)

	var we = asserter.UsingStderr()

Use that asserter during init() to make sure globals are properly
initialized:

	import (
		"github.com/rdrdr/hamcrest/asserter"
		"github.com/rdrdr/hamcrest/slices"
		. "github.com/rdrdr/hamcrest/core"
		"github.com/rdrdr/hamcrest/strings"
	)
	var we = asserter.UsingStderr()

	type Server struct {
		hostname string
		port uint16
	}
	var servers = []Server {
		{ "news.foo.com", 8000 },
		{ "news.bar.com", 8888 },
	}

	func init() {
		ToHostname := Applying(func(s Server) string {
			return s.hostname
		}, "TransformServerToHostname")
		IsInOneOfOurDomains := AnyOf(strings.HasSuffix(".foo.com"),
	                                 strings.HasSuffix(".bar.com"))
		we.FailNowUnless(servers,
			slices.EachElem(ToHostname(IsInOneOfOurDomains)))
	}

Or use the asserter at runtime to guarantee that a method's
preconditions are met:

	var IsValidFilenameForTextFile = AllOf(
		strings.HasSuffix(".txt").Comment("Must have .txt extension."),
		Not(strings.HasPattern("[ \\t\\n\\r]")).Comment("whitespace not permitted"),
		Not(strings.HasPattern("[:////\\\\]")).Comment("path separators not permitted"))

	func WriteTo(filename string) bool {
		we.AssertThat(filename, IsValidFilenameForTextFile)
		// Use filename here.
	}

Or use the asserter with `defer` to program by contract, knowing that you
can later swap out your typical `Asserter` with an
`asserter.ThatDoesNothing()` to bypass those checks:

	IsWellFormedMD5 := AllOf(
		ToLen(EqualTo(32)).Comment("MD5 hashes have length 32"),
		strings.HasPattern("^([0-9][A-F][a-f])+$").Comment("hex digits")))

	func MD5(data []byte) (result string) {
		we.AssertNonNil(data)
		defer we.AssertThat(result, IsWellFormedMD5)

		// calculate MD5 of data
	}

Or use it during development to write your tests in the same file as your code:

	func EncodePigLatin(input string) string {
		...implementation...
	}

	func init() {
		we := asserter.UsingStderr()
		ToEncoded := Applying(EncodePigLatin, "in PigLatin form")
		we.AssertThat("simple", ToEncoded(EqualTo("imple-say")))
		we.AssertThat("Capital"), ToEncoded(EqualTo("Apital-Cay")))
		we.AssertThat("prefix"), ToEncoded(EqualTo("efix-pray")))
		we.AssertThat("oops"), ToEncoded(EqualTo("oops-ay")))
		we.AssertThat("your psychotic y!"),
			ToEncoded(EqualTo("our-yay ychotic-psay y-ay!")))
	}

At some future point, this structure will make it easier to cut-and-paste
each `init()` block into your testing suite.  While moving the block over,
replace:

	func init() {
		we := asserter.UsingStderr()
		...

With an `Asserter` that uses the testing infrastructure, instead:

	func Test_EncodePigLatin(t *testing.T) {
		we := asserter.Using(t)
		...

A note on library design:
=========================

Hamcrest is designed to be a fluent library.  The Go syntax requires external
symbols be preceded by their package name, which can lead to occasionally
awkward constructions:
	we.CheckThat("foobar", core.AllOf(strings.HasPrefix("foo"), strings.HasSuffix("bar")))

To avoid this clunkiness, Hamcrest matchers are generated by functions that
you can assign to local names:
	AllOf := core.AllOf
	StartsWith := strings.HasPrefix
	EndsWith := strings.HasSuffix
	we.CheckThat("foobar", AllOf(StartsWith("foo"), EndsWith("bar")))

Performance note:
=================
Note:  Hamcrest matchers allocate Description and Result objects to
explain in great detail why they did or did not match. However, these
objects are lazily evaluated.  Users should be generally aware that
there is an *object allocation* cost to using Hamcrest matchers, but
there is (generally) no *string construction* cost unless a Hamcrest
Matcher or Result is explicitly asked to self-describe.

Still, users who are particularly sensitive to performance concerns
may wish to think carefully before using Hamcrest matchers in
performance-critical bottlenecks.

A tour of common matchers
=========================

Hamcrest comes with a library of useful matchers. Here are some of the most
common ones.

  * `Anything` - matches any input.
  * `True` - only matches bool `true`.
  * `False` - only matches bool `false`.
  * `Not(matcher)` - logical not of `matcher`.
  * `If(m1).Then(m2)` - checks that whenever `m1` matches, so does `m2`.
  * `IfAndOnlyIf(m1).Then(m2)` - checks that `m1` and `m2` both match/don't match.
  * `EqualTo(y)` - matches any value `x` where `x == y` is legal and true.
  * `NotEqualTo(y)` - matches any value `x` where `x != y` is legal and true.
  * `DeepEqualTo(y)` - matches any value `x` where `reflect.DeepEquals(x, y)` is true.
  * `GreaterThan(y)` - matches any value `x` where `x > y` is legal and true.
  * `GreaterThanOrEqualTo(y)` - matches any value `x` where `x <= y` is legal and true.
  * `LessThan(y)` - matches any value `x` where `x < y` is legal and true.
  * `LessThanOrEqualTo(y)` - matches any value `x` where `x <= y` is legal and true.
  * `Nil` - matches values of any type with an `IsNil() bool` method that returns true for the given object.
  * `NonNil` - matches values of any type with an `IsNil() bool` method that returns false for the given object.
  * `AnyOf(matchers...)` - short-circuiting n-ary logical Or.
  * `AllOf(matchers...)` - short-circuiting n-ary logical And.

Syntactic sugar
===============

Hamcrest strives to make your tests as readable as possible. For example,
the `Is` matcher is a wrapper that doesn't add any extra behavior to the
underlying matcher. The following assertions are equivalent:

    we.AssertThat(x, EqualTo(y));
    we.AssertThat(x, Is(EqualTo(y)))

Similarly, it is possible to simulate common logical conditions using the `logic`
package for readability:

  * `Is(matcher)` - equivalent to `matcher`
  * `Both(matcher1).And(matcher2)` - short-circuiting logical `And`, equivalent to `AllOf(matcher1, matcher2)`
  * `Either(matcher1).Or(matcher2)` - short-circuiting logical `Or`, equivalent to `AnyOf(matcher1, matcher2)`
  * `Neither(matcher1).Nor(matcher2)` - short-circuiting logical `Nor`
  * `If(matcher1).Then(matcher2)` - short-circuiting logical `If/Then`
  * `Iff(matcher1).Then(matcher2)` - logical `IfAndOnlyIf` (note: iff never short-circuits)
  * `Either(matcher1).Xor(matcher)` - logical `Xor` (note: xor never short-circuits)

Custom matchers
===============

Example:

	func IsMultipleOf(k int) *base.Matcher {
		match := func(n int) bool {
			return n % k == 0
		}
		return base.NewMatcherf(match, "multiple of %v", k)
	}

And used:

	we.CheckThat(recordSize, IsMultipleOf(8).Comment(
		"profiling suggests better performance than multiple of 4"))

Or, if you want more control over the error messages:

	func IsMultipleOf(k int) *base.Matcher {
		match := func(actual interface{}) *base.Result {
			if n, ok := actual.(int); ok {
				if remainder := n % k; remainder != 0 {
					return base.NewResultf(false,
						"was not a multiple of %v (remainder %v)", k, remainder)
				}
				return base.NewResultf(true, "was a multiple of %v", k)
			}
			return base.NewResultf(false, "was a %T, expected an int!", actual)
		}
		return base.NewMatcherf(match, "multiple of %v", k)
	}


text:
package org.liquigraph.trinity;

public enum CypherTransport {
    /**
     * Executes Cypher queries with Bolt protocol
     * Requires a JRE 8 and Neo4j v3
     */
    BOLT,
    /**
     * Executes Cypher queries via the REST API
     * Requires at least a JRE 7 and Neo4j v2
     */
    HTTP,
    /**
     * Executes Cypher queries via an embedded Neo4j instance
     * Requires a JRE 7 and Neo4j v2
     */
    EMBEDDED_2,
    /**
     * Executes Cypher queries via an embedded Neo4j instance
     * Requires a JRE 8 and Neo4j v3
     */
    EMBEDDED_3;
}


text:
A common concern when testing applications is how the client handles slow responses or timeout scenarios. Often times the challenge comes in finding a way to generate those conditions reliably for those test cases. While SoapUI may not be your first thought since it is an API testing tool, the ability to host [Mock Services](https://www.soapui.org/soap-mocking/service-mocking-overview.html) is built in for both SOAP and REST services. Lets take a look at how we can set up a basic mock service to test timeout conditions for our client applications.

If you don't already have a SOAPUI project you will need to create one.

## Create a Project

## Adding a Mock Service

SoapUI is a flexible tool and as usual there are multiple ways of accomplishing the same thing. It also allows you to mock a single request at a time or can autogenerate single mock service for all of your endpoints. Since the goal here is to introduce a delayed response to our application we will want to create separate mock services. This allows us to insert a delay for a specific service call without having to provide mock responses for all the services operations.

### Mock Specific Services

The steps are a subtly different when mocking SOAP and REST services.

### SOAP
Right Click on the Operation or Request node you want to mock.

![Soap AddMockService](SoapAddToMockService.png)

Enter the name of the new mock service, then click Ok.

![Soap NameMockService](SoapNameMockService.png)

Click Yes on the Open MockResponse Editor Dialog.

![Soap OpenMockResponseEditor](SoapOpenMockResponseEditor.png)

The Response Editor lets you define the response data that will be returned by the service.

![Soap ResponseEditor](SoapResponseEditor.png)

### REST

Right Click on the Request node you want to mock.

![Rest AddMockService](RestAddToMockService.png)

Enter the name of the new mock service, then click Ok.

![Rest NameMockService](RestNameMockService.png)

The mock service editor window will open.

**Note:** Rest Mock Services will be started automatically.

![Rest MockServiceEditor](RestMockServiceEditor.png)

Close the MockService Editor and follow the prompts to stop the service.

Open the MockResponse Editor Dialog.

![Rest OpenMockResponseEditor](RestOpenMockResponseEditor.png)

The Response Editor lets you define the response data that will be returned by the service.

![Rest ResponseEditor](RestResponseEditor.png)

## Adding a Response Delay

Just like with setting up the mock services, adding a response delay is handled differently with SOAP and REST services.

### SOAP

For Soap Services adding a response delay is as easy as editing a property.
Edit the response delay to your desired amount in milliseconds.

![Soap AddResponseDelay](SoapAddResponseDelay.png)

### REST

For REST services its a little more complex, we'll need to use the Groovy sleep command.

Open the Mock Service Editor

![Rest ShowMockServiceEditor](RestShowMockServiceEditor.png)

Click on the On Request Script and enter the delay you want in milliseconds using the following command *sleep([yourTimeoutHere])*

![Rest OnRequestScript](RestOnRequestScript.png)

## Start up your Mock Service

Open the Mock Service Editor by double clicking on your mock service in the navigation tree.
Click on the green triangle icon to start your service.


text:
import { OperatorFunction } from "../types";
import { map } from "../operators/map";

const { isArray } = Array;

function callOrApply<T, R>(fn: ((...values: T[]) => R), args: T|T[]): R {
    return isArray(args) ? fn(...args) : fn(args);
}

/**
 * Used in several -- mostly deprecated -- situations where we need to
 * apply a list of arguments or a single argument to a result selector.
 */
export function mapOneOrManyArgs<T, R>(fn: ((...values: T[]) => R)): OperatorFunction<T|T[], R> {
    return map(args => callOrApply(fn, args))
}


text:
namespace content {

class BrowserPlugin;
class BrowserPluginDelegate;
class RenderFrame;

// BrowserPluginManager manages the routing of messages to the appropriate
// BrowserPlugin object based on its instance ID. There is one BrowserPlugin
// for the RenderThread.
class CONTENT_EXPORT BrowserPluginManager : public RenderThreadObserver {
 public:
  static BrowserPluginManager* Get();

  BrowserPluginManager();
  ~BrowserPluginManager() override;

  // Creates a new BrowserPlugin object.
  // BrowserPlugin is responsible for associating itself with the
  // BrowserPluginManager via AddBrowserPlugin. When it is destroyed, it is
  // responsible for removing its association via RemoveBrowserPlugin.
  // The |delegate| is expected to manage its own lifetime.
  // Generally BrowserPlugin calls DidDestroyElement() on the delegate and
  // right now the delegate destroys itself once it hears that callback.
  BrowserPlugin* CreateBrowserPlugin(
      RenderFrame* render_frame,
      const base::WeakPtr<BrowserPluginDelegate>& delegate);

  void Attach(int browser_plugin_instance_id);

  void Detach(int browser_plugin_instance_id);

  void AddBrowserPlugin(int browser_plugin_instance_id,
                        BrowserPlugin* browser_plugin);
  void RemoveBrowserPlugin(int browser_plugin_instance_id);
  BrowserPlugin* GetBrowserPlugin(int browser_plugin_instance_id) const;

  void UpdateFocusState();

  // Returns a new instance ID to be used by BrowserPlugin. Instance IDs are
  // unique per process.
  int GetNextInstanceID();

  void DidCommitCompositorFrame(int render_frame_routing_id);
  bool Send(IPC::Message* msg);

  // RenderThreadObserver override.
  bool OnControlMessageReceived(const IPC::Message& message) override;

 private:
  // This map is keyed by guest instance IDs.
  IDMap<BrowserPlugin> instances_;

  DISALLOW_COPY_AND_ASSIGN(BrowserPluginManager);
};

}  // namespace content

#endif  // CONTENT_RENDERER_BROWSER_PLUGIN_BROWSER_PLUGIN_MANAGER_H_


text:
package javax.sql;

import java.sql.SQLException;

/**
 * An interface which provides functionality for a disconnected {@code RowSet}
 * to put data updates back to the data source from which the {@code RowSet} was
 * originally populated. An object implementing this interface is called a
 * writer.
 *

 * The writer must establish a connection to the {@code RowSet}'s database
 * before writing the data. The {@code RowSet} calling this interface must
 * implement the {@code RowSetInternal} interface.
 *

 * The writer may encounter a situation where the updated data needs to be
 * written back to the database, but has already been updated there in the mean
 * time. How a conflict of this kind is handled is determined by the
 * implementation of this writer.
 *
 * @see RowSetInternal
 */
public interface RowSetWriter {

    /**
     * Writes changes made in the {@code RowSet}, which is associated with this
     * {@code RowSetWriter}, back to the database.
     *
     * @param theRowSet
     *            a row set that fulfills the following criteria:
     *

     *
it must implement the {@code RowSetInternal} interface,

     *
have this {@code RowSetWriter} registered with it,

     *
must call this method internally.

     *

     * @return {@code true} if the modified data was written, {@code false}
     *         otherwise (which typically implies some form of conflict).
     * @throws SQLException
     *             if a problem occurs accessing the database.
     */
    public boolean writeData(RowSetInternal theRowSet) throws SQLException;
}