text:
package org.apache.commons.functor.adapter;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.apache.commons.functor.BaseFunctorTest;
import org.apache.commons.functor.Predicate;
import org.apache.commons.functor.core.Constant;
import org.junit.Test;

/**
 * @version $Revision: 1365377 $ $Date: 2012-07-24 21:59:23 -0300 (Tue, 24 Jul 2012) $
 */
public class TestNullaryPredicatePredicate extends BaseFunctorTest {

    // Functor Testing Framework
    // ------------------------------------------------------------------------

    @Override
    protected Object makeFunctor() {
        return new NullaryPredicatePredicate<Object>(Constant.TRUE);
    }

    // Tests
    // ------------------------------------------------------------------------

    @Test
    public void testEvaluate() throws Exception {
        Predicate<Object> p = new NullaryPredicatePredicate<Object>(Constant.TRUE);
        assertTrue(p.test(null));
    }

    @Test
    public void testEquals() throws Exception {
        Predicate<Object> p = new NullaryPredicatePredicate<Object>(Constant.TRUE);
        assertEquals(p,p);
        assertObjectsAreEqual(p,new NullaryPredicatePredicate<Object>(Constant.TRUE));
        assertObjectsAreNotEqual(p,Constant.TRUE);
        assertObjectsAreNotEqual(p,new NullaryPredicatePredicate<Object>(Constant.FALSE));
        assertObjectsAreNotEqual(p,Constant.FALSE);
        assertTrue(!p.equals(null));
    }

    @Test
    public void testAdaptNull() throws Exception {
        assertNull(NullaryPredicatePredicate.adapt(null));
    }

    @Test
    public void testAdapt() throws Exception {
        assertNotNull(NullaryPredicatePredicate.adapt(Constant.TRUE));
    }
}


