text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Advanced.Algorithms.DataStructures
{
    /// <summary>
    /// A binary heap implementation.
    /// </summary>
    public class BHeap<T> : IEnumerable<T> where T : IComparable
    {
        private readonly bool isMaxHeap;

        private T[] heapArray;
        private readonly IComparer<T> comparer;

        public int Count { get; private set; }

        public BHeap(SortDirection sortDirection = SortDirection.Ascending)
            : this(sortDirection, null, null) { }

        public BHeap(SortDirection sortDirection, IEnumerable<T> initial)
            : this(sortDirection, initial, null) { }

        public BHeap(SortDirection sortDirection, IComparer<T> comparer)
            : this(sortDirection, null, comparer) { }

        /// <summary>
        /// Time complexity: O(n) if initial is provided. Otherwise O(1).
        /// </summary>
        /// <param name="initial">The initial items in the heap.</param>
        public BHeap(SortDirection sortDirection, IEnumerable<T> initial, IComparer<T> comparer)
        {
            this.isMaxHeap = sortDirection == SortDirection.Descending;

            if (comparer != null)
            {
                this.comparer = new CustomComparer<T>(sortDirection, comparer);
            }
            else
            {
                this.comparer = new CustomComparer<T>(sortDirection, Comparer<T>.Default);
            }

            if (initial != null)
            {
                var items = initial as T[] ?? initial.ToArray();
                var initArray = new T[items.Count()];

                var i = 0;
                foreach (var item in items)
                {
                    initArray[i] = item;
                    i++;
                }

                bulkInit(initArray);
                Count = initArray.Length;
            }
            else
            {
                heapArray = new T[2];
            }
        }

        private void bulkInit(T[] initial)
        {
            var i = (initial.Length - 1) / 2;

            while (i >= 0)
            {
                bulkInitRecursive(i, initial);
                i--;
            }

            heapArray = initial;
        }

        private void bulkInitRecursive(int i, T[] initial)
        {
            while (true)
            {
                var parent = i;

                var left = 2 * i + 1;
                var right = 2 * i + 2;

                var minMax = left < initial.Length && right < initial.Length ?
                    comparer.Compare(initial[left], initial[right]) < 0 ? left : right
                    : left < initial.Length ? left
                    : right < initial.Length ? right : -1;

                if (minMax != -1 && comparer.Compare(initial[minMax], initial[parent]) < 0)
                {
                    var temp = initial[minMax];
                    initial[minMax] = initial[parent];
                    initial[parent] = temp;

                    //drill down to child
                    i = minMax;
                    continue;
                }

                break;
            }
        }

        /// <summary>
        /// Time complexity: O(log(n)).
        /// </summary>
        public void Insert(T newItem)
        {
            if (Count == heapArray.Length)
            {
                doubleArray();
            }

            heapArray[Count] = newItem;

            for (int i = Count; i > 0; i = (i - 1) / 2)
            {
                if (comparer.Compare(heapArray[i], heapArray[(i - 1) / 2]) < 0)
                {
                    var temp = heapArray[(i - 1) / 2];
                    heapArray[(i - 1) / 2] = heapArray[i];
                    heapArray[i] = temp;
                }
                else
                {
                    break;
                }
            }

            Count++;
        }

        /// <summary>
        /// Time complexity: O(log(n)).
        /// </summary>
        public T Extract()
        {
            if (Count == 0)
            {
                throw new Exception("Empty heap");
            }

            var minMax = heapArray[0];

            delete(0);

            return minMax;
        }

        /// <summary>
        /// Time complexity: O(1).
        /// </summary>
        public T Peek()
        {
            if (Count == 0)
            {
                throw new Exception("Empty heap");
            }

            return heapArray[0];
        }

        /// <summary>
        /// Time complexity: O(n).
        /// </summary>
        public void Delete(T value)
        {
            var index = findIndex(value);

            if (index != -1)
            {
                delete(index);
                return;
            }

            throw new Exception("Item not found.");

        }

        /// <summary>
        /// Time complexity: O(n).
        /// </summary>
        public bool Exists(T value)
        {
            return findIndex(value) != -1;
        }

        private void delete(int parentIndex)
        {
            heapArray[parentIndex] = heapArray[Count - 1];
            Count--;

            //percolate down
            while (true)
            {
                var leftIndex = 2 * parentIndex + 1;
                var rightIndex = 2 * parentIndex + 2;

                var parent = heapArray[parentIndex];

                if (leftIndex < Count && rightIndex < Count)
                {
                    var leftChild = heapArray[leftIndex];
                    var rightChild = heapArray[rightIndex];

                    var leftIsMinMax = false;

                    if (comparer.Compare(leftChild, rightChild) < 0)
                    {
                        leftIsMinMax = true;
                    }

                    var minMaxChildIndex = leftIsMinMax ? leftIndex : rightIndex;

                    if (comparer.Compare(heapArray[minMaxChildIndex], parent) < 0)
                    {
                        var temp = heapArray[parentIndex];
                        heapArray[parentIndex] = heapArray[minMaxChildIndex];
                        heapArray[minMaxChildIndex] = temp;

                        if (leftIsMinMax)
                        {
                            parentIndex = leftIndex;
                        }
                        else
                        {
                            parentIndex = rightIndex;
                        }

                    }
                    else
                    {
                        break;
                    }
                }
                else if (leftIndex < Count)
                {
                    if (comparer.Compare(heapArray[leftIndex], parent) < 0)
                    {
                        var temp = heapArray[parentIndex];
                        heapArray[parentIndex] = heapArray[leftIndex];
                        heapArray[leftIndex] = temp;

                        parentIndex = leftIndex;
                    }
                    else
                    {
                        break;
                    }
                }
                else if (rightIndex < Count)
                {
                    if (comparer.Compare(heapArray[rightIndex], parent) < 0)
                    {
                        var temp = heapArray[parentIndex];
                        heapArray[parentIndex] = heapArray[rightIndex];
                        heapArray[rightIndex] = temp;

                        parentIndex = rightIndex;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }

            }

            if (heapArray.Length / 2 == Count && heapArray.Length > 2)
            {
                halfArray();
            }
        }

        private int findIndex(T value)
        {
            for (int i = 0; i < Count; i++)
            {
                if (heapArray[i].Equals(value))
                {
                    return i;
                }
            }
            return -1;
        }

        private void halfArray()
        {
            var smallerArray = new T[heapArray.Length / 2];

            for (int i = 0; i < Count; i++)
            {
                smallerArray[i] = heapArray[i];
            }

            heapArray = smallerArray;
        }

        private void doubleArray()
        {
            var biggerArray = new T[heapArray.Length * 2];

            for (int i = 0; i < Count; i++)
            {
                biggerArray[i] = heapArray[i];
            }

            heapArray = biggerArray;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<T> GetEnumerator()
        {
            return heapArray.Take(Count).GetEnumerator();
        }

    }
}


text:
package gov.hhs.onc.crigtt.validate.render.impl;

import gov.hhs.onc.crigtt.transform.impl.AbstractCrigttExtensionFunction;
import gov.hhs.onc.crigtt.xml.CrigttXmlNs;
import gov.hhs.onc.crigtt.xml.utils.CrigttXpathUtils;
import java.util.Map;
import javax.annotation.Nonnegative;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmValue;
import net.sf.saxon.value.SequenceType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component("extFuncDefaultIfBlank")
public class DefaultIfBlankFunction extends AbstractCrigttExtensionFunction {
    public final static StructuredQName NAME = new QName(CrigttXmlNs.VALIDATE_PREFIX, CrigttXmlNs.VALIDATE_URI, "default-if-blank").getStructuredQName();

    public DefaultIfBlankFunction() {
        super(NAME, SequenceType.SINGLE_STRING, SequenceType.SINGLE_STRING, SequenceType.OPTIONAL_STRING);
    }

    @Override
    protected XdmValue call(XPathContext context, Map<Object, Object> contextData, XdmValue[] args) throws Exception {
        return new XdmAtomicValue(StringUtils.defaultIfBlank(CrigttXpathUtils.getStringValue(args[0]), CrigttXpathUtils.getStringValue(args[1])));
    }

    @Nonnegative
    @Override
    public int getMinimumNumberOfArguments() {
        return 1;
    }
}

redpajama_set_name: RedPajamaGithub


text:
RSpec.describe "Viewing the beer menu", :integration do
  let!(:region1){ Region.create(name: "Tennessee") }
  let!(:region2){ Region.create(name: "New York") }

  context "a region that is in the list" do
    let(:output){ run_bier_with_input('2') } # New York

    before do
      Beer.create(brewery: "Yazoo", location: "Nashville, TN", description: "The first big microbrew in Music City", region: region1)
      Beer.create(brewery: "Jackalope", location: "Nashville, TN", description: "The second big microbrew in Music City", region: region1)
      Beer.create(brewery: "Brooklyn", location: "Brooklyn, NY", description: "The first big microbrew in Brooklyn", region: region2)
      Beer.create(brewery: "Heartland", location: "Brooklyn, NY", description: "The second big microbrew in Brooklyn", region: region2)
    end

    it "should include the name of the region being viewed" do
      expect(output).to include("We're traveling to New York to try some of their local beers !")
    end
    # it "should list the breweries in this region" do
    #   expected = "1. Brooklyn\n" +
    #              "2. Heartland\n"
    #   expect(output).to include(expected)
    # end
  #   it "shouldn't list the skills in other training paths" do
  #     expect(output).not_to include("with Scissors")
  #     expect(output).not_to include("like a Zombie")
  #   end
  end

  context "if we enter a region that doesn't exist" do
    let(:output){ run_bier_with_input('3') }
    it "prints an error message" do
      expect(output).to include("Sorry, region 3 doesn't exist.")
    end
  end
end


text:
The project is built using the [Spring Boot](https://projects.spring.io/spring-boot/) framework. Use is made of several [_spring-boot-starter_](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters)
 projects to supply significant areas of functionality with minimal work.

Specifically the following components are used:

1. **spring-boot-starter-web** Starter for building web, including RESTful, applications using Spring MVC
2. **spring-boot-starter-undertow** - Starter for using Undertow as the embedded servlet container
3. **spring-boot-starter-actuator** - Starter for using Spring Boot's Actuator which provides production ready features to help you monitor and manage your application
4. **spring-boot-starter-test** - Starter for testing Spring Boot applications

## spring-boot-starter-web

This '[Starter](https://spring.io/guides/gs/spring-boot/)' supplies basic functionality for using Spring Web Services

## spring-boot-starter-undertow

This '[Starter](https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html)' allows the use of the [Undertow](http://undertow.io/) high performance web server rather than
 the default Tomcat container

## spring-boot-starter-actuator

This '[Starter](https://spring.io/guides/gs/actuator-service/)' supplies various Spring Boot additional features to help you monitor and manage your application when it's in production.
Monitoring and management can be done via HTTP endpoints, MX, SSH and Telnet. Monitoring includes auditing, health information and various metrics which may
be gathered.

## spring-boot-starter-test

This 'Starter' supplies utilities, libraries and annotations to help in testing a Spring Boot application.  This includes:

1. [JUnit](http://junit.org/junit4/) — The de-facto standard for unit testing Java applications.
2. [Spring Test & Spring Boot Test](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html)— Utilities and integration test support for Spring Boot applications.
3. [AssertJ ](http://joel-costigliola.github.io/assertj/)— A fluent assertion library.
4. [Hamcrest](http://hamcrest.org/) — A library of matcher objects (also known as constraints or predicates).
5. [Mockito](http://site.mockito.org/) — A Java mocking framework.
6. [JSONassert](http://jsonassert.skyscreamer.org/) — An assertion library for JSON.
7. [JsonPath](https://github.com/jayway/JsonPath) — XPath for JSON.

## spring-boot-starter-aop

This Starter supplies suport for aspect-oriented programming with Spring AOP and AspectJ.  This is used in support of other components

## Gradle

The build system for the project is [Gradle](https://gradle.org/).  To include the starters, the following dependencies are specified:

```groovy
dependencies {
    // Spring boot
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.5.3.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-undertow', version: '1.5.3.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '1.5.3.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.5.3.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop', version: '1.5.3.RELEASE'
    // ...
    }
```


text:
const assert = require('assert');
assert.equal(require('../').version, require('../package.json').version);
assert.equal(
  require('../package.json').version,
  require('../package-lock.json').version
);


text:
module Landable
  module Traffic
    class Access < ActiveRecord::Base
      include Landable::TableName

      lookup_for :path, class_name: Path

      belongs_to :visitor
    end
  end
end


text:
#chaticon, #chatbox {
  visibility: hidden;
  z-index: 400;
  position: absolute;
  bottom: 0px;
  right: 25px;
}
#chaticon.visible, #chatbox.visible {
  visibility: visible;
}
#chaticon {
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border: 1px solid #ccc;
  border-bottom: none;
}
.chat-content {
  width: 400px;
  height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  display: flex;
  border: 1px solid #ccc;
  border-bottom: none;
  z-index: 401;
  background-color: #f7f7f7;
  flex-direction: column;
  transition: all 0.3s cubic-bezier(0.74, -0.05, 0.27, 1.75);
  opacity: .3;
  transform: scale(.5);
  transform-origin: 100% 100%
}
#chatbox.visible .chat-content{
  opacity: 1;
  transform: scale(1);
}

#chatbox.stickyChat {
  position: relative;
  width: auto;
  flex: 1 auto; /* take reminaning vertical space */
  height: 100%;
  right: 0;
  display: flex;
}
#chatbox.stickyChat .chat-content {
  background-color: #f1f1f1;
  border-radius: 0;
  border: none;
  border-left: 1px solid #ccc;
  height: 100%;
  width: 100%;
}
#chatbox.stickyChat .chat-content .stick-to-screen-btn {
  display: none;
}
#chatbox.stickyChat.chatAndUsersChat .chat-content .hide-reduce-btn {
  display:none;
}

/* -- TITLE BAR -- */
#titlebar {
  font-weight: bold;
  padding: 5px;
}
#titlebar #titlelabel {
  margin: 4px 0 0 4px;
  display: inline;
  font-size: 1.4rem;
}
#titlebar .stick-to-screen-btn,
#titlebar .hide-reduce-btn {
  font-size: 25px;
  color: inherit;
  float: right;
  text-align: right;
  text-decoration: none;
  cursor: pointer;
}
#titlebar .stick-to-screen-btn {
  font-size: 10px;
  padding-top: 2px;
}

/* -- MESSAGES -- */
#chattext {
  background-color: white;
  overflow-y: auto;
  flex: 1 auto;
  height: 0; /* strange bug on firefox, if height is not set, the chattext grow bigger than the maximum height */
}
#chattext p {
  padding: 3px;
  overflow-x: hidden;
  word-wrap: break-word;
}
#chattext .time {
  float: right;
  font-style: italic;
  font-size: .85rem;
  opacity: .8;
  margin-left: 3px;
  margin-right: 2px;
}

/* -- INPUT BOX -- */
#chatinputbox {
  padding: 5px;
}
#chatinputbox #chatinput {
  width: 100%;
}

/* -- CHAT ICON -- */
#chaticon {
  background-color: #fff;
  cursor: pointer;
  display: none;
  padding: 5px;
}
#chaticon a {
  text-decoration: none
}
#chaticon #chatlabel {
  font-weight: bold;
  text-decoration: none;
  margin-right: 3px;
  vertical-align: middle;
}
#chaticon #chatcounter {
  font-size: .8rem;
  vertical-align: middle;
  margin-left: 5px;
}

/* -- LOAD MESSAGES -- */
.chatloadmessages
{
  margin-bottom: 5px;
  margin-top: 5px;
  margin-left: auto;
  margin-right: auto;
  display: block;
}
#chatloadmessagesbutton
{
  line-height: 1.8em;
}
#chatloadmessagesball
{
  display: none;
}

@media only screen and (max-width: 800px) {
  #chatbox {
    right: 0;
    bottom: 0;
    left: 0;
  }
  #chatbox .chat-content {
    width: 100%;
  }
}


text:
package utility;

import org.junit.Test;

import java.util.Arrays;

import static main.Column.KEYWORDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static utility.Tokenization.contains;
import static utility.Tokenization.lowercaseSplit;

public class TokenizationTest {

	@Test
	public void testCamelCased() {
		assertEquals(Arrays.asList("I", "Some", "Camel", "Cased", "String"), Tokenization.split("ISomeCamelCasedString"));
	}

	@Test
	public void testSnakeCased() {
		assertEquals(Arrays.asList("UNDERSCORED", "STRING"), Tokenization.split("UNDERSCORED_STRING"));
	}

	@Test
	public void testSnakeCasedSmall() {
		assertEquals(Arrays.asList("underscored", "string"), Tokenization.split("underscored_string"));
	}

	@Test
	public void testMixed() {
		assertEquals(Arrays.asList("camel", "Cased", "and", "UNDERSCORED"), Tokenization.split("camelCased_and_UNDERSCORED"));
	}

	@Test
	public void testSymbol() {
		assertEquals(Arrays.asList("_"), Tokenization.split("_"));
	}

	@Test
	public void testBattery() {
		assertEquals(Arrays.asList("lowercase"), Tokenization.split("lowercase"));
		assertEquals(Arrays.asList("Class"), Tokenization.split("Class"));
		assertEquals(Arrays.asList("My","Class"), Tokenization.split("MyClass"));
		assertEquals(Arrays.asList("HTML"), Tokenization.split("HTML"));
		assertEquals(Arrays.asList("PDF", "Loader"), Tokenization.split("PDFLoader"));
		assertEquals(Arrays.asList("A", "String"), Tokenization.split("AString"));
		assertEquals(Arrays.asList("Simple", "XML", "Parser"), Tokenization.split("SimpleXMLParser"));
		assertEquals(Arrays.asList("lower", "hyphen"), Tokenization.split("lower-hyphen"));
		assertEquals(Arrays.asList("99", "Bottles"), Tokenization.split("99Bottles"));
		assertEquals(Arrays.asList("GL", "11", "Version"), Tokenization.split("GL11Version"));
		assertEquals(Arrays.asList("May", "5"), Tokenization.split("May5"));
		assertEquals(Arrays.asList("BFG", "9000"), Tokenization.split("BFG9000"));
		assertEquals(Arrays.asList("Žluťoučký", "Kůň"), Tokenization.split("ŽluťoučkýKůň"));
		assertEquals(Arrays.asList("."), Tokenization.split("."));
		assertEquals(Arrays.asList(" "), Tokenization.split(" "));
		assertEquals(Arrays.asList("324", "A"), Tokenization.split(" 324A "));
	}