text:
function panels(data) {
let pathname = window.location.pathname
let panel = newPanel(pathname)
panel += panels(pathname, data)

// panel for adding new projects, items, forms
function newPanel(pathname) {
  if(pathname === '/project') {
    let newPanel = '

Create new project...

'
    return newPanel
  }
}

function panelMenu(data, pathname) {
  let panelMenu = []
  for (var i = 0; i < data.length; i++) {
     panelMenu.push('
' +
     '<button onclick="myFunction('+ i + ')" class="dropbtn">...</button>' +
     '
' +
       'Details' +
       'Repeat' +
       'Print...' +
       'Archive' +
       'History' +
     '
' +
   '
')
   }
}
// create an option menu for panels
function panel(data, pathname) {
// for each project return a html object
for (var i = 0; i < projects.length; i++) {
 projectPanels +=
  '

' +
  '
' +
  projects[i].project_name + '
' +
  projects[i].project_desc + '
' +
  projects[i].start_date + '
	' +
  '
' + projectActionMenu[i] +
  '

'
  }
 }
}

redpajama_set_name: RedPajamaGithub


text:
package com.datawizards.dmg.customizations

import com.datawizards.dmg.TestModel._
import com.datawizards.dmg.dialects.{H2Dialect, HiveDialect, MySQLDialect, RedshiftDialect}
import com.datawizards.dmg.generator.HiveGenerator
import com.datawizards.dmg.{DataModelGenerator, DataModelGeneratorBaseTest}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class UnderscoreConversionTest extends DataModelGeneratorBaseTest {

  test("Underscore conversion - H2") {
    val expected =
      """CREATE TABLE person_with_underscore_with_multiple_names(
        |   person_name VARCHAR,
        |   person_age INT
        |);""".stripMargin

    assertResultIgnoringNewLines(expected) {
      DataModelGenerator.generate[PersonWithUnderscoreWithMultipleNames](H2Dialect)
    }
  }

  test("Underscore conversion - Hive") {
    val expected =
      """CREATE TABLE PEOPLE(
        |   name STRING,
        |   person_age INT
        |)
        |TBLPROPERTIES(   'MODEL_GENERATOR_METADATA_HASH' = '1071146412')
        |;""".stripMargin

    assertResultIgnoringNewLines(expected) {
      DataModelGenerator.generate[PersonWithUnderscoreWithMultipleNames](new HiveGenerator)
    }
  }

  test("Underscore conversion - Redshift") {
    val expected =
      """CREATE TABLE person_with_underscore_with_multiple_names(
        |   name VARCHAR,
        |   age INTEGER
        |);""".stripMargin

    assertResultIgnoringNewLines(expected) {
      DataModelGenerator.generate[PersonWithUnderscoreWithMultipleNames](RedshiftDialect)
    }
  }

  test("Underscore conversion - MySQL") {
    val expected =
      """CREATE TABLE PersonWithUnderscoreWithMultipleNames(
        |   personName VARCHAR,
        |   personAge INT
        |);""".stripMargin

    assertResultIgnoringNewLines(expected) {
      DataModelGenerator.generate[PersonWithUnderscoreWithMultipleNames](MySQLDialect)
    }
  }

}


text:
package org.hl7.fhir.instance.model;

// Generated on Wed, Nov 11, 2015 10:54-0500 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hl7.fhir.instance.model.api.IBaseBackboneElement;
import org.hl7.fhir.instance.utilities.Utilities;

import ca.uhn.fhir.model.api.annotation.Block;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
/**
 * This resource provides the target, request and response, and action details for an action to be performed by the target on or about existing resources.
 */
@ResourceDef(name="ProcessRequest", profile="http://hl7.org/fhir/Profile/ProcessRequest")
public class ProcessRequest extends DomainResource {

    public enum ActionList {
        /**
         * Cancel, reverse or nullify the target resource.
         */
        CANCEL,
        /**
         * Check for previously un-read/ not-retrieved resources.
         */
        POLL,
        /**
         * Re-process the target resource.
         */
        REPROCESS,
        /**
         * Retrieve the processing status of the target resource.
         */
        STATUS,
        /**
         * added to help the parsers
         */
        NULL;
        public static ActionList fromCode(String codeString) throws Exception {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("cancel".equals(codeString))
          return CANCEL;
        if ("poll".equals(codeString))
          return POLL;
        if ("reprocess".equals(codeString))
          return REPROCESS;
        if ("status".equals(codeString))
          return STATUS;
        throw new Exception("Unknown ActionList code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case CANCEL: return "cancel";
            case POLL: return "poll";
            case REPROCESS: return "reprocess";
            case STATUS: return "status";
            default: return "?";
          }
        }
        public String getSystem() {
          switch (this) {
            case CANCEL: return "http://hl7.org/fhir/actionlist";
            case POLL: return "http://hl7.org/fhir/actionlist";
            case REPROCESS: return "http://hl7.org/fhir/actionlist";
            case STATUS: return "http://hl7.org/fhir/actionlist";
            default: return "?";
          }
        }
        public String getDefinition() {
          switch (this) {
            case CANCEL: return "Cancel, reverse or nullify the target resource.";
            case POLL: return "Check for previously un-read/ not-retrieved resources.";
            case REPROCESS: return "Re-process the target resource.";
            case STATUS: return "Retrieve the processing status of the target resource.";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case CANCEL: return "Cancel, Reverse or Nullify";
            case POLL: return "Poll";
            case REPROCESS: return "Re-Process";
            case STATUS: return "Status Check";
            default: return "?";
          }
        }
    }

  public static class ActionListEnumFactory implements EnumFactory<ActionList> {
    public ActionList fromCode(String codeString) throws IllegalArgumentException {
      if (codeString == null || "".equals(codeString))
            if (codeString == null || "".equals(codeString))
                return null;
        if ("cancel".equals(codeString))
          return ActionList.CANCEL;
        if ("poll".equals(codeString))
          return ActionList.POLL;
        if ("reprocess".equals(codeString))
          return ActionList.REPROCESS;
        if ("status".equals(codeString))
          return ActionList.STATUS;
        throw new IllegalArgumentException("Unknown ActionList code '"+codeString+"'");
        }
    public String toCode(ActionList code) {
      if (code == ActionList.CANCEL)
        return "cancel";
      if (code == ActionList.POLL)
        return "poll";
      if (code == ActionList.REPROCESS)
        return "reprocess";
      if (code == ActionList.STATUS)
        return "status";
      return "?";
      }
    }

    @Block()
    public static class ItemsComponent extends BackboneElement implements IBaseBackboneElement {
        /**
         * A service line number.
         */
        @Child(name = "sequenceLinkId", type = {IntegerType.class}, order=1, min=1, max=1, modifier=false, summary=true)
        @Description(shortDefinition="Service instance", formalDefinition="A service line number." )
        protected IntegerType sequenceLinkId;

        private static final long serialVersionUID = -1598360600L;

    /*
     * Constructor
     */
      public ItemsComponent() {
        super();
      }

    /*
     * Constructor
     */
      public ItemsComponent(IntegerType sequenceLinkId) {
        super();
        this.sequenceLinkId = sequenceLinkId;
      }

        /**
         * @return {@link #sequenceLinkId} (A service line number.). This is the underlying object with id, value and extensions. The accessor "getSequenceLinkId" gives direct access to the value
         */
        public IntegerType getSequenceLinkIdElement() {
          if (this.sequenceLinkId == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create ItemsComponent.sequenceLinkId");
            else if (Configuration.doAutoCreate())
              this.sequenceLinkId = new IntegerType(); // bb
          return this.sequenceLinkId;
        }

        public boolean hasSequenceLinkIdElement() {
          return this.sequenceLinkId != null && !this.sequenceLinkId.isEmpty();
        }

        public boolean hasSequenceLinkId() {
          return this.sequenceLinkId != null && !this.sequenceLinkId.isEmpty();
        }

        /**
         * @param value {@link #sequenceLinkId} (A service line number.). This is the underlying object with id, value and extensions. The accessor "getSequenceLinkId" gives direct access to the value
         */
        public ItemsComponent setSequenceLinkIdElement(IntegerType value) {
          this.sequenceLinkId = value;
          return this;
        }

        /**
         * @return A service line number.
         */
        public int getSequenceLinkId() {
          return this.sequenceLinkId == null || this.sequenceLinkId.isEmpty() ? 0 : this.sequenceLinkId.getValue();
        }

        /**
         * @param value A service line number.
         */
        public ItemsComponent setSequenceLinkId(int value) {
            if (this.sequenceLinkId == null)
              this.sequenceLinkId = new IntegerType();
            this.sequenceLinkId.setValue(value);
          return this;
        }

        protected void listChildren(List<Property> childrenList) {
          super.listChildren(childrenList);
          childrenList.add(new Property("sequenceLinkId", "integer", "A service line number.", 0, java.lang.Integer.MAX_VALUE, sequenceLinkId));
        }

      public ItemsComponent copy() {
        ItemsComponent dst = new ItemsComponent();
        copyValues(dst);
        dst.sequenceLinkId = sequenceLinkId == null ? null : sequenceLinkId.copy();
        return dst;
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof ItemsComponent))
          return false;
        ItemsComponent o = (ItemsComponent) other;
        return compareDeep(sequenceLinkId, o.sequenceLinkId, true);
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof ItemsComponent))
          return false;
        ItemsComponent o = (ItemsComponent) other;
        return compareValues(sequenceLinkId, o.sequenceLinkId, true);
      }

      public boolean isEmpty() {
        return super.isEmpty() && (sequenceLinkId == null || sequenceLinkId.isEmpty());
      }

  }

    /**
     * The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest.
     */
    @Child(name = "action", type = {CodeType.class}, order=0, min=1, max=1, modifier=false, summary=true)
    @Description(shortDefinition="cancel | poll | reprocess | status", formalDefinition="The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest." )
    protected Enumeration<ActionList> action;

    /**
     * The ProcessRequest business identifier.
     */
    @Child(name = "identifier", type = {Identifier.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="Business Identifier", formalDefinition="The ProcessRequest business identifier." )
    protected List<Identifier> identifier;

    /**
     * The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.
     */
    @Child(name = "ruleset", type = {Coding.class}, order=2, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Resource version", formalDefinition="The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources." )
    protected Coding ruleset;

    /**
     * The style (standard) and version of the original material which was converted into this resource.
     */
    @Child(name = "originalRuleset", type = {Coding.class}, order=3, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Original version", formalDefinition="The style (standard) and version of the original material which was converted into this resource." )
    protected Coding originalRuleset;

    /**
     * The date when this resource was created.
     */
    @Child(name = "created", type = {DateTimeType.class}, order=4, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Creation date", formalDefinition="The date when this resource was created." )
    protected DateTimeType created;

    /**
     * The organization which is the target of the request.
     */
    @Child(name = "target", type = {Organization.class}, order=5, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Target of the request", formalDefinition="The organization which is the target of the request." )
    protected Reference target;

    /**
     * The actual object that is the target of the reference (The organization which is the target of the request.)
     */
    protected Organization targetTarget;

    /**
     * The practitioner who is responsible for the action specified in thise request.
     */
    @Child(name = "provider", type = {Practitioner.class}, order=6, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Responsible practitioner", formalDefinition="The practitioner who is responsible for the action specified in thise request." )
    protected Reference provider;

    /**
     * The actual object that is the target of the reference (The practitioner who is responsible for the action specified in thise request.)
     */
    protected Practitioner providerTarget;

    /**
     * The organization which is responsible for the action speccified in thise request.
     */
    @Child(name = "organization", type = {Organization.class}, order=7, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Responsible organization", formalDefinition="The organization which is responsible for the action speccified in thise request." )
    protected Reference organization;

    /**
     * The actual object that is the target of the reference (The organization which is responsible for the action speccified in thise request.)
     */
    protected Organization organizationTarget;

    /**
     * Reference of resource which is the target or subject of this action.
     */
    @Child(name = "request", type = {}, order=8, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Request reference", formalDefinition="Reference of resource which is the target or subject of this action." )
    protected Reference request;

    /**
     * The actual object that is the target of the reference (Reference of resource which is the target or subject of this action.)
     */
    protected Resource requestTarget;

    /**
     * Reference of a prior response to resource which is the target or subject of this action.
     */
    @Child(name = "response", type = {}, order=9, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Response reference", formalDefinition="Reference of a prior response to resource which is the target or subject of this action." )
    protected Reference response;

    /**
     * The actual object that is the target of the reference (Reference of a prior response to resource which is the target or subject of this action.)
     */
    protected Resource responseTarget;

    /**
     * If true remove all history excluding audit.
     */
    @Child(name = "nullify", type = {BooleanType.class}, order=10, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Nullify", formalDefinition="If true remove all history excluding audit." )
    protected BooleanType nullify;

    /**
     * A reference to supply which authenticates the process.
     */
    @Child(name = "reference", type = {StringType.class}, order=11, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Reference number/string", formalDefinition="A reference to supply which authenticates the process." )
    protected StringType reference;

    /**
     * List of top level items to be re-adjudicated, if none specified then the entire submission is re-adjudicated.
     */
    @Child(name = "item", type = {}, order=12, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="Items to re-adjudicate", formalDefinition="List of top level items to be re-adjudicated, if none specified then the entire submission is re-adjudicated." )
    protected List<ItemsComponent> item;

    /**
     * Names of resource types to include.
     */
    @Child(name = "include", type = {StringType.class}, order=13, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="Resource type(s) to include", formalDefinition="Names of resource types to include." )
    protected List<StringType> include;

    /**
     * Names of resource types to exclude.
     */
    @Child(name = "exclude", type = {StringType.class}, order=14, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="Resource type(s) to exclude", formalDefinition="Names of resource types to exclude." )
    protected List<StringType> exclude;

    /**
     * A period of time during which the fulfilling resources would have been created.
     */
    @Child(name = "period", type = {Period.class}, order=15, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Period", formalDefinition="A period of time during which the fulfilling resources would have been created." )
    protected Period period;

    private static final long serialVersionUID = -1332331220L;

  /*
   * Constructor
   */
    public ProcessRequest() {
      super();
    }

  /*
   * Constructor
   */
    public ProcessRequest(Enumeration<ActionList> action) {
      super();
      this.action = action;
    }

    /**
     * @return {@link #action} (The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest.). This is the underlying object with id, value and extensions. The accessor "getAction" gives direct access to the value
     */
    public Enumeration<ActionList> getActionElement() {
      if (this.action == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.action");
        else if (Configuration.doAutoCreate())
          this.action = new Enumeration<ActionList>(new ActionListEnumFactory()); // bb
      return this.action;
    }

    public boolean hasActionElement() {
      return this.action != null && !this.action.isEmpty();
    }

    public boolean hasAction() {
      return this.action != null && !this.action.isEmpty();
    }

    /**
     * @param value {@link #action} (The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest.). This is the underlying object with id, value and extensions. The accessor "getAction" gives direct access to the value
     */
    public ProcessRequest setActionElement(Enumeration<ActionList> value) {
      this.action = value;
      return this;
    }

    /**
     * @return The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest.
     */
    public ActionList getAction() {
      return this.action == null ? null : this.action.getValue();
    }

    /**
     * @param value The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest.
     */
    public ProcessRequest setAction(ActionList value) {
        if (this.action == null)
          this.action = new Enumeration<ActionList>(new ActionListEnumFactory());
        this.action.setValue(value);
      return this;
    }

    /**
     * @return {@link #identifier} (The ProcessRequest business identifier.)
     */
    public List<Identifier> getIdentifier() {
      if (this.identifier == null)
        this.identifier = new ArrayList<Identifier>();
      return this.identifier;
    }

    public boolean hasIdentifier() {
      if (this.identifier == null)
        return false;
      for (Identifier item : this.identifier)
        if (!item.isEmpty())
          return true;
      return false;
    }

    /**
     * @return {@link #identifier} (The ProcessRequest business identifier.)
     */
    // syntactic sugar
    public Identifier addIdentifier() { //3
      Identifier t = new Identifier();
      if (this.identifier == null)
        this.identifier = new ArrayList<Identifier>();
      this.identifier.add(t);
      return t;
    }

    // syntactic sugar
    public ProcessRequest addIdentifier(Identifier t) { //3
      if (t == null)
        return this;
      if (this.identifier == null)
        this.identifier = new ArrayList<Identifier>();
      this.identifier.add(t);
      return this;
    }

    /**
     * @return {@link #ruleset} (The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.)
     */
    public Coding getRuleset() {
      if (this.ruleset == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.ruleset");
        else if (Configuration.doAutoCreate())
          this.ruleset = new Coding(); // cc
      return this.ruleset;
    }

    public boolean hasRuleset() {
      return this.ruleset != null && !this.ruleset.isEmpty();
    }

    /**
     * @param value {@link #ruleset} (The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.)
     */
    public ProcessRequest setRuleset(Coding value) {
      this.ruleset = value;
      return this;
    }

    /**
     * @return {@link #originalRuleset} (The style (standard) and version of the original material which was converted into this resource.)
     */
    public Coding getOriginalRuleset() {
      if (this.originalRuleset == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.originalRuleset");
        else if (Configuration.doAutoCreate())
          this.originalRuleset = new Coding(); // cc
      return this.originalRuleset;
    }

    public boolean hasOriginalRuleset() {
      return this.originalRuleset != null && !this.originalRuleset.isEmpty();
    }

    /**
     * @param value {@link #originalRuleset} (The style (standard) and version of the original material which was converted into this resource.)
     */
    public ProcessRequest setOriginalRuleset(Coding value) {
      this.originalRuleset = value;
      return this;
    }

    /**
     * @return {@link #created} (The date when this resource was created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value
     */
    public DateTimeType getCreatedElement() {
      if (this.created == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.created");
        else if (Configuration.doAutoCreate())
          this.created = new DateTimeType(); // bb
      return this.created;
    }

    public boolean hasCreatedElement() {
      return this.created != null && !this.created.isEmpty();
    }

    public boolean hasCreated() {
      return this.created != null && !this.created.isEmpty();
    }

    /**
     * @param value {@link #created} (The date when this resource was created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value
     */
    public ProcessRequest setCreatedElement(DateTimeType value) {
      this.created = value;
      return this;
    }

    /**
     * @return The date when this resource was created.
     */
    public Date getCreated() {
      return this.created == null ? null : this.created.getValue();
    }

    /**
     * @param value The date when this resource was created.
     */
    public ProcessRequest setCreated(Date value) {
      if (value == null)
        this.created = null;
      else {
        if (this.created == null)
          this.created = new DateTimeType();
        this.created.setValue(value);
      }
      return this;
    }

    /**
     * @return {@link #target} (The organization which is the target of the request.)
     */
    public Reference getTarget() {
      if (this.target == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.target");
        else if (Configuration.doAutoCreate())
          this.target = new Reference(); // cc
      return this.target;
    }

    public boolean hasTarget() {
      return this.target != null && !this.target.isEmpty();
    }

    /**
     * @param value {@link #target} (The organization which is the target of the request.)
     */
    public ProcessRequest setTarget(Reference value) {
      this.target = value;
      return this;
    }

    /**
     * @return {@link #target} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The organization which is the target of the request.)
     */
    public Organization getTargetTarget() {
      if (this.targetTarget == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.target");
        else if (Configuration.doAutoCreate())
          this.targetTarget = new Organization(); // aa
      return this.targetTarget;
    }

    /**
     * @param value {@link #target} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The organization which is the target of the request.)
     */
    public ProcessRequest setTargetTarget(Organization value) {
      this.targetTarget = value;
      return this;
    }

    /**
     * @return {@link #provider} (The practitioner who is responsible for the action specified in thise request.)
     */
    public Reference getProvider() {
      if (this.provider == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.provider");
        else if (Configuration.doAutoCreate())
          this.provider = new Reference(); // cc
      return this.provider;
    }

    public boolean hasProvider() {
      return this.provider != null && !this.provider.isEmpty();
    }

    /**
     * @param value {@link #provider} (The practitioner who is responsible for the action specified in thise request.)
     */
    public ProcessRequest setProvider(Reference value) {
      this.provider = value;
      return this;
    }

    /**
     * @return {@link #provider} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The practitioner who is responsible for the action specified in thise request.)
     */
    public Practitioner getProviderTarget() {
      if (this.providerTarget == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.provider");
        else if (Configuration.doAutoCreate())
          this.providerTarget = new Practitioner(); // aa
      return this.providerTarget;
    }

    /**
     * @param value {@link #provider} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The practitioner who is responsible for the action specified in thise request.)
     */
    public ProcessRequest setProviderTarget(Practitioner value) {
      this.providerTarget = value;
      return this;
    }

    /**
     * @return {@link #organization} (The organization which is responsible for the action speccified in thise request.)
     */
    public Reference getOrganization() {
      if (this.organization == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.organization");
        else if (Configuration.doAutoCreate())
          this.organization = new Reference(); // cc
      return this.organization;
    }

    public boolean hasOrganization() {
      return this.organization != null && !this.organization.isEmpty();
    }

    /**
     * @param value {@link #organization} (The organization which is responsible for the action speccified in thise request.)
     */
    public ProcessRequest setOrganization(Reference value) {
      this.organization = value;
      return this;
    }

    /**
     * @return {@link #organization} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The organization which is responsible for the action speccified in thise request.)
     */
    public Organization getOrganizationTarget() {
      if (this.organizationTarget == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.organization");
        else if (Configuration.doAutoCreate())
          this.organizationTarget = new Organization(); // aa
      return this.organizationTarget;
    }

    /**
     * @param value {@link #organization} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The organization which is responsible for the action speccified in thise request.)
     */
    public ProcessRequest setOrganizationTarget(Organization value) {
      this.organizationTarget = value;
      return this;
    }

    /**
     * @return {@link #request} (Reference of resource which is the target or subject of this action.)
     */
    public Reference getRequest() {
      if (this.request == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.request");
        else if (Configuration.doAutoCreate())
          this.request = new Reference(); // cc
      return this.request;
    }

    public boolean hasRequest() {
      return this.request != null && !this.request.isEmpty();
    }

    /**
     * @param value {@link #request} (Reference of resource which is the target or subject of this action.)
     */
    public ProcessRequest setRequest(Reference value) {
      this.request = value;
      return this;
    }

    /**
     * @return {@link #request} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Reference of resource which is the target or subject of this action.)
     */
    public Resource getRequestTarget() {
      return this.requestTarget;
    }

    /**
     * @param value {@link #request} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Reference of resource which is the target or subject of this action.)
     */
    public ProcessRequest setRequestTarget(Resource value) {
      this.requestTarget = value;
      return this;
    }

    /**
     * @return {@link #response} (Reference of a prior response to resource which is the target or subject of this action.)
     */
    public Reference getResponse() {
      if (this.response == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.response");
        else if (Configuration.doAutoCreate())
          this.response = new Reference(); // cc
      return this.response;
    }

    public boolean hasResponse() {
      return this.response != null && !this.response.isEmpty();
    }

    /**
     * @param value {@link #response} (Reference of a prior response to resource which is the target or subject of this action.)
     */
    public ProcessRequest setResponse(Reference value) {
      this.response = value;
      return this;
    }

    /**
     * @return {@link #response} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Reference of a prior response to resource which is the target or subject of this action.)
     */
    public Resource getResponseTarget() {
      return this.responseTarget;
    }

    /**
     * @param value {@link #response} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Reference of a prior response to resource which is the target or subject of this action.)
     */
    public ProcessRequest setResponseTarget(Resource value) {
      this.responseTarget = value;
      return this;
    }

    /**
     * @return {@link #nullify} (If true remove all history excluding audit.). This is the underlying object with id, value and extensions. The accessor "getNullify" gives direct access to the value
     */
    public BooleanType getNullifyElement() {
      if (this.nullify == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.nullify");
        else if (Configuration.doAutoCreate())
          this.nullify = new BooleanType(); // bb
      return this.nullify;
    }

    public boolean hasNullifyElement() {
      return this.nullify != null && !this.nullify.isEmpty();
    }

    public boolean hasNullify() {
      return this.nullify != null && !this.nullify.isEmpty();
    }

    /**
     * @param value {@link #nullify} (If true remove all history excluding audit.). This is the underlying object with id, value and extensions. The accessor "getNullify" gives direct access to the value
     */
    public ProcessRequest setNullifyElement(BooleanType value) {
      this.nullify = value;
      return this;
    }

    /**
     * @return If true remove all history excluding audit.
     */
    public boolean getNullify() {
      return this.nullify == null || this.nullify.isEmpty() ? false : this.nullify.getValue();
    }

    /**
     * @param value If true remove all history excluding audit.
     */
    public ProcessRequest setNullify(boolean value) {
        if (this.nullify == null)
          this.nullify = new BooleanType();
        this.nullify.setValue(value);
      return this;
    }

    /**
     * @return {@link #reference} (A reference to supply which authenticates the process.). This is the underlying object with id, value and extensions. The accessor "getReference" gives direct access to the value
     */
    public StringType getReferenceElement() {
      if (this.reference == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.reference");
        else if (Configuration.doAutoCreate())
          this.reference = new StringType(); // bb
      return this.reference;
    }

    public boolean hasReferenceElement() {
      return this.reference != null && !this.reference.isEmpty();
    }

    public boolean hasReference() {
      return this.reference != null && !this.reference.isEmpty();
    }

    /**
     * @param value {@link #reference} (A reference to supply which authenticates the process.). This is the underlying object with id, value and extensions. The accessor "getReference" gives direct access to the value
     */
    public ProcessRequest setReferenceElement(StringType value) {
      this.reference = value;
      return this;
    }

    /**
     * @return A reference to supply which authenticates the process.
     */
    public String getReference() {
      return this.reference == null ? null : this.reference.getValue();
    }

    /**
     * @param value A reference to supply which authenticates the process.
     */
    public ProcessRequest setReference(String value) {
      if (Utilities.noString(value))
        this.reference = null;
      else {
        if (this.reference == null)
          this.reference = new StringType();
        this.reference.setValue(value);
      }
      return this;
    }

    /**
     * @return {@link #item} (List of top level items to be re-adjudicated, if none specified then the entire submission is re-adjudicated.)
     */
    public List<ItemsComponent> getItem() {
      if (this.item == null)
        this.item = new ArrayList<ItemsComponent>();
      return this.item;
    }

    public boolean hasItem() {
      if (this.item == null)
        return false;
      for (ItemsComponent item : this.item)
        if (!item.isEmpty())
          return true;
      return false;
    }

    /**
     * @return {@link #item} (List of top level items to be re-adjudicated, if none specified then the entire submission is re-adjudicated.)
     */
    // syntactic sugar
    public ItemsComponent addItem() { //3
      ItemsComponent t = new ItemsComponent();
      if (this.item == null)
        this.item = new ArrayList<ItemsComponent>();
      this.item.add(t);
      return t;
    }

    // syntactic sugar
    public ProcessRequest addItem(ItemsComponent t) { //3
      if (t == null)
        return this;
      if (this.item == null)
        this.item = new ArrayList<ItemsComponent>();
      this.item.add(t);
      return this;
    }

    /**
     * @return {@link #include} (Names of resource types to include.)
     */
    public List<StringType> getInclude() {
      if (this.include == null)
        this.include = new ArrayList<StringType>();
      return this.include;
    }

    public boolean hasInclude() {
      if (this.include == null)
        return false;
      for (StringType item : this.include)
        if (!item.isEmpty())
          return true;
      return false;
    }

    /**
     * @return {@link #include} (Names of resource types to include.)
     */
    // syntactic sugar
    public StringType addIncludeElement() {//2
      StringType t = new StringType();
      if (this.include == null)
        this.include = new ArrayList<StringType>();
      this.include.add(t);
      return t;
    }

    /**
     * @param value {@link #include} (Names of resource types to include.)
     */
    public ProcessRequest addInclude(String value) { //1
      StringType t = new StringType();
      t.setValue(value);
      if (this.include == null)
        this.include = new ArrayList<StringType>();
      this.include.add(t);
      return this;
    }

    /**
     * @param value {@link #include} (Names of resource types to include.)
     */
    public boolean hasInclude(String value) {
      if (this.include == null)
        return false;
      for (StringType v : this.include)
        if (v.equals(value)) // string
          return true;
      return false;
    }

    /**
     * @return {@link #exclude} (Names of resource types to exclude.)
     */
    public List<StringType> getExclude() {
      if (this.exclude == null)
        this.exclude = new ArrayList<StringType>();
      return this.exclude;
    }

    public boolean hasExclude() {
      if (this.exclude == null)
        return false;
      for (StringType item : this.exclude)
        if (!item.isEmpty())
          return true;
      return false;
    }

    /**
     * @return {@link #exclude} (Names of resource types to exclude.)
     */
    // syntactic sugar
    public StringType addExcludeElement() {//2
      StringType t = new StringType();
      if (this.exclude == null)
        this.exclude = new ArrayList<StringType>();
      this.exclude.add(t);
      return t;
    }

    /**
     * @param value {@link #exclude} (Names of resource types to exclude.)
     */
    public ProcessRequest addExclude(String value) { //1
      StringType t = new StringType();
      t.setValue(value);
      if (this.exclude == null)
        this.exclude = new ArrayList<StringType>();
      this.exclude.add(t);
      return this;
    }

    /**
     * @param value {@link #exclude} (Names of resource types to exclude.)
     */
    public boolean hasExclude(String value) {
      if (this.exclude == null)
        return false;
      for (StringType v : this.exclude)
        if (v.equals(value)) // string
          return true;
      return false;
    }

    /**
     * @return {@link #period} (A period of time during which the fulfilling resources would have been created.)
     */
    public Period getPeriod() {
      if (this.period == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create ProcessRequest.period");
        else if (Configuration.doAutoCreate())
          this.period = new Period(); // cc
      return this.period;
    }

    public boolean hasPeriod() {
      return this.period != null && !this.period.isEmpty();
    }

    /**
     * @param value {@link #period} (A period of time during which the fulfilling resources would have been created.)
     */
    public ProcessRequest setPeriod(Period value) {
      this.period = value;
      return this;
    }

      protected void listChildren(List<Property> childrenList) {
        super.listChildren(childrenList);
        childrenList.add(new Property("action", "code", "The type of processing action being requested, for example Reversal, Readjudication, StatusRequest,PendedRequest.", 0, java.lang.Integer.MAX_VALUE, action));
        childrenList.add(new Property("identifier", "Identifier", "The ProcessRequest business identifier.", 0, java.lang.Integer.MAX_VALUE, identifier));
        childrenList.add(new Property("ruleset", "Coding", "The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.", 0, java.lang.Integer.MAX_VALUE, ruleset));
        childrenList.add(new Property("originalRuleset", "Coding", "The style (standard) and version of the original material which was converted into this resource.", 0, java.lang.Integer.MAX_VALUE, originalRuleset));
        childrenList.add(new Property("created", "dateTime", "The date when this resource was created.", 0, java.lang.Integer.MAX_VALUE, created));
        childrenList.add(new Property("target", "Reference(Organization)", "The organization which is the target of the request.", 0, java.lang.Integer.MAX_VALUE, target));
        childrenList.add(new Property("provider", "Reference(Practitioner)", "The practitioner who is responsible for the action specified in thise request.", 0, java.lang.Integer.MAX_VALUE, provider));
        childrenList.add(new Property("organization", "Reference(Organization)", "The organization which is responsible for the action speccified in thise request.", 0, java.lang.Integer.MAX_VALUE, organization));
        childrenList.add(new Property("request", "Reference(Any)", "Reference of resource which is the target or subject of this action.", 0, java.lang.Integer.MAX_VALUE, request));
        childrenList.add(new Property("response", "Reference(Any)", "Reference of a prior response to resource which is the target or subject of this action.", 0, java.lang.Integer.MAX_VALUE, response));
        childrenList.add(new Property("nullify", "boolean", "If true remove all history excluding audit.", 0, java.lang.Integer.MAX_VALUE, nullify));
        childrenList.add(new Property("reference", "string", "A reference to supply which authenticates the process.", 0, java.lang.Integer.MAX_VALUE, reference));
        childrenList.add(new Property("item", "", "List of top level items to be re-adjudicated, if none specified then the entire submission is re-adjudicated.", 0, java.lang.Integer.MAX_VALUE, item));
        childrenList.add(new Property("include", "string", "Names of resource types to include.", 0, java.lang.Integer.MAX_VALUE, include));
        childrenList.add(new Property("exclude", "string", "Names of resource types to exclude.", 0, java.lang.Integer.MAX_VALUE, exclude));
        childrenList.add(new Property("period", "Period", "A period of time during which the fulfilling resources would have been created.", 0, java.lang.Integer.MAX_VALUE, period));
      }

      public ProcessRequest copy() {
        ProcessRequest dst = new ProcessRequest();
        copyValues(dst);
        dst.action = action == null ? null : action.copy();
        if (identifier != null) {
          dst.identifier = new ArrayList<Identifier>();
          for (Identifier i : identifier)
            dst.identifier.add(i.copy());
        };
        dst.ruleset = ruleset == null ? null : ruleset.copy();
        dst.originalRuleset = originalRuleset == null ? null : originalRuleset.copy();
        dst.created = created == null ? null : created.copy();
        dst.target = target == null ? null : target.copy();
        dst.provider = provider == null ? null : provider.copy();
        dst.organization = organization == null ? null : organization.copy();
        dst.request = request == null ? null : request.copy();
        dst.response = response == null ? null : response.copy();
        dst.nullify = nullify == null ? null : nullify.copy();
        dst.reference = reference == null ? null : reference.copy();
        if (item != null) {
          dst.item = new ArrayList<ItemsComponent>();
          for (ItemsComponent i : item)
            dst.item.add(i.copy());
        };
        if (include != null) {
          dst.include = new ArrayList<StringType>();
          for (StringType i : include)
            dst.include.add(i.copy());
        };
        if (exclude != null) {
          dst.exclude = new ArrayList<StringType>();
          for (StringType i : exclude)
            dst.exclude.add(i.copy());
        };
        dst.period = period == null ? null : period.copy();
        return dst;
      }

      protected ProcessRequest typedCopy() {
        return copy();
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof ProcessRequest))
          return false;
        ProcessRequest o = (ProcessRequest) other;
        return compareDeep(action, o.action, true) && compareDeep(identifier, o.identifier, true) && compareDeep(ruleset, o.ruleset, true)
           && compareDeep(originalRuleset, o.originalRuleset, true) && compareDeep(created, o.created, true)
           && compareDeep(target, o.target, true) && compareDeep(provider, o.provider, true) && compareDeep(organization, o.organization, true)
           && compareDeep(request, o.request, true) && compareDeep(response, o.response, true) && compareDeep(nullify, o.nullify, true)
           && compareDeep(reference, o.reference, true) && compareDeep(item, o.item, true) && compareDeep(include, o.include, true)
           && compareDeep(exclude, o.exclude, true) && compareDeep(period, o.period, true);
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof ProcessRequest))
          return false;
        ProcessRequest o = (ProcessRequest) other;
        return compareValues(action, o.action, true) && compareValues(created, o.created, true) && compareValues(nullify, o.nullify, true)
           && compareValues(reference, o.reference, true) && compareValues(include, o.include, true) && compareValues(exclude, o.exclude, true)
          ;
      }

      public boolean isEmpty() {
        return super.isEmpty() && (action == null || action.isEmpty()) && (identifier == null || identifier.isEmpty())
           && (ruleset == null || ruleset.isEmpty()) && (originalRuleset == null || originalRuleset.isEmpty())
           && (created == null || created.isEmpty()) && (target == null || target.isEmpty()) && (provider == null || provider.isEmpty())
           && (organization == null || organization.isEmpty()) && (request == null || request.isEmpty())
           && (response == null || response.isEmpty()) && (nullify == null || nullify.isEmpty()) && (reference == null || reference.isEmpty())
           && (item == null || item.isEmpty()) && (include == null || include.isEmpty()) && (exclude == null || exclude.isEmpty())
           && (period == null || period.isEmpty());
      }

  @Override
  public ResourceType getResourceType() {
    return ResourceType.ProcessRequest;
   }

  @SearchParamDefinition(name="identifier", path="ProcessRequest.identifier", description="The business identifier of the ProcessRequest", type="token" )
  public static final String SP_IDENTIFIER = "identifier";
  @SearchParamDefinition(name="provider", path="ProcessRequest.provider", description="The provider who regenerated this request", type="reference" )
  public static final String SP_PROVIDER = "provider";
  @SearchParamDefinition(name="organization", path="ProcessRequest.organization", description="The organization who generated this request", type="reference" )
  public static final String SP_ORGANIZATION = "organization";
  @SearchParamDefinition(name="action", path="ProcessRequest.action", description="The action requested by this resource", type="token" )
  public static final String SP_ACTION = "action";

}


text:
date: '2011-05-23 21:18:09'
layout: post
slug: in-your-ear
title: "Watch out for in your ear"
categories:
- quotes
- culture
- video
---

This is one of my all-time favorite [movie exchanges](http://www.imdb.com/title/tt0097351/quotes?qt=qt0314985). From _Field of Dreams_, Shoeless Joe Jackson coaches Archie Graham about what pitch to expect after the first two pitches barely miss his forehead.

- Shoeless Joe Jackson: The first two were high and tight, so where do you think the next one's gonna be?
- Archie Graham: Well, either low and away, or _in my ear_.
- Shoeless Joe Jackson: He's not gonna wanna load the bases, so look low and away.
- Archie Graham: Right.
- Shoeless Joe Jackson: But watch out for in your ear.

I love that he says "watch out" for in your ear. Don't look for it. Just react if need be. If you are on the lookout for the pitch that's headed for your skull, you'll never [hit the sweet pitch](http://t.co/klPEiUJ).


text:
import yappi
import threading
class deadlock_thread(threading.Thread):
    # acquire the lock two times to create a very
    # simple deadlock:)
    def foo(self):
		for i in xrange(0,2): self.lock.acquire()
    def run(self):
        self.lock = threading.Lock()
        self.foo()
yappi.start() # start the profiler
thr = deadlock_thread() # start the deadlock thread
thr.start()
while 1:
    s = raw_input("yappi>")
    exec s


text:
package org.apache.pdfbox.pdmodel.graphics.shading;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.ColorModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.pdfbox.util.Matrix;

/**
 * Shades Gouraud triangles for Type4ShadingContext and Type5ShadingContext.
 *
 * @author Tilman Hausherr
 * @author Shaola Ren
 */
abstract class GouraudShadingContext extends TriangleBasedShadingContext
{
    /**
     * triangle list.
     */
    private List<ShadedTriangle> triangleList = new ArrayList<>();

    /**
     * Constructor creates an instance to be used for fill operations.
     *
     * @param shading the shading type to be used
     * @param colorModel the color model to be used
     * @param xform transformation for user to device space
     * @param matrix the pattern matrix concatenated with that of the parent content stream
     * @throws IOException if something went wrong
     */
    protected GouraudShadingContext(PDShading shading, ColorModel colorModel, AffineTransform xform,
                                    Matrix matrix) throws IOException
    {
        super(shading, colorModel, xform, matrix);
    }

    final void setTriangleList(List<ShadedTriangle> triangleList)
    {
        this.triangleList = triangleList;
    }

    @Override
    protected Map<Point, Integer> calcPixelTable(Rectangle deviceBounds) throws IOException
    {
        Map<Point, Integer> map = new HashMap<>();
        super.calcPixelTable(triangleList, map, deviceBounds);
        return map;
    }

    @Override
    public void dispose()
    {
        triangleList = null;
        super.dispose();
    }

    @Override
    protected boolean isDataEmpty()
    {
        return triangleList.isEmpty();
    }
}


text:
<!DOCTYPE html>

First

Second


text:
namespace Migrap.AspNet.Multitenant {
    internal partial class Tenant : ITenant {
        internal Tenant(string name) {
            Name = name;
        }

        public string Name { get; }
    }
}


text:
{-# LANGUAGE FlexibleContexts,FlexibleInstances,GADTs,DataKinds, PolyKinds, KindSignatures #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeOperators #-}

module Resin.Binders.Tree.Internal(
  -- | the safe subset of the api... I think
  IxEq(..)
  ,Inject(..)
  ,Extract(..) -- Extract is just a newtype wrapper .. for now
  ,TreeEq(..)
  ,treeElimination
  ,rightExtendInject
  ,leftExtendExtract
  ,jumpDepthInject -- not sure if this operation is safe
  ,jumpDepthExtract -- not sure if thats safe too
  ) where
import Numeric.Natural
import Data.Semigroupoid
--import Data.Coerce
import Unsafe.Coerce (unsafeCoerce)
import Data.Type.Equality
--import qualified Data.Semigroupoid.Dual as DL

{-
This module models binders which respect scope having a tree shaped topology
or at least it models some ideas about (finite?) paths on  (finite??!) trees

-}

data IxEq :: (k -> * ) -> k -> k   -> *  where
   PolyRefl ::  IxEq f i i
   MonoRefl :: forall f i . f i -> IxEq f i i

--testIxEquality :: TestEquality f => IxEq f a b -> IxEq f b c ->

instance TestEquality f => TestEquality (IxEq f i) where
  testEquality (MonoRefl f1) (MonoRefl f2) = testEquality f1 f2
  testEquality (PolyRefl  )(MonoRefl _f2) = Just Refl
  testEquality (MonoRefl _f1) (PolyRefl  ) = Just Refl
  testEquality (PolyRefl ) (PolyRefl ) = Just Refl

{- | `Inject` is about

-}
data Inject :: (k -> * ) -> k -> k -> *  where
  InjectRefl :: forall f a b . IxEq f a b->  Inject f a b
  --MonoId :: forall f  i .  (f i) -> Inject f i i
  -- should MonoId be strict in its argument?
  CompactCompose :: forall f i j . (IxEq f i i) -> (IxEq f  j j  )  -> Natural -> Inject f i j
   -- i is origin/root
   -- j is leaf
  -- compact compose is unsafe for users, but should be exposed in a .Internal
  -- module

rightExtendInject :: Inject p a b -> p c -> Inject p a c
rightExtendInject (InjectRefl PolyRefl) rP = CompactCompose PolyRefl (MonoRefl rP) 1
rightExtendInject (InjectRefl (MonoRefl f)) rP = CompactCompose (MonoRefl f) (MonoRefl rP) 1
rightExtendInject (CompactCompose pa _pb n) rP = CompactCompose pa (MonoRefl rP) (n+1 )

leftExtendExtract :: p a -> Extract p b c -> Extract p a c
leftExtendExtract p (Dual inj) = Dual (rightExtendInject inj p)

jumpDepthInject :: Natural -> p c -> Inject p a b -> Inject p a c
jumpDepthInject plus pc  (InjectRefl PolyRefl)  = CompactCompose PolyRefl (MonoRefl pc) (1 + plus)
jumpDepthInject plus pc  (InjectRefl (MonoRefl pa))  = CompactCompose (MonoRefl pa) (MonoRefl pc) (1 + plus)
jumpDepthInject plus pc (CompactCompose pa _pb n) = CompactCompose pa (MonoRefl pc) (n + plus + 1 )

jumpDepthExtract :: Natural -> Extract p b c -> p a -> Extract p a c
jumpDepthExtract plus (Dual cc) pc = Dual (jumpDepthInject plus pc cc)

instance Semigroupoid (Inject f) where
   --PolyId `o`  PolyId =  PolyId
   (InjectRefl (MonoRefl _p)) `o` (!f) = f
   (InjectRefl (PolyRefl)) `o`  (!f) = f
   (CompactCompose in1 out1 size) `o` (InjectRefl  (PolyRefl)) = CompactCompose  in1 out1 size
   (CompactCompose in1 out1 size) `o` (InjectRefl  (MonoRefl !_p)) = CompactCompose  in1 out1 size
   (CompactCompose _cmiddle2 cout sizeleft)
    `o` (CompactCompose cin _cmiddle1 sizeright) = CompactCompose cin cout (sizeright + sizeleft)
      --- TODO is this case too lazy?

-- extract is the dual of Inject
-- aka Data.Semigroupoid.Dual is nearly the exact same type :)
newtype Extract :: (k -> * ) -> k -> k -> * where
  Dual :: ((Inject f) b a ) -> Extract f a b
-- not sure if this is the right design vs
  -- :: Inject f b a -> Extract f a b  --- (which has more explicit duality and less newtypery)

instance Semigroupoid (Extract f) where
  o = \ (Dual l)  (Dual r) -> Dual  $  r `o` l

data TreeEq :: (k -> * ) -> k -> k -> * where
  TreeInject :: Inject f a b -> TreeEq f a b
  TreeExtract :: Extract f a b -> TreeEq f a b
  TreeRefl :: TreeEq f c c

--- this might limit a,c to being kind (or sort?) * / Type for now, but thats OK ??
treeElimination :: TestEquality f => Inject f a b -> Extract f  b  c->  (TreeEq f a c)
treeElimination (InjectRefl PolyRefl) (Dual  (InjectRefl PolyRefl)) =  TreeRefl
treeElimination (InjectRefl (MonoRefl _p1)) (Dual  (InjectRefl PolyRefl)) =  TreeRefl
treeElimination (InjectRefl PolyRefl) (Dual  (InjectRefl (MonoRefl _p2))) =  TreeRefl
treeElimination (InjectRefl (MonoRefl _p1)) (Dual (InjectRefl(MonoRefl _p2))) =  TreeRefl
treeElimination (CompactCompose fa _fb1 n1) (Dual (CompactCompose fc _fb2 n2)) =
         case (compare n1 n2, max n1 n2 - min n1 n2) of
                        (EQ, _ )-> (unsafeCoerce TreeRefl) :: TreeEq f a c
                          --- if the path is zero length they must be equal!
                          --- AUDIT MEEEE
                        (GT, m )->  TreeInject (CompactCompose fa fc  m)
                        (LT, m ) -> TreeExtract (Dual (CompactCompose fc fa m))
treeElimination   (InjectRefl p@(PolyRefl))
                  d@(Dual (CompactCompose _fc _fb _n)) = treeElimination (CompactCompose p p 0) d
treeElimination   (InjectRefl p@(MonoRefl _))
                  d@(Dual (CompactCompose _fc _fb _n)) = treeElimination (CompactCompose p p 0) d
treeElimination   d@( CompactCompose _fc _fb _n)
                  (Dual (InjectRefl p@(PolyRefl))) = treeElimination d (Dual (CompactCompose p p 0))
treeElimination   d@(CompactCompose _fc _fb _n)
                  (Dual (InjectRefl p@(MonoRefl _))) = treeElimination d (Dual (CompactCompose p p 0))


text:
function vars = variables(ds)

% VARIABLES variables of dataset(s).
% --------------------
% vars = variables(ds)
% --------------------
% Description: returns the variables of dataset(s).
% Input:       {ds} dataset instance(s).
% Output:      {vars} if {ds} contains one instance, {vars} is just the
%                   field 'variables'. Otherwise, it is a cell array, with
%                   each cell containing the 'variables' field of one
%                   dataset instance.

% © Liran Carmel
% Classification: SET/GET functions
% Last revision date: 29-Nov-2004

% parse input
error(nargchk(1,1,nargin));

% substitute values
vars = cell(size(ds));
for ii = 1:numel(ds)
    vars{ii} = ds(ii).variables;
end

% don't make a cell array for a single {ds} instance
if numel(ds) == 1
    vars = vars{1};
end


text:
INCLUDE "constants/animations.asm"
INCLUDE "constants/constants.asm"
INCLUDE "constants/emotes.asm"
INCLUDE "constants/flags.asm"
INCLUDE "constants/maps.asm"
INCLUDE "constants/memory.asm"
INCLUDE "constants/sound.asm"
INCLUDE "constants/text.asm"
INCLUDE "constants/thread2.asm"
INCLUDE "constants/tileset.asm"


text:
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StopGuessing.DataStructures;
using StopGuessing.Models;
using System.Text;
using System.Threading;
using StopGuessing.EncryptionPrimitives;
using StopGuessing.Interfaces;
using StopGuessing.Utilities;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace StopGuessing.Controllers
{
    public interface ILoginAttemptController
    {
        Task<LoginAttempt> PutAsync(LoginAttempt loginAttempt,
            string passwordProvidedByClient = null,
            CancellationToken cancellationToken = default(CancellationToken));
    }

    /// <summary>
    /// This controller serves requests to authenticate users, which are issued via PUT requests.
    /// (See PutAsync).
    /// </summary>
    /// <typeparam name="TUserAccount"></typeparam>
    [Route("api/[controller]")]
    public class LoginAttemptController<TUserAccount> :
        Controller,
        ILoginAttemptController where TUserAccount : IUserAccount
    {
        /// <summary>
        /// Configuration options.
        /// </summary>
        private readonly BlockingAlgorithmOptions _options;
        /// <summary>
        /// A binomial ladder filter used to identify frequently-guessed passwords.
        /// </summary>
        private readonly IBinomialLadderFilter _binomialLadderFilter;
        /// <summary>
        /// An interface for creating clients to the repository in which user's account records are stored.
        /// </summary>
        private readonly IUserAccountRepositoryFactory<TUserAccount> _userAccountRepositoryFactory;
        /// <summary>
        /// An interface for creating controllers that can modify user's account records.
        /// </summary>
        private readonly IUserAccountControllerFactory<TUserAccount> _userAccountControllerFactory;
        /// <summary>
        /// A sketch used to identify when the same username/password pair is submitted, for
        /// usernames that are not valid.  (For usernames that are valid, the user's account
        /// keeps track of recent invalid passwords.)
        /// </summary>
        private readonly AgingMembershipSketch _recentIncorrectPasswords;

        /// <summary>
        /// A cache of records for IP addresses tracked by this controller.
        /// </summary>
        private readonly SelfLoadingCache<IPAddress, IpHistory> _ipHistoryCache;

        /// <summary>
        /// Construct the controller.
        /// </summary>
        /// <param name="userAccountControllerFactory">A factory for creating IUserAccountController interfaces for managing user account records.</param>
        /// <param name="userAccountRepositoryFactory">A factory for creating IAccountRepository interfaces for obtaining user account records.</param>
        /// <param name="binomialLadderFilter">A binomial ladder frequency that the controller should use to track frequently-guessed passwords.</param>
        /// <param name="memoryUsageLimiter">A memory usage limiter that the controller should register into so that when memory is tight,
        /// the controller can do its part to free up cached items it may not need anymore.</param>
        /// <param name="blockingOptions">Configuration options.</param>
        public LoginAttemptController(
            IUserAccountControllerFactory<TUserAccount> userAccountControllerFactory,
            IUserAccountRepositoryFactory<TUserAccount> userAccountRepositoryFactory,
            IBinomialLadderFilter binomialLadderFilter,
            MemoryUsageLimiter memoryUsageLimiter,
            BlockingAlgorithmOptions blockingOptions
            )
        {
            // Copy parameters into the controller.
            _options = blockingOptions;
            _binomialLadderFilter = binomialLadderFilter;
            _userAccountRepositoryFactory = userAccountRepositoryFactory;
            _userAccountControllerFactory = userAccountControllerFactory;

            // Create a membership sketch to track username/password pairs that have failed.
            _recentIncorrectPasswords = new AgingMembershipSketch(blockingOptions.AgingMembershipSketchTables, blockingOptions.AgingMembershipSketchTableSize);

            // Create a cache of records storing information about the behavior of IPs that have issued login attempts.
            _ipHistoryCache = new SelfLoadingCache<IPAddress, IpHistory>(address => new IpHistory(address, _options));

            // When memory is low, the memeory usage limiter should call the ReduceMemoryUsage method of this controller.
            memoryUsageLimiter.OnReduceMemoryUsageEventHandler += ReduceMemoryUsage;
        }

        /// <summary>
        /// When a user attempts to login, a REST PUT will record the login attempt and provide and return the outcome.
        /// </summary>
        /// <param name="id">The unique ID of the login attempt.  Must match loginAttempt.UniqueID.</param>
        /// <param name="loginAttempt">A record of all the details known about the login attempt.</param>
        /// <param name="passwordProvidedByClient">The plaintext password provided by the client trying to login.</param>
        /// <param name="cancellationToken">An optional cancellation token to support asynchrony.</param>
        /// <returns>An ObjectResult that, if the request is successfully processed, encapsulates the LoginAttempt
        /// record as modified by this process.  Successfully returning the LoginAttempt does not mean the request
        /// to login should be granted.  Rather, the login should only succeed if the Outcome field is set to
        /// CredentialsValid.</returns>
        // PUT api/LoginAttempt/clientsIpHistory-address-datetime
        [HttpPut("{id}")]
        public async Task<IActionResult> PutAsync([FromRoute] string id,
            [FromBody] LoginAttempt loginAttempt,
            [FromBody] string passwordProvidedByClient = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (id != loginAttempt.UniqueKey)
            {
                throw new Exception("The id assigned to the login does not match it's unique key.");
            }

            return new ObjectResult(await PutAsync(loginAttempt,
                passwordProvidedByClient,
                cancellationToken: cancellationToken));
        }

        /// <summary>
        /// When a user attempts to login, record the login attempt and provide and return the outcome.
        /// </summary>
        /// <param name="loginAttempt">A record of all the details known about the login attempt.</param>
        /// <param name="passwordProvidedByClient">The plaintext password provided by the client trying to login.</param>
        /// <param name="cancellationToken">An optional cancellation token to support asynchrony.</param>
        /// <returns>The modified loginAttempt with the Outcome field set to indicate whether the
        /// the client should be allowed to login to the account.</returns>
        public async Task<LoginAttempt> PutAsync(
            LoginAttempt loginAttempt,
            string passwordProvidedByClient = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            return await DetermineLoginAttemptOutcomeAsync(
                loginAttempt,
                passwordProvidedByClient,
                cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Ensure that a known-common password is treated as frequent
        /// </summary>
        /// <param name="passwordToTreatAsFrequent">The password to treat as frequent</param>
        /// <param name="numberOfSteps">The number of consecutive occurrences to simulate</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task PrimeCommonPasswordAsync(string passwordToTreatAsFrequent,
            int numberOfSteps,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            for (int i = 0; i < numberOfSteps; i++)
            {
                await _binomialLadderFilter.StepAsync(passwordToTreatAsFrequent, cancellationToken: cancellationToken);
            }
        }

        // DELETE api/LoginAttempt/<key>
        [HttpDelete("{id}")]
        public IActionResult Delete(string id)
        {
            // no-op
            return new NotFoundResult();
        }

        /// <summary>
        /// This analysis will examine the client IP's previous failed attempts to login to this account
        /// to determine if any failed attempts were due to typos.
        /// </summary>
        /// <param name="clientsIpHistory">Records of this client's previous attempts to examine.</param>
        /// <param name="accountController"></param>
        /// <param name="account">The account that the client is currently trying to login to.</param>
        /// <param name="whenUtc"></param>
        /// <param name="correctPassword">The correct password for this account.  (We can only know it because
        /// the client must have provided the correct one this loginAttempt.)</param>
        /// <param name="phase1HashOfCorrectPassword">The phase1 hash of that correct password (which we could
        /// recalculate from the information in the previous parameters, but doing so would be expensive.)</param>
        /// <returns></returns>
        protected void AdjustBlockingScoreForPastTyposTreatedAsFullFailures(
            IpHistory clientsIpHistory,
            IUserAccountController<TUserAccount> accountController,
            TUserAccount account,
            DateTime whenUtc,
            string correctPassword,
            byte[] phase1HashOfCorrectPassword)
        {
            double credit = 0d;

            if (clientsIpHistory == null)
                return;

            LoginAttemptSummaryForTypoAnalysis[] recentPotentialTypos = clientsIpHistory.RecentPotentialTypos.MostRecentFirst.ToArray();
            Encryption.IPrivateKey privateAccountLogKey = null;
            try
            {
                foreach (LoginAttemptSummaryForTypoAnalysis potentialTypo in recentPotentialTypos)
                {
                    bool usernameCorrect = potentialTypo.UsernameOrAccountId == account.UsernameOrAccountId;
                    //bool usernameHadTypo = !usernameCorrect &&
                    //    EditDistance.Calculate(potentialTypo.UsernameOrAccountId, account.UsernameOrAccountId) <=
                    //_options.MaxEditDistanceConsideredATypo;

                    if (usernameCorrect) // || usernameHadTypo
                    {
                        // Get the plaintext password from the previous login attempt
                        string passwordSubmittedInFailedAttempt = null;
                        if (account.GetType().Name == "SimulatedUserAccount")
                        {
                            passwordSubmittedInFailedAttempt = potentialTypo.EncryptedIncorrectPassword.Ciphertext;
                        }
                        else
                        {
                            if (privateAccountLogKey == null)
                            {
                                // Get the EC decryption key, which is stored encrypted with the Phase1 password hash
                                try
                                {
                                    privateAccountLogKey = accountController.DecryptPrivateAccountLogKey(account,
                                        phase1HashOfCorrectPassword);
                                }
                                catch (Exception)
                                {
                                    // There's a problem with the key that prevents us from decrypting it.  We won't be able to do this analysis.
                                    return;
                                }
                            }
                            // Now try to decrypt the incorrect password from the previous attempt and perform the typo analysis
                            try
                            {
                                // Attempt to decrypt the password.
                                passwordSubmittedInFailedAttempt =
                                    potentialTypo.EncryptedIncorrectPassword.Read(privateAccountLogKey);
                            }
                            catch (Exception)
                            {
                                // An exception is likely due to an incorrect key (perhaps outdated).
                                // Since we simply can't do anything with a record we can't Decrypt, we carry on
                                // as if nothing ever happened.  No.  Really.  Nothing to see here.
                            }
                        }

                        if (passwordSubmittedInFailedAttempt != null)
                        {
                            //bool passwordCorrect = passwordSubmittedInFailedAttempt == correctPassword;
                            bool passwordHadTypo = // !passwordCorrect &&
                                EditDistance.Calculate(passwordSubmittedInFailedAttempt, correctPassword) <=
                                _options.MaxEditDistanceConsideredATypo;

                            // Get credit for this nearly-correct attempt to counter penalty
                            if (passwordHadTypo)
                            {
                                credit += potentialTypo.Penalty.GetValue(_options.AccountCreditLimitHalfLife, whenUtc)*
                                          (1d - _options.PenaltyMulitiplierForTypo);
                            }
                        }
                    }

                    // Now that we know whether this past event was a typo or not, we no longer need to keep track
                    // of it (and we should remove it so we don't double credit it).
                    clientsIpHistory.RecentPotentialTypos.Remove(potentialTypo);
                }

                // Remove the amount to be credited from the block score due to the discovery of typos
                clientsIpHistory.CurrentBlockScore.SubtractInPlace(account.CreditHalfLife, credit, whenUtc);
            }
            finally
            {
                privateAccountLogKey?.Dispose();
            }
        }

        /// <returns></returns>
        /// <summary>
        /// Add a LoginAttempt, along the way determining whether that loginAttempt should be allowed
        /// (the user authenticated) or denied.
        /// </summary>
        /// <param name="loginAttempt">The login loginAttempt record to be stored.</param>
        /// <param name="passwordProvidedByClient">The plaintext password provided by the client.</param>
        /// <param name="phase1HashOfProvidedPassword">If the caller has already computed the phase 1 (expensive) hash of the submitted password,
        /// it can supply it via this optional parameter to avoid incurring the cost of having incurring the expense of this calculationg a second time.</param>
        /// <param name="timeout"></param>
        /// <param name="cancellationToken">To allow this async method to be cancelled.</param>
        /// <returns>If the password is correct and the IP not blocked, returns AuthenticationOutcome.CredentialsValid.
        /// Otherwise, it returns a different AuthenticationOutcome.
        /// The client should not be made aware of any information beyond whether the login was allowed or not.</returns>
        public async Task<LoginAttempt> DetermineLoginAttemptOutcomeAsync(
            LoginAttempt loginAttempt,
            string passwordProvidedByClient,
            byte[] phase1HashOfProvidedPassword = null,
            TimeSpan? timeout = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            //
            // In parallel, fetch information we'll need to determine the outcome
            //

            // Get information about the client's IP
            Task<IpHistory> ipHistoryGetTask = _ipHistoryCache.GetAsync(loginAttempt.AddressOfClientInitiatingRequest,
                cancellationToken);

            // Get information about the account the client is trying to login to
            //IStableStoreContext<string, UserAccount> userAccountContext = _userAccountContextFactory.Get();
            IRepository<string, TUserAccount> userAccountRepository = _userAccountRepositoryFactory.Create();
            Task<TUserAccount> userAccountRequestTask = userAccountRepository.LoadAsync(loginAttempt.UsernameOrAccountId, cancellationToken);

            // Get a binomial ladder to estimate if the password is common
            Task<int> passwordsHeightOnBinomialLadderTask =
                _binomialLadderFilter.GetHeightAsync(passwordProvidedByClient, cancellationToken: cancellationToken);

            //
            // Start processing information as it comes in
            //

            // Preform an analysis of the IPs past beavhior to determine if the IP has been performing so many failed guesses
            // that we disallow logins even if it got the right password.  We call this even when the submitted password is
            // correct lest we create a timing indicator (slower responses for correct passwords) that attackers could use
            // to guess passwords even if we'd blocked their IPs.
            IpHistory ip = await ipHistoryGetTask;

            // We'll need the salt from the account record before we can calculate the expensive hash,
            // so await that task first
            TUserAccount account = await userAccountRequestTask;
            if (account != null)
            {
                try
                {
                    IUserAccountController<TUserAccount> userAccountController = _userAccountControllerFactory.Create();
                    //
                    // This is an login attempt for a valid (existent) account.
                    //

                    // Determine whether the client provided a cookie to indicate that it has previously logged
                    // into this account successfully---a very strong indicator that it is a client used by the
                    // legitimate user and not an unknown client performing a guessing attack.
                    loginAttempt.DeviceCookieHadPriorSuccessfulLoginForThisAccount = await
                        userAccountController.HasClientWithThisHashedCookieSuccessfullyLoggedInBeforeAsync(
                            account,
                            loginAttempt.HashOfCookieProvidedByBrowser,
                            cancellationToken);

                    // Test to see if the password is correct by calculating the Phase2Hash and comparing it with the Phase2 hash
                    // in this record.  The expensive (phase1) hash which is used to encrypt the EC public key for this account
                    // (which we use to store the encryptions of incorrect passwords)
                    if (phase1HashOfProvidedPassword == null)
                    {
                        phase1HashOfProvidedPassword =
                            userAccountController.ComputePhase1Hash(account, passwordProvidedByClient);
                    }

                    // Since we can't store the phase1 hash (it can decrypt that EC key) we instead store a simple (SHA256)
                    // hash of the phase1 hash, which we call the phase 2 hash, and use that to compare the provided password
                    // with the correct password.
                    string phase2HashOfProvidedPassword =
                            userAccountController.ComputePhase2HashFromPhase1Hash(account, phase1HashOfProvidedPassword);

                    // To determine if the password is correct, compare the phase2 has we just generated (phase2HashOfProvidedPassword)
                    // with the one generated from the correct password when the user chose their password (account.PasswordHashPhase2).
                    bool isSubmittedPasswordCorrect = phase2HashOfProvidedPassword == account.PasswordHashPhase2;

                    // Get the popularity of the password provided by the client among incorrect passwords submitted in the past,
                    // as we are most concerned about frequently-guessed passwords.
                    loginAttempt.PasswordsHeightOnBinomialLadder = await passwordsHeightOnBinomialLadderTask;

                    if (isSubmittedPasswordCorrect)
                    {
                        // The password is corerct.

                        // Determine if any of the outcomes for login attempts from the client IP for this request were the result of typos,
                        // as this might impact our decision about whether or not to block this client IP in response to its past behaviors.
                        AdjustBlockingScoreForPastTyposTreatedAsFullFailures(
                            ip, userAccountController, account, loginAttempt.TimeOfAttemptUtc, passwordProvidedByClient,
                            phase1HashOfProvidedPassword);

                        // We'll get the blocking threshold, blocking condition, and block if the condition exceeds the threshold.
                        double blockingThreshold = _options.BlockThresholdPopularPassword_T_base*
                                                   _options.PopularityBasedThresholdMultiplier_T_multiplier(
                                                       loginAttempt);
                        double blockScore = ip.CurrentBlockScore.GetValue(_options.BlockScoreHalfLife,
                            loginAttempt.TimeOfAttemptUtc);

                        // If the client provided a cookie proving a past successful login, we'll ignore the block condition
                        if (loginAttempt.DeviceCookieHadPriorSuccessfulLoginForThisAccount)
                            blockScore *= _options.MultiplierIfClientCookieIndicatesPriorSuccessfulLogin_Kappa;

                        if (blockScore > blockingThreshold)
                        {
                            // While this login attempt had valid credentials, the circumstances
                            // are so suspicious that we should block the login and pretend the
                            // credentials were invalid
                            loginAttempt.Outcome = AuthenticationOutcome.CredentialsValidButBlocked;
                        }
                        else
                        {
                            // This login attempt has valid credentials and no reason to block, so the
                            // client will be authenticated.
                            loginAttempt.Outcome = AuthenticationOutcome.CredentialsValid;
                            userAccountController.RecordHashOfDeviceCookieUsedDuringSuccessfulLoginBackground(
                                account,
                                loginAttempt.HashOfCookieProvidedByBrowser);

                            // Use this login attempt to offset harm caused by prior login failures
                            if (
                                ip.CurrentBlockScore.GetValue(_options.AccountCreditLimitHalfLife,
                                    loginAttempt.TimeOfAttemptUtc) > 0)
                            {
                                // There is a non-zero blocking score that might be counteracted by a credit
                                TaskHelper.RunInBackground(Task.Run( async () =>
                                {
                                    double credit = await userAccountController.TryGetCreditAsync(
                                        account,
                                        _options.RewardForCorrectPasswordPerAccount_Sigma,
                                        loginAttempt.TimeOfAttemptUtc, cancellationToken);
                                    ip.CurrentBlockScore.SubtractInPlace(_options.AccountCreditLimitHalfLife, credit,
                                        loginAttempt.TimeOfAttemptUtc);
                                }, cancellationToken));
                            }
                        }

                    }
                    else
                    {
                        //
                        // The password was invalid.  Do bookkeeping of information about this failure so that we can
                        // block the origin IP if it appears to be engaged in guessing and so that we can track
                        // frequently guessed passwords.

                        // We'll not only store the (phase 2) hash of the incorrect password, but we'll also store
                        // the incorrect passwords itself, encrypted with the EcPublicAccountLogKey.
                        // (The decryption key to get the incorrect password plaintext back is encrypted with the
                        //  correct password, so you can't get to the plaintext of the incorrect password if you
                        //  don't already know the correct password.)
                        loginAttempt.Phase2HashOfIncorrectPassword = phase2HashOfProvidedPassword;
                        if (account.GetType().Name == "SimulatedUserAccount")
                        {
                            loginAttempt.EncryptedIncorrectPassword.Ciphertext = passwordProvidedByClient;
                        }
                        else
                        {
                            loginAttempt.EncryptedIncorrectPassword.Write(passwordProvidedByClient,
                                account.EcPublicAccountLogKey);
                        }
                        // Next, if it's possible to declare more about this outcome than simply that the
                        // user provided the incorrect password, let's do so.
                        // Since users who are unsure of their passwords may enter the same username/password twice, but attackers
                        // don't learn anything from doing so, we'll want to account for these repeats differently (and penalize them less).
                        // We actually have two data structures for catching this: A large sketch of clientsIpHistory/account/password triples and a
                        // tiny LRU cache of recent failed passwords for this account.  We'll check both.
                        if (await userAccountController.AddIncorrectPhaseTwoHashAsync(account, phase2HashOfProvidedPassword, cancellationToken: cancellationToken))
                        {
                            // The same incorrect password was recently used for this account, indicate this so that we
                            // do not penalize the IP further (as attackers don't gain anything from guessing the wrong password again).
                            loginAttempt.Outcome = AuthenticationOutcome.CredentialsInvalidRepeatedIncorrectPassword;
                        }
                        else
                        {
                            // This is the first time we've (at least recently) seen this incorrect password attempted for the account,
                            loginAttempt.Outcome = AuthenticationOutcome.CredentialsInvalidIncorrectPassword;

                            // Penalize the IP for the invalid password
                            double invalidPasswordPenalty = _options.PenaltyForInvalidPassword_Beta*
                                                            _options.PopularityBasedPenaltyMultiplier_phi(
                                                                loginAttempt);
                            ip.CurrentBlockScore.AddInPlace(_options.AccountCreditLimitHalfLife,
                                invalidPasswordPenalty,
                                loginAttempt.TimeOfAttemptUtc);
                            // Record the penalty so that it can be reduced if this incorrect password is later discovered to be a typo.
                            ip.RecentPotentialTypos.Add(new LoginAttemptSummaryForTypoAnalysis()
                            {
                                EncryptedIncorrectPassword = loginAttempt.EncryptedIncorrectPassword,
                                Penalty = new DecayingDouble(invalidPasswordPenalty, loginAttempt.TimeOfAttemptUtc),
                                UsernameOrAccountId = loginAttempt.UsernameOrAccountId
                            });
                        }

                    }
                }
                finally
                {
                    // Save changes to the user account record in the background (so that we don't hold up returning the result)
                    TaskHelper.RunInBackground(userAccountRepository.SaveChangesAsync(cancellationToken));
                }
            }
            else
            {
                // account == null
                // This is an login attempt for an INvalid (NONexistent) account.
                //
                if (phase1HashOfProvidedPassword == null)
                {
                    phase1HashOfProvidedPassword =
                        ExpensiveHashFunctionFactory.Get(_options.DefaultExpensiveHashingFunction)(
                            passwordProvidedByClient,
                            ManagedSHA256.Hash(Encoding.UTF8.GetBytes(loginAttempt.UsernameOrAccountId)),
                            _options.ExpensiveHashingFunctionIterations);
                }

                // Get the popularity of the password provided by the client among incorrect passwords submitted in the past,
                // as we are most concerned about frequently-guessed passwords.
                loginAttempt.PasswordsHeightOnBinomialLadder = await passwordsHeightOnBinomialLadderTask;

                // This appears to be an loginAttempt to login to a non-existent account, and so all we need to do is
                // mark it as such.  However, since it's possible that users will forget their account names and
                // repeatedly loginAttempt to login to a nonexistent account, we'll want to track whether we've seen
                // this account/password double before and note in the outcome if it's a repeat so that.
                // the IP need not be penalized for issuign a query that isn't getting it any information it
                // didn't already have.

                if (_recentIncorrectPasswords.AddMember(Convert.ToBase64String(phase1HashOfProvidedPassword)))
                {
                    // Don't penalize the incorrect <invalid account/password> pair if we've seen the same
                    // pair recently
                    loginAttempt.Outcome = AuthenticationOutcome.CredentialsInvalidRepeatedNoSuchAccount;
                }
                else
                {
                    // Penalize the IP for a login attempt with an invalid account
                    loginAttempt.Outcome = AuthenticationOutcome.CredentialsInvalidNoSuchAccount;
                    double invalidAccontPenalty = _options.PenaltyForInvalidAccount_Alpha*
                                                  _options.PopularityBasedPenaltyMultiplier_phi(loginAttempt);
                    ip.CurrentBlockScore.AddInPlace(_options.BlockScoreHalfLife, invalidAccontPenalty,
                        loginAttempt.TimeOfAttemptUtc);
                }
            }

            if (loginAttempt.Outcome == AuthenticationOutcome.CredentialsInvalidNoSuchAccount ||
                loginAttempt.Outcome == AuthenticationOutcome.CredentialsInvalidIncorrectPassword)
            {
                // Record the invalid password into the binomial ladder sketch that tracks freqeunt-incorrect passwords
                // Since we don't need to know the result, we'll run it in the background (so that we don't hold up returning the result)
                TaskHelper.RunInBackground(_binomialLadderFilter.StepAsync(passwordProvidedByClient, cancellationToken: cancellationToken));
            }

            return loginAttempt;
        }

        /// <summary>
        /// When memory runs low, call this function to remove a fraction of the space used by non-fixed-size data structures
        /// (In this case, it is the history of information about IP addresses)
        /// </summary>
        public void ReduceMemoryUsage(object sender, MemoryUsageLimiter.ReduceMemoryUsageEventParameters parameters)
        {
            _ipHistoryCache.RecoverSpace(parameters.FractionOfMemoryToTryToRemove);
        }
    }
}


text:
package com.amazonaws.services.keyspaces.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.keyspaces.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * ClusteringKey JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClusteringKeyJsonUnmarshaller implements Unmarshaller<ClusteringKey, JsonUnmarshallerContext> {

    public ClusteringKey unmarshall(JsonUnmarshallerContext context) throws Exception {
        ClusteringKey clusteringKey = new ClusteringKey();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("name", targetDepth)) {
                    context.nextToken();
                    clusteringKey.setName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("orderBy", targetDepth)) {
                    context.nextToken();
                    clusteringKey.setOrderBy(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return clusteringKey;
    }

    private static ClusteringKeyJsonUnmarshaller instance;

    public static ClusteringKeyJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new ClusteringKeyJsonUnmarshaller();
        return instance;
    }
}