		@Test
	public void containsBatteryTest() {
		assertTrue(contains(lowercaseSplit("personId"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("person_id"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("PERSON_ID"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("id"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("ID"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("IdP"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("id_person"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("ID_PERSON"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("IDPerson"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("person_id2"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("personID2"), KEYWORDS));
		assertTrue(contains(lowercaseSplit("personId2"), KEYWORDS));

		assertFalse(contains(lowercaseSplit("personid"), KEYWORDS));
		assertFalse(contains(lowercaseSplit("PERSONID"), KEYWORDS));
		assertFalse(contains(lowercaseSplit("idperson"), KEYWORDS));
		assertFalse(contains(lowercaseSplit("IDPERSON"), KEYWORDS));
		assertFalse(contains(lowercaseSplit("x"), KEYWORDS));
		assertFalse(contains(lowercaseSplit("prefix_personid"), KEYWORDS));
		assertFalse(contains(lowercaseSplit("IDPERSON"), KEYWORDS));
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: staabm
 * Date: 21.11.2015
 * Time: 16:08
 */

namespace Whoops;

function isAjaxRequest()
{
    return (
        !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
        && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}

/**
 * Check, if possible, that this execution was triggered by a command line.
 * @return bool
 */
function isCommandLine()
{
    return PHP_SAPI == 'cli';
}


text:
package org.fao.fenix.commons.msd.dto.templates.standard.metadata;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.fao.fenix.commons.msd.dto.templates.ResponseHandler;

public class SeProjectionParameters extends ResponseHandler {

    public SeProjectionParameters() {}
    public SeProjectionParameters(Object source) {
        super(source);
    }

    @JsonProperty
    public Integer getZone() {
        return null;
    }
    @JsonProperty
    public Double getStandardParallel() {
        return null;
    }
    @JsonProperty
    public Double getLongitudeOfCentralMeridian() {
        return null;
    }
    @JsonProperty
    public Double getLatitudeOfProjectionOrigin() {
        return null;
    }
    @JsonProperty
    public Double getFalseEasting() {
        return null;
    }
    @JsonProperty
    public Double getFalseNorthing() {
        return null;
    }
    @JsonProperty
    public OjMeasure getFalseEastingNorthingUnits() {
        return null;
    }
    @JsonProperty
    public Double getScaleFactorAtEquator() {
        return null;
    }
    @JsonProperty
    public Double getHeightOfProspectivePointAboveSurface() {
        return null;
    }
    @JsonProperty
    public Double getLongitudeOfProjectionCenter() {
        return null;
    }
    @JsonProperty
    public Double getLatitudeOfProjectionCenter() {
        return null;
    }
    @JsonProperty
    public Double getScaleFactorAtCenterLine() {
        return null;
    }
    @JsonProperty
    public Double getStraightVerticalLongitudeFromPole() {
        return null;
    }
    @JsonProperty
    public Double getScaleFactorAtProjectionOrigin() {
        return null;
    }
    @JsonProperty
    public SeObliqueLineAzimuth getSeObliqueLineAzimuth() {
        return null;
    }
    @JsonProperty
    public SeObliqueLinePoint getSeObliqueLinePoint() {
        return null;
    }

}


text:
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Swashbuckle.AspNetCore.Annotations.Test
{
    public class VendorExtensionsOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext contex)
        {
            operation.Extensions.Add("X-property1", new OpenApiString("value"));
        }
    }
}


text:
namespace voom {

  // Constructor
  PhaseModel::PhaseModel(Mesh* aMesh, vector<CahnHilliard * > materials,
				 const uint NodeDoF):
    EllipticModel(aMesh, NodeDoF), _materials(materials)
  {
    // THERE IS ONE MATERIAL PER ELEMENT - CAN BE CHANGEd - DIFFERENT THAN BEFORE
    // Resize and initialize (default function) _field vector
    _field.resize(  _myMesh->getNumberOfNodes()  );
    _lagMult = 0.0;
    this->initializeField(0.5-double(rand())/double(RAND_MAX));
    //this->initializeField();
  }

  // Compute Function - Compute Energy, Force, Stiffness
  void PhaseModel::compute(EllipticResult & R)
  {
    const vector<GeomElement* > elements = _myMesh->getElements();
    const int AvgNodePerEl = ((elements[0])->getNodesID()).size();
    const int NumEl = elements.size();
    const int dim = _myMesh->getDimension();
    vector<Triplet<Real > > KtripletList, HgtripletList;

    int PbDoF = R.getPbDoF();
    int TotNumMatProp = R.getNumMatProp();
    vector<VectorXd > dRdalpha;
    VectorXd Residual;
    //int NumPropPerMat = (_materials[0]->getMaterialParameters()).size(); // Assume all materials have the same number of material properties

    // Reset values in result struct
    if ( R.getRequest() & ENERGY ) {
      R.setEnergy(0.0);
    }
    if ( R.getRequest() & FORCE || R.getRequest() & DMATPROP )  {
      R.resetResidualToZero();
      R.resetConstraintToZero();
    }
    if ( R.getRequest() & STIFFNESS ) {
      R.resetStiffnessToZero();
      KtripletList.reserve(dim*dim*NumEl*AvgNodePerEl*AvgNodePerEl);
    }

    // Loop through elements, also through material points array, which is unrolled
    // uint index = 0;
    CahnHilliard::Scalarresults ShRes;
    ShRes.request = R.getRequest();
    for(int e = 0; e < NumEl; e++)
      {
	LoopShellElement* element = dynamic_cast<LoopShellElement*>(elements[e]);
	const vector<int  >& NodesID = element->getNodesID();
	const int numQP    = element->getNumberOfQuadPoints();
	const int numNodes = NodesID.size();

	// Loop over quadrature points
	for(int q = 0; q < numQP; q++) {
	  // Initialize a and aPartials
	  vector<Vector3d> a(2, Vector3d::Zero());
	  vector<Vector3d> aPartials(3, Vector3d::Zero());
	  Vector3d temp;
	  Real phi;
	  Vector2d phiPartials = Vector2d::Zero();
	  for(uint J = 0; J < 2; J++) { //J =0,1 (represents two surface coordinates
	    temp = Vector3d::Zero();
	    phi = 0;
	    for(uint n = 0; n < numNodes; n++) {
	      for(uint i = 0; i < 3; i++) { //i =0,1,2 represents x,y,z
		temp(i) += _myMesh->getX(NodesID[n],i) * element->getN(q,n);
		a[J](i) += _myMesh->getX(NodesID[n],i) * element->getDN(q, n, J);
		aPartials[J](i) += _myMesh->getX(NodesID[n],i) * element->getDDN(q,n,J,J); //a_tt, a_pp
	      }

	      phi += _field[NodesID[n]] * element->getN(q,n);

	      phiPartials(J) += _field[NodesID[n]] * element->getDN(q,n,J);
	    }
	  }

	  for(uint i = 0; i < dim; i++) { //i =0,1,2 represents three displacement indices
	    for(uint n = 0; n < numNodes; n++) {
	      aPartials[2](i) += _myMesh->getX(NodesID[n],i) *element->getDDN(q,n,0,1); //a_tt, a_pp
	    }
	  }

	  ShellGeometry geometry = ShellGeometry(a,aPartials);
	  Real metric = geometry.metric();

	  _materials[e]->compute(ShRes, phi, phiPartials, _lagMult, geometry);

	  // Volume associated with QP q
	  Real Vol = element->getQPweights(q) * metric;

	  // Compute energy
	  if (R.getRequest() & ENERGY) {
	    R.addEnergy(ShRes.W * Vol);
	  }

	  // Compute Residual
	    if ( (R.getRequest() & FORCE) ) {

	    for(uint n = 0; n < numNodes; n++) {
	      Real tempResidual = 0.0;
	      tempResidual = ShRes.n * element->getN(q,n) +
		ShRes.m[0]*element->getDN(q,n,0) + ShRes.m[1]*element->getDN(q,n,1);
	      R.addResidual(NodesID[n], tempResidual*Vol);
	    } // n loop
	    R.addConstraint( ShRes.constr * Vol );
	    } // Internal force loop
	}

      }// Element loop

  } // Compute Mechanics Model

  // Writing output
  void PhaseModel::writeOutputVTK(const string OutputFile, int step)
  {
    // Create outputFile name
    stringstream FileNameStream;
    FileNameStream << OutputFile << step << ".vtk";
    ofstream out;
    out.open( (FileNameStream.str()).c_str() );
    int NumNodes = _myMesh->getNumberOfNodes();

    // Header
    char spchar = '#';
    out << spchar << " vtk DataFile Version 3.1" << endl;
    out << "vtk output" << endl;
    out << "ASCII" << endl;
    out << "DATASET UNSTRUCTURED_GRID" << endl;
    out << "POINTS " << NumNodes << " FLOAT" << endl;

    // For now we assumed dim == 3 !
    for (int i = 0; i < NumNodes; i++ ) {
      out << _myMesh->getX(i) << endl;
    }

    vector<GeomElement* > elements = _myMesh->getElements();
    int NumEl = elements.size();
    int NodePerEl = (elements[0])->getNodesPerElement();
    // To be adjusted - not general at all!
    int CellType = 0;
    switch (NodePerEl) {
    case 4:
      CellType = 10;
      break;
    case 10:
      CellType = 24;
      break;
    default:
      cout << "Error cell type not implemented in PhaseModel writeOutput. " << endl;
    }

    out << endl << "CELLS " << NumEl << " " << NumEl*(NodePerEl+1) << endl;

    for (int e = 0; e < NumEl; e++) {
      out << NodePerEl << " ";
      const vector<int > & NodesID = (elements[e])->getNodesID();
      for (int n = 0; n < NodePerEl; n++) {
	out << NodesID[n] << " ";
      }
      out << endl;
    }

    out << endl << "CELL_TYPES " << NumEl << endl;
    for (int e = 0; e < NumEl; e++) {
      out << CellType << " " << endl;
    }  // end of printing conntable

    // Point data section
    out << endl << "POINT_DATA " << NumNodes << endl
	<< "VECTORS displacements double" << endl;

    int dim = _myMesh->getDimension();
    for (int i = 0; i < NumNodes; i++ ) {
      VectorXd x = VectorXd::Zero(dim);
      for (int j = 0; j < dim; j++) {
	x(j) = _field[i*dim + j];
      }
      out << x - _myMesh->getX(i) << endl;
    }

    // Close file
    out.close();
  } // writeOutput

} // namespace voom


text:
		<?php echo $cluster_name; ?> /

		<a href="describe_keyspace.php?keyspace_name=<?php echo $keyspace_name; ?>"><?php echo $keyspace_name; ?> /

		<a href="describe_columnfamily.php?keyspace_name=<?php echo $keyspace_name; ?>&columnfamily_name=<?php echo $columnfamily_name; ?>"><?php echo $columnfamily_name; ?> /

		<?php if ($mode == 'insert'): ?>Insert a Row<?php elseif ($mode == 'edit'): ?>Edit Row "<?php echo htmlentities($key,ENT_COMPAT,'UTF-8'); ?>"<?php endif; ?>

<?php echo $success_message; ?>
<?php echo $info_message; ?>
<?php echo $error_message; ?>

<form method="post" action="" class="well">
	<?php if ($is_super_cf): ?>

		<input type="button" onclick="addSuperColumnWithColumn();" value="Add Super Column..." class="float_right btn" />

	<?php endif; ?>

		Row Key:
		<input id="key" name="key" type="text" value="<?php echo $key; ?>" <?php if ($mode == 'edit'): ?>disabled="disabled"<?php endif;?> />

		<input type="submit" class="btn btn-primary" name="btn_insert_row" value="<?php if ($mode == 'insert'): ?>Insert Row<?php elseif ($mode == 'edit'): ?>Edit Row<?php endif; ?>" />

	<?php if ($mode == 'edit'): ?><input type="hidden" name="key" value="<?php echo $key; ?>" /><?php endif;?>
	<input type="hidden" name="keyspace_name" value="<?php echo $keyspace_name; ?>" />
	<input type="hidden" name="columnfamily_name" value="<?php echo $columnfamily_name; ?>" />
	<input type="hidden" name="mode" value="<?php echo $mode; ?>" />
</form>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;

namespace Microsoft.UnitTests.Core.XUnit {
    [AttributeUsage(AttributeTargets.Class)]
    public class ThreadTypeAttribute : Attribute {
        public ThreadTypeAttribute(ThreadType threadType) {
            ThreadType = threadType;
        }

        public ThreadType ThreadType { get; set; }
    }
}


text:
package com.twitter.elephantbird.thrift;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TList;
import org.apache.thrift.protocol.TMap;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.protocol.TSet;
import org.apache.thrift.protocol.TType;
import org.apache.thrift.transport.TTransport;

/**
 * Functionally exactly same as {@link TBinaryProtocol}. <p>
 *
 * Overwrites a few methods so that some malformed messages don't end up
 * taking excessively large amounts of cpu inside TProtocolUtil.skip().
 *
 * To obtain an instance of ThriftBinaryProtocol use {@link ThriftCompat#createBinaryProtocol(TTransport)}.
 * It will take care of cross version compatibility between thrift 0.7 and 0.9+ code.
 *
 * @see ThriftCompat
 */
public class ThriftBinaryProtocol extends AbstractThriftBinaryProtocol {

  ThriftBinaryProtocol(TTransport trans) {
    super(trans);
  }

  ThriftBinaryProtocol(TTransport trans, long stringLengthLimit, long containerLengthLimit) {
    super(trans, stringLengthLimit, containerLengthLimit);
  }

  /**
   * Ensures that an element type in a for container (List, Set, Map) is
   * a valid container.
   *
   * @param type
   * @throws TException if the type is not one of the expected type.
   */
  public static void checkContainerElemType(byte type) throws TException {
    // only valid types for an element in a container (List, Map, Set)
    // are the ones that are considered in TProtocolUtil.skip()
    switch (type) {
      case TType.BOOL:
      case TType.BYTE:
      case TType.I16:
      case TType.I32:
      case TType.I64:
      case TType.DOUBLE:
      case TType.STRING:
      case TType.STRUCT:
      case TType.MAP:
      case TType.SET:
      case TType.LIST:
        break;

      // list other known types, but not expected
      case TType.STOP:
      case TType.VOID:
      case TType.ENUM: // would be I32 on the wire
      default:
        throw new TException("Unexpected type " + type + " in a container");
    }
  }

  @Override
  public TMap readMapBegin() throws TException {
    TMap map = super.readMapBegin();
    checkContainerSize(map.size);
    checkContainerElemType(map.keyType);
    checkContainerElemType(map.valueType);
    return map;
  }

  @Override
  public TList readListBegin() throws TException {
    TList list = super.readListBegin();
    checkContainerSize(list.size);
    checkContainerElemType(list.elemType);
    return list;
  }

  @Override
  public TSet readSetBegin() throws TException {
    TSet set = super.readSetBegin();
    checkContainerSize(set.size);
    checkContainerElemType(set.elemType);
    return set;
  }

  @SuppressWarnings("serial")
  public static class Factory implements TProtocolFactory {

    public TProtocol getProtocol(TTransport trans) {
      return new ThriftBinaryProtocol(trans);
    }
  }
}


text:
package com.github.jasonmfehr.combiner.file;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

import java.io.File;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.github.jasonmfehr.combiner.logging.ParameterizedLogger;
import com.github.jasonmfehr.tojs.exception.FileSystemLocationNotFound;
import com.github.jasonmfehr.tojs.exception.NotReadableException;
import com.github.jasonmfehr.tojs.exception.NotWriteableException;

@RunWith(MockitoJUnitRunner.class)
public class FileValidatorTest {

	private static final String TEST_LOCATION = "filevalidatortest";

	@Mock private ParameterizedLogger mockLogger;

	@InjectMocks private FileValidator fixture;

	@Rule public TemporaryFolder tmpFolder = new TemporaryFolder();

	@Test(expected=IllegalArgumentException.class)
	public void testReadableNullInput() {
		fixture.existsAndReadable(null);
	}

	@Test(expected=IllegalArgumentException.class)
	public void testReadableBlankInput() {
		fixture.existsAndReadable("");
	}

	@Test(expected=FileSystemLocationNotFound.class)
	public void testReadableNotExists() throws Exception {
		fixture.existsAndReadable(tmpFolder.newFolder().getAbsolutePath() + "/" + TEST_LOCATION);
	}

	@Test(expected=NotReadableException.class)
	public void testReadableExistsNotReadable() throws Exception {
		final File notReadableFile = tmpFolder.newFile();

		assertThat(notReadableFile.setReadable(false), equalTo(true));
		assertThat(notReadableFile.setWritable(false), equalTo(true));

		fixture.existsAndReadable(notReadableFile.getAbsolutePath());
	}

	@Test
	public void testExistsReadable() throws Exception {
		final File tmpFile = tmpFolder.newFile();

		fixture.existsAndReadable(tmpFile.getAbsolutePath());

		verify(mockLogger).debugWithParams(contains("exists"), any(), any());
		verify(mockLogger).debugWithParams(any(String.class), any(), any(), eq("readable"));
		verify(mockLogger).debugWithParams(contains("valid"), any(), any());
	}

	@Test(expected=IllegalArgumentException.class)
	public void testWriteableNullInput() {
		fixture.existsAndWriteable(null);
	}

	@Test(expected=IllegalArgumentException.class)
	public void testWriteableBlankInput() {
		fixture.existsAndWriteable("");
	}

	@Test(expected=FileSystemLocationNotFound.class)
	public void testWriteableNotExists() throws Exception {
		fixture.existsAndWriteable(tmpFolder.newFolder().getAbsolutePath() + "/" + TEST_LOCATION);
	}

	@Test(expected=NotWriteableException.class)
	public void testWriteableExistsNotWriteable() throws Exception {
		final File notWriteableFile = tmpFolder.newFile();

		assertThat(notWriteableFile.setReadable(false), equalTo(true));
		assertThat(notWriteableFile.setWritable(false), equalTo(true));

		fixture.existsAndWriteable(notWriteableFile.getAbsolutePath());
	}

	@Test
	public void testExistsWriteable() throws Exception {
		final File tmpFile = tmpFolder.newFile();

		fixture.existsAndWriteable(tmpFile.getAbsolutePath());

		verify(mockLogger).debugWithParams(contains("exists"), any(), any());
		verify(mockLogger).debugWithParams(any(String.class), any(), any(), eq("writeable"));
		verify(mockLogger).debugWithParams(contains("valid"), any(), any());
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Erioderma physcioides var. hypotrachyna

### Remarks
null


text:
package net.anotheria.moskito.core.threshold;

/**
 * If a producer is a CustomThresholdProvider it will be asked for its threshold status instead of the actual stats by the threshold.
 *
 * @author lrosenberg
 * @since 26.02.18 18:04
 */
public interface CustomThresholdProvider {
	/**
	 * Returns threshold status.
	 * @return current status.
	 */
	ThresholdStatus getStatus();

	/**
	 * Returns current threshold value.
	 * @return current value.
	 */
	String getCurrentValue();
}


text:
ActiveRecord::Schema.define(version: 20140204233952) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "users", force: true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "image_url"
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "failed_attempts",        default: 0,  null: false
    t.string   "unlock_token"
    t.datetime "locked_at"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "is_admin"
    t.index ["confirmation_token"], :name => "index_users_on_confirmation_token", :unique => true
    t.index ["email"], :name => "index_users_on_email", :unique => true, :case_sensitive => false
    t.index ["is_admin"], :name => "index_users_on_is_admin"
    t.index ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
    t.index ["unlock_token"], :name => "index_users_on_unlock_token", :unique => true
  end

  create_table "authentications", force: true do |t|
    t.integer  "user_id"
    t.string   "provider",      null: false
    t.string   "proid",         null: false
    t.string   "token"
    t.string   "refresh_token"
    t.string   "secret"
    t.datetime "expires_at"
    t.string   "username"
    t.string   "image_url"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.index ["provider"], :name => "index_authentications_on_provider"
    t.index ["user_id"], :name => "fk__authentications_user_id"
    t.foreign_key ["user_id"], "users", ["id"], :on_update => :no_action, :on_delete => :no_action, :name => "fk_authentications_user_id"
  end

  create_table "oauth_caches", id: false, force: true do |t|
    t.integer  "authentication_id", null: false
    t.text     "data_json",         null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.index ["authentication_id"], :name => "fk__oauth_caches_authentication_id"
    t.index ["authentication_id"], :name => "index_oauth_caches_on_authentication_id"
    t.foreign_key ["authentication_id"], "authentications", ["id"], :on_update => :no_action, :on_delete => :no_action, :name => "fk_oauth_caches_authentication_id"
  end

  create_table "rails_admin_histories", force: true do |t|
    t.text     "message"
    t.string   "username"
    t.integer  "item"
    t.string   "table"
    t.integer  "month",      limit: 2
    t.integer  "year",       limit: 8
    t.datetime "created_at"
    t.datetime "updated_at"
    t.index ["item", "table", "month", "year"], :name => "index_rails_admin_histories"
  end

end


text:
package org.apache.geode.management.internal.cli.commands;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.query.CqAttributesFactory;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.test.dunit.SerializableConsumerIF;
import org.apache.geode.test.dunit.rules.ClientVM;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.GfshTest;
import org.apache.geode.test.junit.rules.GfshCommandRule;

@Category({GfshTest.class})
@SuppressWarnings("serial")
public class DescribeClientCommandDUnitTest {

  private MemberVM locatorVm0;
  private MemberVM server1Vm1;
  private MemberVM server2Vm2;
  private ClientVM client1Vm3;
  private ClientVM client2Vm4;

  private static final String STOCKS_REGION = "stocks";

  @Rule
  public ClusterStartupRule rule = new ClusterStartupRule(5);

  @Rule
  public GfshCommandRule gfsh = new GfshCommandRule();

  @Before
  public void setup() throws Exception {
    locatorVm0 = rule.startLocatorVM(0);
    server1Vm1 = rule.startServerVM(1, locatorVm0.getPort());
    server2Vm2 = rule.startServerVM(2, locatorVm0.getPort());

    server1Vm1.invoke(() -> {
      RegionFactory factory =
          ClusterStartupRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
      factory.create(STOCKS_REGION);
    });

    server2Vm2.invoke(() -> {
      RegionFactory factory =
          ClusterStartupRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
      factory.create(STOCKS_REGION);
    });

    gfsh.connectAndVerify(locatorVm0);
  }

  @Test
  public void describeClient() throws Exception {
    boolean subscriptionEnabled = true;
    client1Vm3 = createClient(3, subscriptionEnabled);
    setupCqsOnVM(client1Vm3, STOCKS_REGION, "cq1", "cq2", "cq3");

    client2Vm4 = createClient(4, subscriptionEnabled);
    setupCqsOnVM(client2Vm4, STOCKS_REGION, "cq1", "cq2", "cq3");

    waitForClientReady(3);

    validateResults(subscriptionEnabled);
  }

  @Test
  public void describeClientWithoutSubscription() throws Exception {
    boolean subscriptionEnabled = false;
    client1Vm3 = createClient(3, subscriptionEnabled);
    setupCqsOnVM(client1Vm3, STOCKS_REGION, "cq1", "cq2", "cq3");

    client2Vm4 = createClient(4, subscriptionEnabled);
    setupCqsOnVM(client2Vm4, STOCKS_REGION, "cq1", "cq2", "cq3");

    waitForClientReady(1);

    validateResults(subscriptionEnabled);
  }

  private void validateResults(boolean subscriptionEnabled) {
    CommandResult result = gfsh.executeCommand("list members");
    Map<String, List<String>> members = result.getMapFromTableContent("members");
    int server1Idx = members.get("Name").indexOf("server-1");
    String server1 = members.get("Id").get(server1Idx);

    result = gfsh.executeCommand("list clients");
    String clientId = result.getColumnFromTableContent(CliStrings.LIST_CLIENT_COLUMN_Clients,
        "section1", "TableForClientList").get(0);

    result = gfsh.executeCommand("describe client --clientID=" + clientId);
    assertThat(result.getStatus()).isEqualTo(Result.Status.OK);

    Map<String, List<String>> table =
        result.getMapFromTableContent("Pool Stats For Pool Name = DEFAULT");
    Map<String, String> data = result.getMapFromSection("InfoSection");

    assertThat(table.get(CliStrings.DESCRIBE_CLIENT_MIN_CONN).get(0)).isEqualTo("1");
    assertThat(table.get(CliStrings.DESCRIBE_CLIENT_MAX_CONN).get(0)).isEqualTo("-1");
    assertThat(table.get(CliStrings.DESCRIBE_CLIENT_REDUNDANCY).get(0)).isEqualTo("1");

    if (subscriptionEnabled) {
      assertThat(table.get(CliStrings.DESCRIBE_CLIENT_CQs).get(0)).isEqualTo("3");
      assertThat(Integer.parseInt(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_QUEUE_SIZE)))
          .isGreaterThanOrEqualTo(1);
      assertThat(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_PRIMARY_SERVERS)).isEqualTo(server1);
    } else {
      assertThat(table.get(CliStrings.DESCRIBE_CLIENT_CQs).get(0)).isEqualTo("1");
      assertThat(Integer.parseInt(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_QUEUE_SIZE)))
          .isEqualTo(0);
      assertThat(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_PRIMARY_SERVERS)).isEqualTo("N.A.");
    }

    assertThat(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_PUTS)).isEqualTo("2");
    assertThat(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_LISTENER_CALLS)).isEqualTo("0");
    assertThat(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_DURABLE)).isEqualTo("No");
    assertThat(Integer.parseInt(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_THREADS)))
        .isGreaterThan(0);
    assertThat(Integer.parseInt(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_CPU))).isGreaterThan(0);
    assertThat(Integer.parseInt(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_UP_TIME)))
        .isGreaterThanOrEqualTo(0);
    assertThat(Long.parseLong(data.get(CliStrings.DESCRIBE_CLIENT_COLUMN_PROCESS_CPU_TIME)))
        .isGreaterThan(0);
  }

  void waitForClientReady(int cqsToWaitFor) {
    // Wait until all CQs are ready
    Awaitility.waitAtMost(20, TimeUnit.SECONDS).until(() -> {
      CommandResult r = gfsh.executeCommand("list clients");
      if (r.getStatus() != Result.Status.OK) {
        return false;
      }

      String clientId = r.getColumnFromTableContent(CliStrings.LIST_CLIENT_COLUMN_Clients,
          "section1", "TableForClientList").get(0);
      r = gfsh.executeCommand("describe client --clientID=" + clientId);
      Map<String, List<String>> table =
          r.getMapFromTableContent("Pool Stats For Pool Name = DEFAULT");

      if (table.size() == 0 || table.get(CliStrings.DESCRIBE_CLIENT_CQs).size() == 0) {
        return false;
      }

      return table.get(CliStrings.DESCRIBE_CLIENT_CQs).get(0).equals(cqsToWaitFor + "");
    });
  }

  private ClientVM createClient(int vmId, boolean subscriptionEnabled) throws Exception {
    int server1Port = server1Vm1.getPort();
    SerializableConsumerIF<ClientCacheFactory> cacheSetup = cf -> {
      cf.addPoolServer("localhost", server1Port);
      cf.setPoolSubscriptionEnabled(subscriptionEnabled);
      cf.setPoolPingInterval(100);
      cf.setPoolStatisticInterval(100);
      cf.setPoolSubscriptionRedundancy(1);
      cf.setPoolMinConnections(1);
    };

    Properties clientProps = new Properties();
    clientProps.setProperty("statistic-archive-file", "client.gfs");
    clientProps.setProperty("statistic-sampling-enabled", "true");
    ClientVM vm = rule.startClientVM(vmId, clientProps, cacheSetup);

    vm.invoke(() -> {
      ClientCache cache = ClusterStartupRule.getClientCache();
      ClientRegionFactory crf = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
      crf.setPoolName(cache.getDefaultPool().getName());

      Region region = crf.create(STOCKS_REGION);
      region.put("k1", "v1");
      region.put("k2", "v2");
    });

    return vm;
  }

  private void setupCqsOnVM(ClientVM vm, String regionName, String cq1, String cq2, String cq3) {
    vm.invoke(() -> {
      Cache cache = GemFireCacheImpl.getInstance();
      QueryService qs = cache.getQueryService();
      CqAttributesFactory cqAf = new CqAttributesFactory();
      try {
        qs.newCq(cq1, "select * from /" + regionName, cqAf.create(), true).execute();
        qs.newCq(cq2, "select * from /" + regionName + " where id = 1", cqAf.create(), true)
            .execute();
        qs.newCq(cq3, "select * from /" + regionName + " where id > 2", cqAf.create(), true)
            .execute();
        cache.getLogger()
            .info("setupCqs on vm created cqs = " + cache.getQueryService().getCqs().length);
      } catch (Exception e) {
        cache.getLogger().info("setupCqs on vm Exception " + ExceptionUtils.getStackTrace(e));
      }
      return true;
    });
  }
}


text:
package com.hazelcast.internal.ascii;

public abstract class TypeAwareCommandParser implements CommandParser {

    protected final TextCommandConstants.TextCommandType type;

    protected TypeAwareCommandParser(TextCommandConstants.TextCommandType type) {
        this.type = type;
    }
}


text:
/**
 *
 */
package com.ebay.jetstream.management;

import java.net.InetAddress;

import com.ebay.jetstream.config.ConfigException;
import com.ebay.jetstream.config.NetworkMap;
import com.ebay.jetstream.xmlser.XSerializable;

/**
 *
 *
 */
public class ManagementNetworkSecurity implements XSerializable {
  private static ManagementNetworkSecurity s_instance;

  public static ManagementNetworkSecurity getInstance() {
    return s_instance;
  }

  private final NetworkMap m_networkMap = new NetworkMap();

  // TODO: This should be looked at. Currently, if this constructor is never called,
  // security is disabled. Need to make this safer by changing how static is set.
  // Perhaps a static activate() method would be preferable.
  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
  public ManagementNetworkSecurity() {
    s_instance = this;
  }

  public String getReadOnlyAddresses() {
    return NetworkMap.asString(m_networkMap.getCategoryRanges("RO"));
  }

  public String getReadWriteAddresses() {
    return NetworkMap.asString(m_networkMap.getCategoryRanges("RW"));
  }

  public boolean isAuthorized(InetAddress addr, boolean forWrite) {
    return m_networkMap.isWithinRange(addr, "RW") || !forWrite && m_networkMap.isWithinRange(addr, "RO");
  }

  public void setReadOnlyAddresses(String addresses) throws ConfigException {
    m_networkMap.setCategoryRanges("RO", NetworkMap.asList(addresses));
  }

  public void setReadWriteAddresses(String addresses) throws ConfigException {
    m_networkMap.setCategoryRanges("RW", NetworkMap.asList(addresses));
  }
}


text:
<!DOCTYPE html>

    <title>Big O Complexity</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link href='http://fonts.googleapis.com/css?family=Quicksand:300,400,700|Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic|Source+Code+Pro:600' rel='stylesheet' type='text/css'/>
    <link rel="stylesheet" type="text/css" href="stylesheets/reset.css" />
    <link rel="stylesheet" type="text/css" href="stylesheets/blog.css" charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

      HENRY'S BLOG

About

Blog Posts

                How to Ask

                Big O Complexity

                Dealing with Conflict

                SQL vs NoSQL

                Self-Evaluation

                Inheritance vs Composition

                Being a 'Kraut'

                Upper Class

                Full Stack Teamwork

                Enumerablez

                Don't feed the patent troll!

                What's cool about Javascript?

                Mindnority Report

                Well Positioned

                Wireframes

                My Take On The DBC Experience

                Websites With Good Design

Big O Complexity

Regarding Coding

        í

            Think about an algorithm that counts the number of characters in a string. The complexity is O(n), because it needs to iterate over every character to come up with the number of characters. If you'd already have the number of characters stored in a variable beforehand, the complexity would be constant at a level of 1 -> O(1), because it would take the algorithm only one step to look up the number of characters, no matter how many there are in the string.

            An example for a logarithmic behavior would be the binary search algorithm. It works like this: Let's say we have an ordered list of numbers, [1,2,5,6,8,9,11]. We tell the algorithm to look for the number 2.

            It will divide the list into two piles: [1,2,5],6,[8,9,11]. Is 6 the number we're looking for? No, but we know that 2 is smaller than 6, so we can ignore the pile to right from now on: [1,2,5].

            Now it divides the list into two piles again: [1],2,[5]. It looks in the middle again, and it finds the number 2! The algorithm ends now after two divisions in total.

            This was the worst case scenario, because the 2 could have been in the middle of the list right from the beginning. Then it would have been zero divisions to find the number (best case scenario). You can calculate the worst case scenario number using this formula: ⌊log,base2 (x)⌋. So in this case it would be ⌊log,base2 (7)⌋ = ⌊2.807⌋ = 2. So to find a number in the list you would need two divisions at maximum.

            The "O" is used for describing the worst case complexity, which is O(⌊log,base2 (x)⌋) in this case. For best case scenario we use "omega", so it's Ω(1) in this case.

           henry-p


text:
"""Utilities for working with python's standard ast library"""
import ast
import re

def copy_node(node, *args, **kwargs):
    """Shallow copies the provided ast node.

    Non-keyword arguments are set according to the order in the Python ast documentation.
    Keyword arguments are set explicitly.
    """
    cls = node.__class__
    new_node = cls()

    set_attrs = {}

    # non-keyword args
    for name, value in zip(cls._fields, args):
        set_attrs[name] = value

    # keyword args
    for name, value in kwargs.iteritems():
        set_attrs[name] = value

    # attributes
    for name, value in node.__dict__.iteritems():
        if name not in set_attrs:
            set_attrs[name] = value

    # apply set_attrs
    for name, value in set_attrs.iteritems():
        setattr(new_node, name, value)

    return new_node

def deep_copy_node(node, *args, **kwargs):
    """Deep copies the provided ast node.

    Non-keyword arguments are set according to the order in the Python ast documentation.

    Keyword arguments are set explicitly."""
    cls = node.__class__
    new_node = cls()

    set_attrs = {}

    # non-keyword args
    for name, value in zip(cls._fields, args):
        set_attrs[name] = value

    # keyword args
    for name, value in kwargs.iteritems():
        set_attrs[name] = value

    # deep copy attributes
    for name, value in node.__dict__.iteritems():
        if name not in set_attrs:
            if isinstance(value, ast.AST):
                set_attrs[name] = deep_copy_node(value)
            else:
                set_attrs[name] = value

    # apply set_attrs
    for name, value in set_attrs.iteritems():
        setattr(new_node, name, value)

    return new_node

def builtin_call(name, args):
    return ast.Call(
        func=ast.Attribute(
            value=ast.Name(
                id='__builtin__', ctx=ast.Load()),
            attr=name, ctx=ast.Load()),
        args=args,
        keywords=[],
        starargs=None,
        kwargs=None)

def import_expr(name):
    return builtin_call('__import__', [ast.Str(s=name)])

def method_call(obj, method_name, args):
    return ast.Call(
        func=ast.Attribute(
            value=obj,
            attr=method_name,
            ctx=ast.Load()),
        args=args,
        keywords=[],
        starargs=None,
        kwargs=None)

_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
def is_identifier(id):
    return bool(_name_re.match(id))

def _get_arg_names(args):
    return tuple(arg.id for arg in args.args)

def make_Lambda(arg_vars, body):
    return ast.Lambda(
        args=ast.arguments(
            args=[
                ast.Name(id=arg_var, ctx=ast.Param())
                for arg_var in arg_vars],
            vararg=None,
            kwarg=None,
            defaults=[]),
        body=body)

def make_simple_Call(func, args):
    return ast.Call(
        func=func,
        args=args,
        keywords=[],
        starargs=None,
        kwargs=None)

def expr_Raise_Exception_string(message):
    # hack: (_ for _ in ()).throw(Exception(message))
    return ast.Call(
        func=ast.Attribute(
            value=ast.GeneratorExp(
                elt=ast.Name(id='_', ctx=ast.Load()),
                generators=[
                    ast.comprehension(
                        target=ast.Name(id='_', ctx=ast.Store()),
                        iter=ast.Tuple(
                            elts=[],
                            ctx=ast.Load()),
                        ifs=[])]),
            attr='throw', ctx=ast.Load()),
        args=[builtin_call('Exception', [ast.Str(s=message)])],
        keywords=[],
        starargs=None,
        kwargs=None)

def stmt_Raise_Exception_string(message):
    return ast.Raise(
        type=builtin_call('Exception', [ast.Str(s=message)]),
        inst=None,
        tback=None)

def make_binary_And(left, right):
    return ast.BoolOp(
        op=ast.And(),
        values=[left, right])

def make_Attribute(value, attr):
    return ast.Attribute(
        value=value,
        attr=attr,
        ctx=ast.Load())

def make_Subscript_Num_Index(value, n):
    return ast.Subscript(
        value=value,
        slice=ast.Index(
            value=ast.Num(n=n)
        ),
        ctx=ast.Load())

def cond_vacuously_true(cond):
    if isinstance(cond, ast.Name) and cond.id == "True":
        return True
    if isinstance(cond, ast.BoolOp):
        if isinstance(cond.op, ast.And):
            for value in cond.values:
                if not cond_vacuously_true(value):
                    return False
            return True
    return False


text:
package net.bytebuddy.implementation.bytecode.assign;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.assign.primitive.PrimitiveTypeAwareAssigner;
import net.bytebuddy.implementation.bytecode.assign.primitive.VoidAwareAssigner;
import net.bytebuddy.implementation.bytecode.assign.reference.ReferenceTypeAwareAssigner;

/**
 * An assigner is responsible for converting some type {@code A} to another type {@code B} if possible.
 * <p> </p>
 * An assigner is for example responsible for type casting, auto boxing or unboxing or for the widening of primitive
 * types.
 */
@SuppressFBWarnings(value = "IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION", justification = "Safe initialization is implied")
public interface Assigner {

    /**
     * A default assigner that can handle {@code void}, primitive types and references.
     */
    Assigner DEFAULT = new VoidAwareAssigner(new PrimitiveTypeAwareAssigner(ReferenceTypeAwareAssigner.INSTANCE));

    /**
     * @param source The original type that is to be transformed into the {@code targetType}.
     * @param target The target type into which the {@code sourceType} is to be converted.
     * @param typing A hint whether the assignment should consider the runtime type of the source type,
     *               i.e. if type down or cross castings are allowed. If this hint is set, this is
     *               also an indication that {@code void} to non-{@code void} assignments are permitted.
     * @return A stack manipulation that transforms the {@code sourceType} into the {@code targetType} if this
     * is possible. An illegal stack manipulation otherwise.
     */
    StackManipulation assign(TypeDescription.Generic source, TypeDescription.Generic target, Typing typing);

    /**
     * Indicates for a type assignment, if a type casting should be applied in case that two types are not statically assignable.
     * Also, a dynamic typing indicates that void values are assignable to other types by assigning the target type's default value.
     */
    enum Typing {

        /**
         * Requires static typing.
         */
        STATIC(false),

        /**
         * Allows dynamic typing.
         */
        DYNAMIC(true);

        /**
         * {@code true} if dynamic typing is a legitimate choice.
         */
        private final boolean dynamic;

        /**
         * Creates a new typing hint.
         *
         * @param dynamic {@code true} if dynamic typing is a legitimate choice.
         */
        Typing(boolean dynamic) {
            this.dynamic = dynamic;
        }

        /**
         * Resolves a typing constant for the presented boolean where {@code true} indicates that dynamic typing is a legitimate choice.
         *
         * @param dynamic An indicator for if dynamic typing is a legitimate choice.
         * @return A corresponding typing constant.
         */
        public static Typing of(boolean dynamic) {
            return dynamic
                    ? DYNAMIC
                    : STATIC;
        }

        /**
         * Checks if this instance's typing behavior permits dynamic typing.
         *
         * @return {@code true} if dynamic typing is a legitimate choice.
         */
        public boolean isDynamic() {
            return dynamic;
        }
    }

    /**
     * An assigner that only allows to assign types if they are equal to another.
     */
    enum EqualTypesOnly implements Assigner {

        /**
         * An type assigner that only considers equal generic types to be assignable.
         */
        GENERIC {
            /** {@inheritDoc} */
            public StackManipulation assign(TypeDescription.Generic source, TypeDescription.Generic target, Typing typing) {
                return source.equals(target)
                        ? StackManipulation.Trivial.INSTANCE
                        : StackManipulation.Illegal.INSTANCE;
            }
        },

        /**
         * A type assigner that considers two generic types to be equal if their erasure is equal.
         */
        ERASURE {
            /** {@inheritDoc} */
            public StackManipulation assign(TypeDescription.Generic source, TypeDescription.Generic target, Typing typing) {
                return source.asErasure().equals(target.asErasure())
                        ? StackManipulation.Trivial.INSTANCE
                        : StackManipulation.Illegal.INSTANCE;
            }
        };
    }

    /**
     * An assigner that does not allow any assignments.
     */
    enum Refusing implements Assigner {

        /**
         * The singleton instance.
         */
        INSTANCE;

        /**
         * {@inheritDoc}
         */
        public StackManipulation assign(TypeDescription.Generic source, TypeDescription.Generic target, Typing typing) {
            return StackManipulation.Illegal.INSTANCE;
        }
    }
}


text:
import { getNestedKeys, getNestedActions } from './nested.js'
import { getWriteAction } from './write_action.js'

// Parse an object (including its children) inside `args.data`
// as a set of write actions
export const parseActions = function ({ data, ...rest }) {
  const dataA = normalizeData({ data })

  const nestedKeys = getNestedKeys({ data: dataA, ...rest })
  // Pass `parseActions` for recursion
  const nestedActions = getNestedActions({
    parseActions,
    data: dataA,
    nestedKeys,
    ...rest,
  })
  const action = getWriteAction({ data: dataA, nestedKeys, ...rest })
  const actionA = filterAction({ action })
  return [...actionA, ...nestedActions]
}

// Commands are normalized to being only multiple
// So we also normalize `args.data` to always be an array
const normalizeData = function ({ data }) {
  return Array.isArray(data) ? data : [data]
}

// Do not create actions with empty `args.data`
const filterAction = function ({
  action,
  action: {
    args: { data },
  },
}) {
  const isEmptyAction = data.length === 0

  if (isEmptyAction) {
    return []
  }

  return [action]
}


text:
/*
 * E_Ethernet.hpp
 *
 *  Created on: 2014. 11. 20.
 *      Author: 근홍
 */

#ifndef E_ETHERNET_HPP_
#define E_ETHERNET_HPP_

#include <E/Networking/E_Networking.hpp>
#include <E/Networking/E_Host.hpp>

namespace E
{

class Ethernet : public HostModule, public NetworkModule, private NetworkLog
{
public:
	Ethernet(Host* host);
	virtual ~Ethernet();
protected:
	virtual void packetArrived(std::string fromModule, Packet* packet) final;
};

}

#endif /* E_ETHERNET_HPP_ */


text:
String.prototype.replaceAll = function(stringToFind, stringToReplace) {
	var temp = this;
	var index = temp.indexOf(stringToFind);
	while (index != -1) {
		temp = temp.replace(stringToFind, stringToReplace);
		index = temp.indexOf(stringToFind);
	}
	return temp;
};

function htmlEncode(value){
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return jQuery('<div />').html(value).text();
    } else {
        return '';
    }
}

function toDateString(time){
	var date = new Date(parseInt(time)*1000);
	return (date.getMonth().toString() + '/' + date.getDate().toString() + '/' +  date.getFullYear().toString());
}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function encodeQueryData(data)
{
   var ret = [];
   for (var d in data)
      ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
   return ret.join("&");
}

(function(){
  var cache = {};
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

//alert(currentUrl);

if(currentUrl.indexOf('localhost') < 0){
	var h = function(rs){
		console.log(rs);
	};
	//jQuery.getJSON("http://127.0.0.1:9090/tracking",{reading_url : currentUrl, referrer : referrerUrl},h);
}

//www.facebook.com/plugins/like


text:
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

Meteor.startup(function () {

  Template[getTemplate('search')].helpers({
    canSearch: function () {
      return canView(Meteor.user());
    },
    searchQuery: function () {
      return Session.get("searchQuery");
    },
    searchQueryEmpty: function () {
      return !!Session.get("searchQuery") ? '' : 'empty';
    }
  });

  Template[getTemplate('search')].events({
    'keyup, search .search-field': function(e){
      e.preventDefault();
      var val = $(e.target).val(),
          $search = $('.search');
      if (val === '') {
        // if search field is empty, just do nothing and show an empty template
        $search.addClass('empty');
        Session.set('searchQuery', '');
        Router.go('search', null, {replaceState: true});
      } else {
        $search.removeClass('empty');
        // if search field is not empty, add a delay to avoid firing new searches for every keystroke
        delay(function(){
          Session.set('searchQuery', val);

          // Update the querystring.
          var opts = {query: {q: val}};
          // if we're already on the search page, do a replaceState. Otherwise,
          // just use the pushState default.
          if(Router.current().route.getName() === 'search') {
            opts.replaceState = true;
          }
          Router.go('search', null, opts);

        }, 700 );
      }
    }
  });

});


text:
require 'origen'
require 'socket'
require 'origen_link/vector_based'
require 'origen_link/listener'
require_relative '../config/version'


text:
SQUARE_APP_ID     = 'YOUR APP ID HERE'
SQUARE_APP_SECRET = 'YOUR APP SECRET HERE'

# Headers to provide to OAuth API endpoints
SQUARE_OAUTH_REQUEST_HEADERS = {
  'Authorization' => "Client #{SQUARE_APP_SECRET}",
  'Accept' => 'application/json',
  'Content-Type' => 'application/json'
}

SQUARE_CONNECT_HOST = 'https://connect.squareup.com'

# Set the path you'd like your user to go to after they go to Square's site
# and authorize your app.
# Upon redirect, your customer's square access token will be in the session
# variable session[:square_access_token]

SQUARE_AFTER_AUTHORIZE_PATH = nil # path to go to after user authorizes, eg '/home/dashboard'

SQUARE_SCOPE = 'PAYMENTS_READ,MERCHANT_PROFILE_READ' # set to desired permissions.  See

include SquareRails


text:
package v6fakes

import (
	sync "sync"

	v3action "code.cloudfoundry.org/cli/actor/v3action"
	v6 "code.cloudfoundry.org/cli/command/v6"
)

type FakeV3PushVersionActor struct {
	CloudControllerAPIVersionStub        func() string
	cloudControllerAPIVersionMutex       sync.RWMutex
	cloudControllerAPIVersionArgsForCall []struct {
	}
	cloudControllerAPIVersionReturns struct {
		result1 string
	}
	cloudControllerAPIVersionReturnsOnCall map[int]struct {
		result1 string
	}
	GetStreamingLogsForApplicationByNameAndSpaceStub        func(string, string, v3action.NOAAClient) (<-chan *v3action.LogMessage, <-chan error, v3action.Warnings, error)
	getStreamingLogsForApplicationByNameAndSpaceMutex       sync.RWMutex
	getStreamingLogsForApplicationByNameAndSpaceArgsForCall []struct {
		arg1 string
		arg2 string
		arg3 v3action.NOAAClient
	}
	getStreamingLogsForApplicationByNameAndSpaceReturns struct {
		result1 <-chan *v3action.LogMessage
		result2 <-chan error
		result3 v3action.Warnings
		result4 error
	}
	getStreamingLogsForApplicationByNameAndSpaceReturnsOnCall map[int]struct {
		result1 <-chan *v3action.LogMessage
		result2 <-chan error
		result3 v3action.Warnings
		result4 error
	}
	PollStartStub        func(string, chan<- v3action.Warnings) error
	pollStartMutex       sync.RWMutex
	pollStartArgsForCall []struct {
		arg1 string
		arg2 chan<- v3action.Warnings
	}
	pollStartReturns struct {
		result1 error
	}
	pollStartReturnsOnCall map[int]struct {
		result1 error
	}
	RestartApplicationStub        func(string) (v3action.Warnings, error)
	restartApplicationMutex       sync.RWMutex
	restartApplicationArgsForCall []struct {
		arg1 string
	}
	restartApplicationReturns struct {
		result1 v3action.Warnings
		result2 error
	}
	restartApplicationReturnsOnCall map[int]struct {
		result1 v3action.Warnings
		result2 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeV3PushVersionActor) CloudControllerAPIVersion() string {
	fake.cloudControllerAPIVersionMutex.Lock()
	ret, specificReturn := fake.cloudControllerAPIVersionReturnsOnCall[len(fake.cloudControllerAPIVersionArgsForCall)]
	fake.cloudControllerAPIVersionArgsForCall = append(fake.cloudControllerAPIVersionArgsForCall, struct {
	}{})
	fake.recordInvocation("CloudControllerAPIVersion", []interface{}{})
	fake.cloudControllerAPIVersionMutex.Unlock()
	if fake.CloudControllerAPIVersionStub != nil {
		return fake.CloudControllerAPIVersionStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.cloudControllerAPIVersionReturns
	return fakeReturns.result1
}

func (fake *FakeV3PushVersionActor) CloudControllerAPIVersionCallCount() int {
	fake.cloudControllerAPIVersionMutex.RLock()
	defer fake.cloudControllerAPIVersionMutex.RUnlock()
	return len(fake.cloudControllerAPIVersionArgsForCall)
}

func (fake *FakeV3PushVersionActor) CloudControllerAPIVersionCalls(stub func() string) {
	fake.cloudControllerAPIVersionMutex.Lock()
	defer fake.cloudControllerAPIVersionMutex.Unlock()
	fake.CloudControllerAPIVersionStub = stub
}

func (fake *FakeV3PushVersionActor) CloudControllerAPIVersionReturns(result1 string) {
	fake.cloudControllerAPIVersionMutex.Lock()
	defer fake.cloudControllerAPIVersionMutex.Unlock()
	fake.CloudControllerAPIVersionStub = nil
	fake.cloudControllerAPIVersionReturns = struct {
		result1 string
	}{result1}
}

func (fake *FakeV3PushVersionActor) CloudControllerAPIVersionReturnsOnCall(i int, result1 string) {
	fake.cloudControllerAPIVersionMutex.Lock()
	defer fake.cloudControllerAPIVersionMutex.Unlock()
	fake.CloudControllerAPIVersionStub = nil
	if fake.cloudControllerAPIVersionReturnsOnCall == nil {
		fake.cloudControllerAPIVersionReturnsOnCall = make(map[int]struct {
			result1 string
		})
	}
	fake.cloudControllerAPIVersionReturnsOnCall[i] = struct {
		result1 string
	}{result1}
}

func (fake *FakeV3PushVersionActor) GetStreamingLogsForApplicationByNameAndSpace(arg1 string, arg2 string, arg3 v3action.NOAAClient) (<-chan *v3action.LogMessage, <-chan error, v3action.Warnings, error) {
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Lock()
	ret, specificReturn := fake.getStreamingLogsForApplicationByNameAndSpaceReturnsOnCall[len(fake.getStreamingLogsForApplicationByNameAndSpaceArgsForCall)]
	fake.getStreamingLogsForApplicationByNameAndSpaceArgsForCall = append(fake.getStreamingLogsForApplicationByNameAndSpaceArgsForCall, struct {
		arg1 string
		arg2 string
		arg3 v3action.NOAAClient
	}{arg1, arg2, arg3})
	fake.recordInvocation("GetStreamingLogsForApplicationByNameAndSpace", []interface{}{arg1, arg2, arg3})
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Unlock()
	if fake.GetStreamingLogsForApplicationByNameAndSpaceStub != nil {
		return fake.GetStreamingLogsForApplicationByNameAndSpaceStub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1, ret.result2, ret.result3, ret.result4
	}
	fakeReturns := fake.getStreamingLogsForApplicationByNameAndSpaceReturns
	return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3, fakeReturns.result4
}

func (fake *FakeV3PushVersionActor) GetStreamingLogsForApplicationByNameAndSpaceCallCount() int {
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.RLock()
	defer fake.getStreamingLogsForApplicationByNameAndSpaceMutex.RUnlock()
	return len(fake.getStreamingLogsForApplicationByNameAndSpaceArgsForCall)
}

func (fake *FakeV3PushVersionActor) GetStreamingLogsForApplicationByNameAndSpaceCalls(stub func(string, string, v3action.NOAAClient) (<-chan *v3action.LogMessage, <-chan error, v3action.Warnings, error)) {
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Lock()
	defer fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Unlock()
	fake.GetStreamingLogsForApplicationByNameAndSpaceStub = stub
}

func (fake *FakeV3PushVersionActor) GetStreamingLogsForApplicationByNameAndSpaceArgsForCall(i int) (string, string, v3action.NOAAClient) {
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.RLock()
	defer fake.getStreamingLogsForApplicationByNameAndSpaceMutex.RUnlock()
	argsForCall := fake.getStreamingLogsForApplicationByNameAndSpaceArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeV3PushVersionActor) GetStreamingLogsForApplicationByNameAndSpaceReturns(result1 <-chan *v3action.LogMessage, result2 <-chan error, result3 v3action.Warnings, result4 error) {
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Lock()
	defer fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Unlock()
	fake.GetStreamingLogsForApplicationByNameAndSpaceStub = nil
	fake.getStreamingLogsForApplicationByNameAndSpaceReturns = struct {
		result1 <-chan *v3action.LogMessage
		result2 <-chan error
		result3 v3action.Warnings
		result4 error
	}{result1, result2, result3, result4}
}

func (fake *FakeV3PushVersionActor) GetStreamingLogsForApplicationByNameAndSpaceReturnsOnCall(i int, result1 <-chan *v3action.LogMessage, result2 <-chan error, result3 v3action.Warnings, result4 error) {
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Lock()
	defer fake.getStreamingLogsForApplicationByNameAndSpaceMutex.Unlock()
	fake.GetStreamingLogsForApplicationByNameAndSpaceStub = nil
	if fake.getStreamingLogsForApplicationByNameAndSpaceReturnsOnCall == nil {
		fake.getStreamingLogsForApplicationByNameAndSpaceReturnsOnCall = make(map[int]struct {
			result1 <-chan *v3action.LogMessage
			result2 <-chan error
			result3 v3action.Warnings
			result4 error
		})
	}
	fake.getStreamingLogsForApplicationByNameAndSpaceReturnsOnCall[i] = struct {
		result1 <-chan *v3action.LogMessage
		result2 <-chan error
		result3 v3action.Warnings
		result4 error
	}{result1, result2, result3, result4}
}

func (fake *FakeV3PushVersionActor) PollStart(arg1 string, arg2 chan<- v3action.Warnings) error {
	fake.pollStartMutex.Lock()
	ret, specificReturn := fake.pollStartReturnsOnCall[len(fake.pollStartArgsForCall)]
	fake.pollStartArgsForCall = append(fake.pollStartArgsForCall, struct {
		arg1 string
		arg2 chan<- v3action.Warnings
	}{arg1, arg2})
	fake.recordInvocation("PollStart", []interface{}{arg1, arg2})
	fake.pollStartMutex.Unlock()
	if fake.PollStartStub != nil {
		return fake.PollStartStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.pollStartReturns
	return fakeReturns.result1
}

func (fake *FakeV3PushVersionActor) PollStartCallCount() int {
	fake.pollStartMutex.RLock()
	defer fake.pollStartMutex.RUnlock()
	return len(fake.pollStartArgsForCall)
}

func (fake *FakeV3PushVersionActor) PollStartCalls(stub func(string, chan<- v3action.Warnings) error) {
	fake.pollStartMutex.Lock()
	defer fake.pollStartMutex.Unlock()
	fake.PollStartStub = stub
}

func (fake *FakeV3PushVersionActor) PollStartArgsForCall(i int) (string, chan<- v3action.Warnings) {
	fake.pollStartMutex.RLock()
	defer fake.pollStartMutex.RUnlock()
	argsForCall := fake.pollStartArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeV3PushVersionActor) PollStartReturns(result1 error) {
	fake.pollStartMutex.Lock()
	defer fake.pollStartMutex.Unlock()
	fake.PollStartStub = nil
	fake.pollStartReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeV3PushVersionActor) PollStartReturnsOnCall(i int, result1 error) {
	fake.pollStartMutex.Lock()
	defer fake.pollStartMutex.Unlock()
	fake.PollStartStub = nil
	if fake.pollStartReturnsOnCall == nil {
		fake.pollStartReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.pollStartReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeV3PushVersionActor) RestartApplication(arg1 string) (v3action.Warnings, error) {
	fake.restartApplicationMutex.Lock()
	ret, specificReturn := fake.restartApplicationReturnsOnCall[len(fake.restartApplicationArgsForCall)]
	fake.restartApplicationArgsForCall = append(fake.restartApplicationArgsForCall, struct {
		arg1 string
	}{arg1})
	fake.recordInvocation("RestartApplication", []interface{}{arg1})
	fake.restartApplicationMutex.Unlock()
	if fake.RestartApplicationStub != nil {
		return fake.RestartApplicationStub(arg1)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.restartApplicationReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeV3PushVersionActor) RestartApplicationCallCount() int {
	fake.restartApplicationMutex.RLock()
	defer fake.restartApplicationMutex.RUnlock()
	return len(fake.restartApplicationArgsForCall)
}

func (fake *FakeV3PushVersionActor) RestartApplicationCalls(stub func(string) (v3action.Warnings, error)) {
	fake.restartApplicationMutex.Lock()
	defer fake.restartApplicationMutex.Unlock()
	fake.RestartApplicationStub = stub
}

func (fake *FakeV3PushVersionActor) RestartApplicationArgsForCall(i int) string {
	fake.restartApplicationMutex.RLock()
	defer fake.restartApplicationMutex.RUnlock()
	argsForCall := fake.restartApplicationArgsForCall[i]
	return argsForCall.arg1
}

func (fake *FakeV3PushVersionActor) RestartApplicationReturns(result1 v3action.Warnings, result2 error) {
	fake.restartApplicationMutex.Lock()
	defer fake.restartApplicationMutex.Unlock()
	fake.RestartApplicationStub = nil
	fake.restartApplicationReturns = struct {
		result1 v3action.Warnings
		result2 error
	}{result1, result2}
}

func (fake *FakeV3PushVersionActor) RestartApplicationReturnsOnCall(i int, result1 v3action.Warnings, result2 error) {
	fake.restartApplicationMutex.Lock()
	defer fake.restartApplicationMutex.Unlock()
	fake.RestartApplicationStub = nil
	if fake.restartApplicationReturnsOnCall == nil {
		fake.restartApplicationReturnsOnCall = make(map[int]struct {
			result1 v3action.Warnings
			result2 error
		})
	}
	fake.restartApplicationReturnsOnCall[i] = struct {
		result1 v3action.Warnings
		result2 error
	}{result1, result2}
}

func (fake *FakeV3PushVersionActor) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.cloudControllerAPIVersionMutex.RLock()
	defer fake.cloudControllerAPIVersionMutex.RUnlock()
	fake.getStreamingLogsForApplicationByNameAndSpaceMutex.RLock()
	defer fake.getStreamingLogsForApplicationByNameAndSpaceMutex.RUnlock()
	fake.pollStartMutex.RLock()
	defer fake.pollStartMutex.RUnlock()
	fake.restartApplicationMutex.RLock()
	defer fake.restartApplicationMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeV3PushVersionActor) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ v6.V3PushVersionActor = new(FakeV3PushVersionActor)


text:
1.  [Overview](#overview)
2.  [Writing Action Creators](#writing-action-creators)
3.  [Dispatching to Domains](#dispatching-to-domains)
4.  [How this works](#how-this-works)
5.  [API](#api)

## Overview

Microcosm uses actions to queue up some task and track its
progress. Actions are ultimately dispatched to domains and effects for
additional processing. Use actions to send requests to a server, or
dispatch a global notification that some user action has occurred.

Create an action by executing `Microcosm::push` with a function that
performs some type of work. We call this function an _action creator_.

```javascript
// axios is an AJAX library
// https://github.com/mzabriskie/axios
import axios from 'axios'

const repo = new Microcosm()

function createPlanet(data) {
  // This will return a promise, which Microcosm automatically
  // understands. Read further for more details.
  return axios.post('/planets', data)
}

const action = repo.push(createPlanet, { name: 'Venus' })

action.onDone(function() {
  console.log('All done!')
})
```

An action moves through several states:

1.  `open`: Indicates work has started.
2.  `loading`: Used for progress updates.
3.  `done`: The action has completed successfully.
4.  `error`: The action has failed.
5.  `cancelled`: Useful tracking aborted XHR requests or closed dialog modals.

You can access these states with varying degrees of control depending
on how you author action creators.

## Writing Action Creators

There are four ways to write action creators in Microcosm, all of
which relate to the value returned from functions passed into `repo.push()`.

### Return a primitive value

Action creators that return a primitive value resolve immediately:

```javascript
function addPlanet(props) {
  return props
}

repo.push(addPlanet, { name: 'Saturn' })
```

### Return a promise

```javascript
import axios from 'axios'

function getPlanet(id) {
  // Any promise-based AJAX library will do. We like axios
  return axios(`/planets/${id}`)
}

repo.push(getPlanet, 'mars')
```

When returning a Promise:

1.  The action is opened with the first argument of the parameters
    passed to `repo.push`. In this case: `'mars'`
2.  When the request finishes, the action is resolved with the payload
    passed into the Promise's resolve callback
3.  If the request fails, the action is rejected with whatever error
    was passed with the Promise's reject callback

### Return a function

Action creators that return functions grant full access to the action
that represents it. If we were to write a lower level version of the Promise
example earlier:

```javascript
function readPlanets() {
  return function(action) {
    action.open()

    const xhr = new XMLHttpRequest()

    xhr.open('GET', '/planets')
    xhr.setRequestHeader('Content-Type', 'application/json')

    xhr.addEventListener('load', function() {
      action.resolve(JSON.parse(xhr.responseText))
    })

    xhr.addEventListener('error', function() {
      action.reject({ status: xhr.status })
    })

    xhr.send()
  }
}

repo.push(readPlanets)
```

**Heads up:** Sometimes you want an action to return a function that isn't
executed as a thunk. If you pass a function as an action argument and return
that function in the action body, Microcosm _will not_ treat this as a thunk.

```javascript
function noThunk(fn) {
  return fn // will not be called as a thunk by Microcosm
}
```

If you need to return a function from an action body consider wrapping it in a
thunk:

```javascript
function actionReturnsFunction() {
  return function(action) {
    action.resolve(x => x) // the action's payload will be this inner function
  }
}
```

Alternatively, if you want Microcosm to treat your function action argument as
a thunk, you can wrap it in an anonymous function first.

```javascript
function maybeThunk(thunkFn, shouldThunk) {
  if (shouldThunk) {
    return (action, repo) => thunkFn(action, repo)
  }
}
```

### Return a generator

**Heads up:** Generators are a new feature included in the JS2015
language specification, which does not have wide support. To get
around this, we recommend using [Babel](https://babeljs.io) with
the [regenerator](https://github.com/facebook/regenerator) polyfill
available
through [babel-polyfill](https://babeljs.io/docs/usage/polyfill/).

Often times we need to dispatch multiple actions in sequential
order. For example, what if we want to ask the user to confirm their
action before deleting a record?

This can be accomplished by using a generator:

```javascript
function ask(message) {
  return action => {
    if (confirm(message)) {
      action.resolve()
    } else {
      action.reject()
    }
  }
}

function deleteUser(id) {
  return axios.delete('/users/${id}')
}

function confirmAndDelete(user) {
  return function*(repo) {
    yield repo.push(ask, `Are you sure you want to delete ${user.name}?`)
    yield repo.push(deleteUser, user.id)
  }
}
```

Each `yield` in the generator processes sequentially. A parent action
is returned from `repo.push()` to represent the entire sequence. If
any action is cancelled or rejected along the way, the parent action
is rejected or cancelled with the same payload.

When all steps of the generator complete, the payload of the parent
action will be the resolved payload of the final action.

#### Yielding Actions in Parallel

By yielding an array of actions, you can wait for multiple actions to
complete before continuing:

```javascript
function getUser(id) {
  return fetch(`/users/${id}`)
}

function getUsers(ids) {
  return function*(repo) {
    yield ids.map(id => repo.push(getUser, id))
  }
}
```

If all actions resolve or cancel, the generator sequence
continues.

### Action status methods are auto-bound

Action status methods like `action.resolve()` and `action.reject()`
are auto-bound. They can be passed directly into a callback without
needing to wrap them in an anonymous function.

This is particularly useful when working with AJAX libraries. For
example, when working with `superagent`:

```javascript
import superagent from 'superagent'

function getPlanets() {
  return action => {
    let request = superagent.get('/planets')

    request.on('request', action.open)
    request.on('progress', action.update)
    request.on('abort', action.cancel)

    request.then(action.resolve, action.reject)
  }
}
```

## Dispatching to Domains

One of the differences between Microcosm and other Flux
implementations is the dispatch process. Sending actions to domains is
handled by Microcosm. Instead of dispatching `ACTION_LOADING` or
`ACTION_FAILED`, actions go through various states as they
resolve. You can subscribe to these states within domains like:

```javascript
// A sample domain that subscribes to every action state
const SolarSystem = {
  // ... Other domain methods

  register() {
    return {
      [getPlanet]: {
        open: this.setLoading,
        update: this.setProgress,
        done: this.addPlanet,
        error: this.setError,
        cancel: this.setCancelled
      }
    }
  }
}
```

## How this works

Whenever `repo.push()` is invoked, Microcosm creates a new `Action`
object, appending it to a ledger of all actions. As the state of an
action changes, the associated microcosm will run through all
outstanding actions to determine the next state.

By default, Microcosm will only hold on to unresolved actions. This
can be extended by setting the `maxHistory` setting when creating a Microcosm:

```javascript
const repo = new Microcosm({ maxHistory: 100 })
```

This is useful for debugging purposes, or to implement undo/redo
behavior.

## API

### `onDone(callback, [scope])`

Add a one-time event subscription for when the action resolves
successfully. If the action is already resolved, it will immediately
execute.

### `onError(callback, [scope])`

Add a one-time event subscription for when the action is rejected. If
the action has already failed, it will immediately execute.

### `onUpdate(callback, [scope])`

Listen for progress updates from an action as it loads. For example:

```javascript
function wait() {
  return function(action) {
    action.open()
    setTimeout(() => action.update(25), 500)
    setTimeout(() => action.update(50), 1000)
    setTimeout(() => action.update(75), 1500)
    setTimeout(() => action.resolve(100), 1000)
  }
}

repo.push(wait).onUpdate(function(payload) {
  console.log(payload) // 25...50...75
})
```

An important note here is that `onUpdate` does not trigger when an
action completes.

### `onCancel(callback, [scope])`

Add a one-time event subscription for when the action is cancelled. If
the action has already been cancelled, it will immediately execute.

### `then(resolve, reject)`

Return a promisified version of the action. This is useful for interop
with `async/await`, or working with testing tools like `ava` or
`mocha`.

```javascript
const result = await repo.push(promiseAction)

// or
repo.push(promiseAction).then(success, failure)
```

### `open([payload])`

Elevate an action into the `open` state and optional update the
payload. Domains registered to `action.open` will pick up on an action
within this state.

### `update([payload])`

Send a progress update. This will move an action into the `loading`
state and optional update the payload. Domains registered to
`action.loading` will pick up on an action within this state.

### `reject([payload])`

Reject an action. This will move an action into the `error` state and
optional update the payload. Domains registered to `action.error` will
pick up on an action within this state.

### `resolve([payload])`

Resolve an action. This will move an action into the `done` state and
optional update the payload. Domains registered to `action` or `action.done`
will pick up on an action within this state.

### `cancel()`

Cancel an action. This is useful for handling cases such as aborting
ajax requests. Moves an action into the `cancelled`. Domains registered
to `action.cancelled` will pick up on an action within this state.