text:
var NamedFunction, WeakMap, assertObject, call;

require("lotus-require");

NamedFunction = require("NamedFunction");

WeakMap = module.exports = NamedFunction("WeakMap", function() {
  if (!(this instanceof WeakMap)) {
    return new WeakMap;
  }
  this.name = WeakMap.unique();
  return this;
});

WeakMap.prototype.set = function(object, key, newValue) {
  var data, entry, isDefined, ref;
  assertObject(object);
  entry = (ref = object[this.name]) != null ? ref : [];
  isDefined = entry[0] === object;
  if (arguments.hasOwnProperty(2)) {
    data = entry[1];
    if (!isDefined || (data == null)) {
      data = entry[1] = {};
    }
    WeakMap.cake(data, key, {
      set: newValue
    });
  } else {
    newValue = key;
    entry[1] = newValue;
  }
  if (!isDefined) {
    entry[0] = object;
    Object.defineProperty(object, this.name, {
      value: entry,
      writable: true,
      configurable: true
    });
  }
  return newValue;
};

WeakMap.prototype.get = function(object, key) {
  var data, entry;
  assertObject(object);
  entry = object[this.name];
  if ((entry == null) || entry[0] !== object) {
    return;
  }
  data = entry[1];
  if (!arguments.hasOwnProperty(1)) {
    return data;
  }
  if (data instanceof Object) {
    return WeakMap.cake(data, key, {
      get: true
    });
  }
};

WeakMap.prototype.remove = function(object, key) {
  var data, entry;
  assertObject(object);
  entry = object[this.name];
  if ((entry == null) || entry[0] !== object) {
    return false;
  }
  if (arguments.hasOwnProperty(1)) {
    data = entry[1];
    if (!(data instanceof Object)) {
      return false;
    }
    return WeakMap.cake(data, key, {
      remove: true
    });
  }
  entry[0] = entry[1] = void 0;
  return true;
};

WeakMap.prototype.has = function(object, key) {
  var data, entry;
  assertObject(object);
  entry = object[this.name];
  if ((entry == null) || entry[0] !== object) {
    return false;
  }
  if (!arguments.hasOwnProperty(1)) {
    return true;
  }
  data = entry[1];
  if (!(data instanceof Object)) {
    return false;
  }
  return WeakMap.cake(data, key, {
    has: true
  });
};

call = function(fn) {
  return fn();
};

assertObject = function(value) {
  if (value) {
    if (value.__proto__ === void 0) {
      return;
    }
    if (value instanceof Object) {
      return;
    }
  }
  throw TypeError("Expected a kind of Object!");
};

Object.defineProperty(WeakMap, "unique", {
  writable: true,
  value: call(function() {
    var uniqueIndex;
    uniqueIndex = Date.now() % 1e9;
    return function() {
      return "__st" + (Math.random() * 1e9 >>> 0) + (uniqueIndex++ + "__");
    };
  })
});

Object.defineProperty(WeakMap, "cake", {
  writable: true,
  value: call(function() {
    var actions, getAction;
    actions = ["get", "set", "has", "remove"];
    getAction = function(actions, options) {
      var action, i, len;
      for (i = 0, len = actions.length; i < len; i++) {
        action = actions[i];
        if (options.hasOwnProperty(action)) {
          return action;
        }
      }
      throw Error("Missing action. Try: " + actions.join(", "));
    };
    return function(object, key, options) {
      var action, crumb, crumbs, i, len, trail;
      if (typeof key !== "string") {
        throw TypeError("'key' must be a String.");
      }
      if (!(object instanceof Object)) {
        throw TypeError("Cannot set '" + key + "' on non-object.");
      }
      action = getAction(actions, options);
      crumbs = key.split(".");
      key = crumbs.pop();
      for (i = 0, len = crumbs.length; i < len; i++) {
        crumb = crumbs[i];
        trail = object[crumb];
        if (!(trail instanceof Object)) {
          switch (action) {
            case "get":
              return;
            case "set":
              trail = object[crumb] = {};
              break;
            case "has":
              return false;
            case "remove":
              return false;
          }
        }
        object = trail;
      }
      switch (action) {
        case "get":
          return object[key];
        case "set":
          return object[key] = options.set;
        case "has":
          return object.hasOwnProperty(key);
        case "remove":
          return delete object[key];
      }
    };
  })
});


text:
class AddUserIdToExercises < ActiveRecord::Migration
  def change
    add_column :exercises, :user_id, :integer, null: false,
      default: User.find_by(email: 'default_user@test.com')
  end
end

redpajama_set_name: RedPajamaGithub


text:
module RailsBestPractices
  module Core
    # Klass container.
    class Klasses < Array
      # If include the class.
      #
      # @param [String] class name
      # @return [Boolean] include or not
      def include?(class_name)
        find { |klass| klass.to_s == class_name }
      end
    end

    # Class info includes clas name, extend class name and module names.
    class Klass
      attr_reader :class_name, :extend_class_name

      def initialize(class_name, extend_class_name, modules)
        @class_name = class_name
        @extend_class_name = extend_class_name
        @modules = modules.dup
      end

      def to_s
        if @modules.empty?
          @class_name
        else
          @modules.map { |modu| "#{modu}::" }.join("") + @class_name
        end
      end
    end
  end
end


text:
import pytest
from run_demos import run_demo

def pytest_addoption(parser):
    parser.addoption('-D', '--run-demos', action='store_true')

def pytest_collect_file(path, parent):
    if parent.config.option.run_demos:
        if path.fnmatch('demo_*.py'):
            return DemoFile.from_parent(parent, fspath=path)

class DemoFile(pytest.File):

    def collect(self):
        name = self.fspath.basename[:-len('.py')]
        yield DemoItem.from_parent(self, name=name, fspath=self.fspath)

class DemoItem(pytest.Item):

    def __init__(self, name, parent, fspath):
        super().__init__(name, parent)
        self.path = fspath

    def runtest(self):
        run_demo(self.path.strpath)


text:
package database

type (
	// FileElement contains information about file available on Curse server.
	FileElement struct {
		ID, PkgID       int    // File ID, Package ID
		Name, MCVersion string // File name, Minecraft version
	}
	// FileList interface supplies a method of getting file information
	FileList interface {
		Get(fid int) *FileElement
	}
	filelist map[int]FileElement
)

func (fl *filelist) Get(fid int) *FileElement {
	if el, ok := (*fl)[fid]; ok {
		return &el
	}
	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TexasHoldEm.Core
{
    public class TexasHandAsserter
    {
        public string Name { get; set; }
        protected int NumberOfCardsNeeded { get; set; }
        protected Stack<Card> startStack { get; set; } = new Stack<Card>();
        protected Queue<Card> finalRestQueue { get; set; } = new Queue<Card>();
        public Queue<Card> tempRestQueue { get; set; } = new Queue<Card>();
        protected List<Card> OutputCards { get; set; }
        protected Queue<Card> SavedPairs { get; set; } = new Queue<Card>();

        public TexasHandAsserter(string name, int numberOfCardsNeeded)
        {
            this.Name = name;
            this.NumberOfCardsNeeded = numberOfCardsNeeded;
        }

        public virtual List<Card> ReturnBestHand(List<Card> incomingCards)
        {
            finalRestQueue.Clear();
            startStack.Clear();
            SavedPairs.Clear();
            incomingCards = incomingCards.OrderBy(card => card.Number).ToList();

            while (incomingCards.Count >= NumberOfCardsNeeded)

            {
                tempRestQueue.Clear();
                foreach (Card card in incomingCards)
                {
                    startStack.Push(card);
                }

                Stack<Card> comparingStack = new Stack<Card>(incomingCards.Count);
                //Initialize comparison Stack
                comparingStack.Push(startStack.Pop());
                while (startStack.Count > 0)
                {
                    Card previousCard = comparingStack.Peek();
                    comparingStack.Push(startStack.Pop());
                    ///----------------------------------------------------------------------
                    ///------------------------The Core Comparison---------------------------
                    CheckForMatch(comparingStack, previousCard, incomingCards);
                    ///----------------------------------------------------------------------
                    ///----------------------------------------------------------------------
                }

                if (comparingStack.Count == NumberOfCardsNeeded)
                {
                    OutputCards = comparingStack.Reverse().ToList();
                    FillOutHand(5);
                    return OutputCards;
                }

                Card removedCard = incomingCards.Last();
                incomingCards.RemoveAt(incomingCards.Count - 1); //Popping the largest number card

                if (removedCard.Number == 14)
                {
                    incomingCards.Insert(0, removedCard);
                    finalRestQueue.Enqueue(removedCard);
                }
                else
                {
                    finalRestQueue.Enqueue(removedCard);
                }

            }
            return new List<Card>();
        }
        /// <summary>
        /// Filling out the hand to a 5 card Hand.
        /// First all cards in tempRestQueue are enQueued to the finalRestQueue.
        /// The cards and added to OutputCards from finalRestQueue.
        /// </summary>
        protected virtual void FillOutHand(int numberOfCardsForFullHand)
        {

            while (tempRestQueue.Count > 0)
            {
                finalRestQueue.Enqueue(tempRestQueue.Dequeue());
            }

            int restCardsNeeded = numberOfCardsForFullHand - this.NumberOfCardsNeeded;
            for (int i = 0; i < restCardsNeeded; i++)
            {
                OutputCards.Add(finalRestQueue.Dequeue());
            }
        }
        /// <summary>
        /// Standard for pair, threes, fours, Overridden by straight, straight flush
        /// </summary>
        /// <param name="comparingStack"></param>
        /// <param name="previousCard"></param>
        protected virtual void CheckForMatch(Stack<Card> comparingStack, Card previousCard, List<Card> incomingCards)
        {
            if ((comparingStack.Peek().Number == previousCard.Number) && comparingStack.Count <= NumberOfCardsNeeded)
            {
                //AssertForTwoPairs(comparingStack, incomingCards);
            }
            else
            {
                tempRestQueue.Enqueue(comparingStack.Pop());
            }
        }

        private void AssertForTwoPairs(Stack<Card> comparingStack, List<Card> incomingCards)
        {
            if (this.Name == "Two Pairs" && comparingStack.Count == 2)
            {
                SavePairs(comparingStack);
            }
            //Remove saved pair from incoming cards. Otherwise Aces will be added again, and one pair of aces comes back again when Aces count as number=1.
            foreach (Card card in SavedPairs)
            {
                incomingCards.RemoveAll(x => x.Number == card.Number && x.Colour == card.Colour);
            }
        }

        private void SavePairs(Stack<Card> comparingStack)
        {
            while (comparingStack.Count > 0)
            {
                SavedPairs.Enqueue(comparingStack.Pop());
            }

            if (SavedPairs.Count == 4)
            {
                foreach (Card cardInTwoPairs in SavedPairs)
                {
                    comparingStack.Push(cardInTwoPairs);
                }
            }
            else
            {
                comparingStack.Push(startStack.Pop());
            }
        }
    }
}


text:
Instrument Repair Request

        <form class="form-horizontal" data-ng-submit="sendEmail()" novalidate>
            <fieldset>

                    <select name="mydropdown" data-ng-model="formdata.instrument" id="primary" class="form-control" placeholder="Instrument" required>
                            <option ng-repeat="instruments in instruments" value="{{instruments}}" placeholder="Instrument">{{instruments}}</option>
                    </select>

                    <input type="text" data-ng-model="formdata.ID" id="instrumentID" class="form-control" placeholder="Instrument ID" required>

                    <input type="text" data-ng-model="formdata.description" id="description" class="form-control" placeholder="Description of the Problem" required>

                    <input id = "submit" type="submit" class="btn btn-lg btn-info">

            </fieldset>
        </form>


text:
@interface RegistrationViewController : UITableViewController <UITextFieldDelegate>

- (IBAction)cancelRegistration:(id)sender;
- (IBAction)signUp:(id)sender;

@end


text: Basic setup for Proof-of-concept experiments


text:
package org.nd4j.linalg.api.ops.impl.transforms.custom;

import lombok.val;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.common.base.Preconditions;
import org.nd4j.imports.NoOpNameFoundException;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.BaseDynamicTransformOp;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.nd4j.linalg.ops.transforms.Transforms;

public class ATan2 extends BaseDynamicTransformOp {

    public ATan2(SameDiff sameDiff, SDVariable y, SDVariable x) {
        super(sameDiff, new SDVariable[] {y, x} ,false);
    }

    /**
     * Note that the order of x and y match {@link Math#atan2(double, double)},
     * and are reversed when compared to OldATan2.
     * See {@link Transforms#atan2(INDArray, INDArray)}
     */
    public ATan2(INDArray x, INDArray y) {
        this(x,y,null);
    }

    /**
     * Note that the order of x and y match {@link Math#atan2(double, double)},
     * and are reversed when compared to OldATan2.
     * See {@link Transforms#atan2(INDArray, INDArray)}
     */
    public ATan2(INDArray x, INDArray y, INDArray z) {
        super(new INDArray[]{x, y}, wrapOrNull(z));
    }

    public ATan2() {}

    @Override
    public String opName() {
        return "tf_atan2";
    }

    @Override
    public String onnxName() {
        throw new NoOpNameFoundException("No onnx op opName found for " +  opName());
    }

    @Override
    public String tensorflowName() {
        return "Atan2";
    }

    @Override
    public List<SDVariable> doDiff(List<SDVariable> i_v) {
        //Let z=atan2(r), with r=y/x
        //dz/dr = 1/(r^2+1), dr/dy = 1/x, dr/dx = -y/x^2
        SDVariable y = larg();
        SDVariable x = rarg();

        val xGrad = sameDiff.math.neg(y.div(x.pow(2).add(y.pow(2)))).mul(i_v.get(0));
        val yGrad = x.div(x.pow(2).add(y.pow(2))).mul(i_v.get(0));

        return Arrays.asList(yGrad, xGrad);
    }

    @Override
    public List<DataType> calculateOutputDataTypes(List<DataType> dataTypes){
        Preconditions.checkState(dataTypes != null && dataTypes.size() == 2, "Expected exactly 2 input datatypes for %s, got %s", getClass(), dataTypes);
        Preconditions.checkState(dataTypes.get(0) == dataTypes.get(1), "Input datatypes must be same type: got %s", dataTypes);
        return Collections.singletonList(dataTypes.get(0));
    }
}


text:
This structure holds the information on a single connection

**Fields**

- char \*address | the address of the connection
- int fd | the file descriptor
-  CBUS\_sub \*subs | the signals the client subscribed to.
- char \*path | the path of the cbus connection

### CBUS\_sub
This structure holds information on a single signal subscription of a
connection

- char \*sender\_name | which sender we want to listen for
- char \*signal\_name | which signal name we want to listen for

### CBUS\_msg

- uint32\_t length  | the length of the message
- uint32\_t type | the type of the message
- uint32\_t serial | the serial of the message, a random number connecting calls and replies
- char \*token | the access token
- char \*from | the callers/emitters name
- char \*to | the receiver's name
- char \*fn\_name | the name of the emitted signal or called function
- char \*arg\_str | string describing the arguments
-  CBUS\_arg \*args | the arguments
- char \*msg | the message as is
- char \*errstr | shorthand to get the error string when the message is an error
- int err | shorthand for the error number

The arg\_str consists of characters which each describe the type of one argument

- "s" a NULL-terminated string
- "i" an integer
- "d" a double precision floating point

For example "dis" would describe 3 arguments, first being a double,
second being a integer and the last being a stirng

Refer to the protocol definition about messages for more information on this
data structure

### CBUS\_arg

- int int\_value | the value, if it is an int;
- double double\_value | the value, if it is a double;
- char \*str\_value | the value if it is a string;
- int type | the type of the argument

You may only access the \*\_value which matches the data type

# The API

## Helpers

### int fn\_call\_matches( CBUS\_msg \*msg, char \*to, char \*fn\_name, char \*args);
### int fn\_return\_matches( CBUS\_msg \*msg, char \*from, char \*fn\_name, char \*args);
### int signal\_matches( CBUS\_msg \*msg, char \*from, char \*sig\_name, char \*args);

Checks wether msg matches our definition
if an argument is "", cbus will not check it.

### void cbus\_print\_msg( CBUS\_msg \*msg)

Print a  messages

**Arguments**
-  CBUS\_msg \*msg | the message that will be printed

### char \*cbus\_errstr(int err)
Returns a human-readable description of an error number

## Starting and stopping the connection

### CBUS\_conn \*cbus\_connect(char \*address, int \*err)

**Arguments**
- char \*address | the base directory of the CBUS instance
- int \*err |  pointer to an integer filled with an error code

**Returns**

A pointer to a  CBUS\_conn representing the connection, or
NULL on failure

**Errors**
- CBUS\_ERR\_CONNECTION | connecting to the daemon failed

### void cbus\_disconnect( CBUS\_conn \*conn);

Disconnects the connection "conn" and frees the corresponding structure

## Receiving messages

### CBUS\_msg \*cbus\_read( CBUS\_conn \*conn, int \*err, int flags);

**Arguments**
-  CBUS\_conn \*conn | the connection that will be read
- int \*err | pointer to an integer filled with an error code
- int flags | should be always 0 (for future additions)

**Returns**

The message read
**Errors**

- CBUS\_ERR\_CONNECTION | the connection failed

## Calling functions

### int cbus\_call( CBUS\_conn \*conn, char \*address, char \*fn\_name,char \*args, ...)

Calls a function

**Arguments**

**Returns**
The positive serial of the sent message, or a negative error code on error

**Errors**

- CBUS\_ERR\_NO\_AUTH | the application lacks the rights to call this function
- CBUS\_ERR\_PARSE | the construction of the message failed
- CBUS\_ERR\_CONNECTIONNECTION | the connection had an error
- CBUS\_ERR\_DISCONNECT | we were disconnected

### CBUS\_msg \*cbus\_response( CBUS\_conn \*conn, int \*err, char \*address, char \*fn\_name, char \*args, ...);

Calls a function and waits for the return

**Arguments**
-  CBUS\_conn \*conn | Connection on which the function call is sent
- int \*err | A pointer to an integer which is to be filled with an error code
- char \*address | The address of the call
- char \*fn\_name | The remote function to  be called
- char \*args | A string describing the arguments
- ... | the arguments

**Returns**

The matching function return, function error or NULL, in which case
err will be set

**Errors**

- CBUS\_ERR\_NO\_AUTH | the application lacks the rights to call this function
- CBUS\_ERR\_PARSE | the construction of the message failed
- CBUS\_ERR\_CONNECTION | the connection had an error
- CBUS\_ERR\_DISCONNECT | we were disconnected

## Answering function calls

### int cbus\_answer( CBUS\_conn \*conn,  CBUS\_msg \*msg, char \*args, ...)

Answers a function call

**Arguments**
-  CBUS\_conn \*conn | Connection on which the function call is sent
-  CBUS\_msg \*msg | The function call to be answered
- char \*args | the structure of the arguments
- ... | the arguments

**Returns**

0 if everything went well, an error code when not

**Errors**

- CBUS\_ERR\_PARSE | Construction of the answer message failed

## Subscribing to and sending signals

### int cbus\_subscribe( CBUS\_conn \*conn, char \*sender, char \*sig\_name)

Subscribes to a signal

**Arguments**
-  CBUS\_conn \*conn | Connection on which the subscribe request is sent
- char \*sender | the sender we are listening for
- char \*sig\_name | the signal name we are listening for

**Returns**

0 if everything went well, an error code when not

**Errors**
- CBUS\_ERR\_NO\_AUTH | the application lacks the rights to subscribe
- CBUS\_ERR\_CONNECTION | the connection had an error
- CBUS\_ERR\_DISCONNECT | we were disconnected

### int cbus\_emit( CBUS\_conn \*conn, char \*sig\_name, char \*args, ...)

**Arguments**
-  CBUS\_conn \*conn | Connection on which the signal is sent
- char \*sig\_name | the name of the signal we want to send
- char \*args | the ure of the arguments
- ... | the arguments

**Returns**

0 if everything went well, an error code when not

**Errors**
- CBUS\_ERR\_NO\_AUTH | the application lacks rights to send this signal
- CBUS\_ERR\_PARSE | couldn't construct the signal
## Functions for interacting with the daemon

### int cbus\_request\_name( CBUS\_conn \*conn, char \*name)

Requests a (new) name

**Arguments**
-  CBUS\_conn \*conn | Connection which we want to be (re)named
- char \*name | the name we are demanding

**Returns**

0 if everything went well, an error code when not

**Errors**
- CBUS\_ERR\_NO\_AUTH | the application lacks the rights to get a name
- CBUS\_ERR\_PARSE | the construction of the message failed
- CBUS\_ERR\_CONNECTION | the connection had an error
- CBUS\_ERR\_DISCONNECT | we were disconnected
- CBUS\_ERR\_CONFLICT | this name conflicts with another

# Enumerations
## CBUS\_msg\_type
the message types:

- CBUS\_TYPE\_FN\_CALL
- CBUS\_TYPE\_FN\_ERR
- CBUS\_TYPE\_FN\_RETURN
- CBUS\_TYPE\_SIGNAL


text:
import React from "react";
import { Map } from "immutable";
import ArrowIcon from "../../../img/svg-icons/arrow-icon.svg";

import css from "../../../css/portal-dashboard/overlay-class-response.less";

interface IProps {
  currentQuestion?: Map<string, any>;
}
interface IState {
  hideResponseArea: boolean;
}

export class ClassResponse extends React.PureComponent<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      hideResponseArea: false
    };
  }
  render() {
    const chevronClass = this.state.hideResponseArea ? `${css.arrow} ${css.hideResponseArea}`:`${css.arrow}`;
    const responseAreaClass = this.state.hideResponseArea ? `${css.responseArea}  ${css.hidden}` : `${css.responseArea}`;

    return (

Class Response

            <ArrowIcon className={chevronClass} />

          This is where aggregate info of class responses will go

    );
  }

  private handleChevronClick = () => {
    this.setState({
      hideResponseArea: !this.state.hideResponseArea
    });
  }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.spi.type;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Map;

import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

public class TestTypeSignature
{
    @Test
    public void testBindParameters()
            throws Exception
    {
        Map<String, Type> boundParameters = ImmutableMap.of("T1", DoubleType.DOUBLE, "T2", BigintType.BIGINT);

        assertBindSignature("bigint", boundParameters, "bigint");
        assertBindSignature("T1", boundParameters, "double");
        assertBindSignature("T2", boundParameters, "bigint");
        assertBindSignature("array(T1)", boundParameters, "array(double)");
        assertBindSignature("array<T1>", boundParameters, "array(double)");
        assertBindSignature("map(T1,T2)", boundParameters, "map(double,bigint)");
        assertBindSignature("map<T1,T2>", boundParameters, "map(double,bigint)");
        assertBindSignature("row<T1,T2>('a','b')", boundParameters, "row<double,bigint>('a','b')");
        assertBindSignature("bla(T1,42,T2)", boundParameters, "bla(double,42,bigint)");

        assertBindSignatureFails("T1(bigint)", boundParameters, "Unbounded parameters can not have parameters");
    }

    private void assertBindSignatureFails(String typeName, Map<String, Type> boundParameters, String reason)
    {
        try {
            parseTypeSignature(typeName).bindParameters(boundParameters);
            fail(reason);
        }
        catch (RuntimeException e) {
            // Expected
        }
    }

    private void assertBindSignature(String typeName, Map<String, Type> boundParameters, String expectedTypeName)
    {
        assertEquals(parseTypeSignature(typeName).bindParameters(boundParameters).toString(), expectedTypeName);
    }

    @Test
    public void parseRowSignature()
            throws Exception
    {
        assertRowSignature(
                "row<bigint,varchar>('a','b')",
                "row",
                ImmutableList.of("a bigint", "b varchar"));
        assertRowSignature(
                "ROW<bigint,varchar>('a','b')",
                "ROW",
                ImmutableList.of("a bigint", "b varchar"),
                "row<bigint,varchar>('a','b')");
        assertRowSignature(
                "row<bigint,array(bigint),row<bigint>('a')>('a','b','c')",
                "row",
                ImmutableList.of("a bigint", "b array(bigint)", "c row<bigint>('a')"));
        assertRowSignature(
                "row<varchar(10),row<bigint>('a')>('a','b')",
                "row",
                ImmutableList.of("a varchar(10)", "b row<bigint>('a')"));
        assertRowSignature(
                "array(row<bigint,double>('col0','col1'))",
                "array",
                ImmutableList.of("row<bigint,double>('col0','col1')"));
        assertRowSignature(
                "row<array(row<bigint,double>('col0','col1'))>('col0')",
                "row",
                ImmutableList.of("col0 array(row<bigint,double>('col0','col1'))"));
    }

    @Test
    public void parseSignature()
            throws Exception
    {
        assertSignature("bigint", "bigint", ImmutableList.<String>of());
        assertSignature("boolean", "boolean", ImmutableList.<String>of());
        assertSignature("varchar", "varchar", ImmutableList.<String>of());

        assertSignature("array(bigint)", "array", ImmutableList.of("bigint"));
        assertSignature("array(array(bigint))", "array", ImmutableList.of("array(bigint)"));
        assertSignature(
                "array(timestamp with time zone)",
                "array",
                ImmutableList.of("timestamp with time zone"));

        assertSignature(
                "map(bigint,bigint)",
                "map",
                ImmutableList.of("bigint", "bigint"));
        assertSignature(
                "map(bigint,array(bigint))",
                "map", ImmutableList.of("bigint", "array(bigint)"));
        assertSignature(
                "map(bigint,map(bigint,map(varchar,bigint)))",
                "map",
                ImmutableList.of("bigint", "map(bigint,map(varchar,bigint))"));

        assertSignatureFail("blah()");
        assertSignatureFail("array()");
        assertSignatureFail("map()");

        // ensure this is not treated as a row type
        assertSignature("rowxxx<a>", "rowxxx", ImmutableList.of("a"));
    }

    @Test
    public void parseWithLiteralParameters()
    {
        assertSignature("foo(42)", "foo", ImmutableList.<String>of("42"));
        assertSignature("varchar(10)", "varchar", ImmutableList.<String>of("10"));
    }

    private static void assertRowSignature(
            String typeName,
            String base,
            List<String> parameters)
    {
        assertRowSignature(typeName, base, parameters, typeName);
    }

    private static void assertRowSignature(
            String typeName,
            String base,
            List<String> parameters,
            String expected)
    {
        assertSignature(typeName, base, parameters, expected);
    }

    private static void assertSignature(String typeName, String base, List<String> parameters)
    {
        assertSignature(typeName, base, parameters, typeName.replace("<", "(").replace(">", ")"));
    }

    private static void assertSignature(
            String typeName,
            String base,
            List<String> parameters,
            String expectedTypeName)
    {
        TypeSignature signature = parseTypeSignature(typeName);
        assertEquals(signature.getBase(), base);
        assertEquals(signature.getParameters().size(), parameters.size());
        for (int i = 0; i < signature.getParameters().size(); i++) {
            assertEquals(signature.getParameters().get(i).toString(), parameters.get(i));
        }
        assertEquals(signature.toString(), expectedTypeName);
    }

    private void assertSignatureFail(String typeName)
    {
        try {
            parseTypeSignature(typeName);
            fail("Type signatures with zero parameters should fail to parse");
        }
        catch (RuntimeException e) {
            // Expected
        }
    }
}


text:
title: "Furniture"
bg:  '#63BD2F'
color: black
fa-icon: home
style: center
---

## Red ikea lounge chair $100
![](https://raw.githubusercontent.com/zoevanhavre/VGS/gh-pages/img/IMG_20160520_140727-01.jpeg)

## Christmas tree $50
Folds away in its own box, looks very nice. Feature: Cannot die.

![](https://raw.githubusercontent.com/zoevanhavre/VGS/gh-pages/img/IMG_20141201_234041-01-01.jpeg)

## Glass table
### By itself - $80

Frosted glass square dining table, metal frame, light but sturdy.

![](https://raw.githubusercontent.com/zoevanhavre/VGS/gh-pages/img/IMG_9544.jpg)

### With 3 black chairs - $100

![](https://raw.githubusercontent.com/zoevanhavre/VGS/gh-pages/img/IMG_20160619_161554-01.jpg)

## King size bed (mattress + base) - $100
 This is a NZ king, ~so an extra large queen. Mattress itself is very good quality and not too soft, while the base was cheap but works.
*Pic coming asap*

## Super comfy Lazy-Boy lounge chair >$200 (make an offer)
Black lazy boy. Full recline. Heaven.


text:
from __future__ import print_function
import glob
import itertools
import os
import sys

# PyPI imports
import numpy as np

# Intra-package imports
import pplot
from .fixtures import ref_panels, ref_series, ref_size_series, ref_source

###
# Global variables
###
# Relative figure size
SCALE = 2.5
DPI = 100
FHEIGHT = 3 * SCALE
FWIDTH = 4 * SCALE

###
# Functions
###
def create_axis_display_images(
    mode, test_dir, ref_panels_list, disp1, disp2, disp4, olist, verbose=True
):
    """Compare multi-panel images with independent axis shown in many or none."""
    mode, ref_dir, test_dir = setup_env(mode, test_dir)
    panel1_obj, panel2_obj, panel4_obj = ref_panels_list
    panel1_obj.display_indep_axis = disp1 == "yes"
    panel2_obj.display_indep_axis = disp2 == "yes"
    panel4_obj.display_indep_axis = disp4 == "yes"
    img_name = (
        "figure_multiple_indep_axis_panel1_"
        "{0}_panel2_{1}_panel3_{2}.png".format(disp1, disp2, disp4)
    )
    fname = def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose)
    default_display = (disp1 == "no") and (disp2 == "no") and (disp4 == "no")
    fig_obj = pplot.Figure(
        panels=[panel1_obj, panel2_obj, panel4_obj],
        indep_var_label="Independent axis" if default_display else "",
        indep_var_units="",
        log_indep_axis=False,
        dpi=DPI,
        title=(
            "Multiple independent axis\n"
            "Panel 1 {0}, panel 2 {1}, panel 3 {2}".format(
                disp1, disp2, "yes by omission" if default_display else disp4
            )
        ),
    )
    fig_obj.save(fname)

def create_axis_type_display_images(
    mode, test_dir, ref_series_list, axis_type, series_in_axis, olist, verbose=True
):
    """Create panels with different type of axis types."""
    (
        series1_obj,
        series2_obj,
        series3_obj,
        series4_obj,
        series5_obj,
        series6_obj,
        series7_obj,
        series8_obj,
        series9_obj,
        _,
        _,
    ) = ref_series_list
    mode, ref_dir, test_dir = setup_env(mode, test_dir)
    img_name = "panel_{0}_axis_series_in_{1}_axis.png".format(axis_type, series_in_axis)
    if (axis_type != "filter") or (
        (axis_type == "filter") and (series_in_axis == "primary")
    ):
        fname = def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose)
    if axis_type == "linear":
        if series_in_axis == "both":
            series_obj = [series1_obj, series2_obj, series3_obj, series4_obj]
        elif series_in_axis == "primary":
            series_obj = [series1_obj, series2_obj]
        elif series_in_axis == "secondary":
            series_obj = [series3_obj, series4_obj]
    elif axis_type == "log":
        if series_in_axis == "both":
            series_obj = [series1_obj, series5_obj]
        elif series_in_axis == "primary":
            series_obj = [series1_obj]
        elif series_in_axis == "secondary":
            series_obj = [series6_obj]
    if axis_type == "single":
        if series_in_axis == "both":
            series_obj = [series7_obj, series8_obj]
        elif series_in_axis == "primary":
            series_obj = [series7_obj]
        elif series_in_axis == "secondary":
            series_obj = [series8_obj]
    if axis_type == "filter":
        if series_in_axis == "both":
            pass
        elif series_in_axis == "primary":
            series_obj = [series9_obj]
        elif series_in_axis == "secondary":
            pass
    if (axis_type != "filter") or (
        (axis_type == "filter") and (series_in_axis == "primary")
    ):
        pflag = series_in_axis in ["primary", "both"]
        sflag = series_in_axis in ["secondary", "both"]
        panel_obj = pplot.Panel(
            series=series_obj,
            primary_axis_label="Primary axis" if pflag else None,
            primary_axis_units="-" if pflag else None,
            secondary_axis_label="Secondary axis" if sflag else None,
            secondary_axis_units="-" if sflag else None,
            # Hard-code it here to test series re-calculation
            # when set to True after
            log_dep_axis=False,
        )
        panel_obj.log_dep_axis = bool(axis_type == "log")
        fig_obj = pplot.Figure(
            panels=panel_obj,
            indep_var_label="Independent axis",
            indep_var_units="",
            log_indep_axis=(axis_type == "filter"),
            fig_width=FWIDTH,
            fig_height=FHEIGHT,
            dpi=DPI,
            title="Axis: {0}\nSeries in axis: {1}".format(axis_type, series_in_axis),
        )
        fig_obj.save(fname)

def create_basic_figure_image(mode, test_dir, olist, verbose=True):
    """Create figure without anything but tick marks and series without given size."""
    mode, ref_dir, test_dir = setup_env(mode, test_dir)
    img_name = "figure_basic.png"
    fname = def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose)
    source_obj = pplot.BasicSource(
        np.array(list(range(1, 6))), np.array([1, 2, 3, 10, 4])
    )
    series_obj = pplot.Series(source_obj, label="")
    panel_obj = pplot.Panel(series_obj)
    figure_obj = pplot.Figure(panel_obj, dpi=DPI)
    figure_obj.save(fname)

def create_marker_line_type_image(
    mode, test_dir, ref_src, marker, interp, line_style, olist, verbose=True
):
    """Create figure testing different marker and series line style options."""
    mode, ref_dir, test_dir = setup_env(mode, test_dir)
    line_style_desc = {"-": "solid", "--": "dashed", "-.": "dash-dot", ":": "dot"}
    img_name = "series_marker_{0}_interp_{1}_line_style_{2}.png".format(
        "true" if marker else "false",
        interp.lower(),
        "none" if not line_style else line_style_desc[line_style],
    )
    fname = def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose=verbose)
    series_obj = pplot.Series(
        data_source=ref_src,
        label="test series",
        marker="o" if marker else None,
        interp=interp,
        line_style=line_style,
    )
    panel_obj = pplot.Panel(
        series=series_obj, primary_axis_label="Dependent axis", primary_axis_units="-"
    )
    fig_obj = pplot.Figure(
        panels=panel_obj,
        indep_var_label="Independent axis",
        indep_var_units="",
        log_indep_axis=False,
        fig_width=FWIDTH,
        fig_height=FHEIGHT,
        dpi=DPI,
        title="marker: {0}\ninterp: {1}\nline_style: {2}".format(
            marker, interp, line_style
        ),
    )
    fig_obj.save(fname)

def create_simple_panel_image(mode, test_dir, ref_series_list, olist, verbose=True):
    """Create panel with many series but no labels, should not print legend panel."""
    _, _, _, _, _, _, _, _, _, seriesa_obj, seriesb_obj = ref_series_list
    mode, ref_dir, test_dir = setup_env(mode, test_dir)
    img_name = "panel_no_legend.png"
    fname = def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose)
    series_obj = [seriesa_obj, seriesb_obj]
    panel_obj = pplot.Panel(
        series=series_obj,
        primary_axis_label="Primary axis",
        primary_axis_units="-",
        secondary_axis_label="Secondary axis",
        secondary_axis_units="-",
        log_dep_axis=True,
    )
    fig_obj = pplot.Figure(
        panels=panel_obj,
        indep_var_label="Independent axis",
        indep_var_units="",
        log_indep_axis=False,
        fig_width=FWIDTH,
        fig_height=FHEIGHT,
        dpi=DPI,
        title="Panel no legend",
    )
    fig_obj.save(fname)

def create_sizing_image(
    mode,
    test_dir,
    series_list,
    tlength,
    ilength,
    itype,
    plength,
    slength,
    olist,
    verbose=True,
):
    """Create figure to test minimum image size algorithm."""
    mode, ref_dir, test_dir = setup_env(mode, test_dir)
    series1_obj, series2_obj, series3_obj = series_list
    img_name = "size_title_{0}_indep_{1}_{2}_prim_{3}_sec_{4}.png".format(
        tlength, ilength, itype, plength, slength
    )
    fname = def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose)
    panel1_obj = pplot.Panel(series=series1_obj)
    ltext = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in"
    vartext = lambda x, y: None if x == "no" else (y if x == "short" else ltext)
    panel2_obj = pplot.Panel(
        series=(
            [series2_obj, series3_obj]
            if (plength != "no") and (slength != "no")
            else (series2_obj if plength != "no" else series3_obj)
        ),
        primary_axis_label=vartext(plength, "Primary axis"),
        secondary_axis_label=vartext(slength, "Secondary axis"),
        log_dep_axis=False,
    )
    fig_obj = pplot.Figure(
        panels=[panel1_obj, panel2_obj],
        indep_var_label=vartext(ilength, "Independent axis"),
        log_indep_axis=itype == "log",
        title=vartext(tlength, "Title"),
    )
    fig_obj.save(fname)

def def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose=True):
    """Generate image file names."""
    test_fname = os.path.realpath(os.path.join(test_dir, img_name))
    if mode == "ref":
        ref_fname = os.path.realpath(os.path.join(ref_dir, img_name))
    else:
        # Support incomplete sets of reference images to reduce size
        # of source tar ball
        fdirs = glob.glob(ref_dir.format("*"))
        temp_ref_fname = [
            os.path.realpath(os.path.join(fdir, img_name)) for fdir in fdirs
        ]
        ref_fname = [item for item in temp_ref_fname if os.path.exists(item)]
    olist.append({"ref_fname": ref_fname, "test_fname": test_fname})
    if verbose:
        print("Generating image {0}".format(ref_fname if mode == "ref" else test_fname))
    return ref_fname if mode == "ref" else test_fname

def setup_env(mode, test_dir):
    """Define directories."""
    mode = "ref" if mode is None else mode.lower()
    ref_dir = (
        os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "support",
            "ref_images{0}".format("_{0}" if mode == "test" else ""),
        )
        if (mode == "test") or (not test_dir)
        else test_dir
    )
    test_dir = (
        os.path.abspath(os.path.join(".", os.path.abspath(os.sep), "test_images"))
        if test_dir is None
        else test_dir
    )
    return mode, ref_dir, test_dir

def unittest_series_images(mode=None, test_dir=None, _timeit=False):
    """Images for Series() class."""
    marker_list = [False, True]
    interp_list = ["STRAIGHT", "STEP", "CUBIC", "LINREG"]
    line_style_list = [None, "-", "--", "-.", ":"]
    master_list = [marker_list, interp_list, line_style_list]
    comb_list = itertools.product(*master_list)
    olist = []
    for marker, interp, line_style in comb_list:
        create_marker_line_type_image(
            mode, test_dir, ref_source(), marker, interp, line_style, olist, True
        )
        if _timeit:
            break
    return olist

def unittest_panel_images(mode=None, test_dir=None):
    """Images for Panel() class."""
    axis_type_list = ["single", "linear", "log", "filter"]
    series_in_axis_list = ["primary", "secondary", "both"]
    master_list = [axis_type_list, series_in_axis_list]
    comb_list = itertools.product(*master_list)
    olist = []
    ref_series_list = ref_series()
    for axis_type, series_in_axis in comb_list:
        create_axis_type_display_images(
            mode, test_dir, ref_series_list, axis_type, series_in_axis, olist
        )
    create_simple_panel_image(mode, test_dir, ref_series_list, olist)
    return olist

def unittest_sizing_images(mode=None, test_dir=None):
    """Images for minimum figure size."""
    title_list = ["short", "long", "no"]
    indep_axis_list = ["short", "long", "no"]
    indep_axis_type_list = ["linear", "log"]
    prim_dep_axis_list = ["short", "long", "no"]
    sec_dep_axis_list = ["short", "long", "no"]
    master_list = [
        title_list,
        indep_axis_list,
        indep_axis_type_list,
        prim_dep_axis_list,
        sec_dep_axis_list,
    ]
    comb_list = itertools.product(*master_list)
    olist = []
    print("")
    for tlength, ilength, itype, plength, slength in comb_list:
        create_sizing_image(
            mode,
            test_dir,
            ref_size_series(),
            tlength,
            ilength,
            itype,
            plength,
            slength,
            olist,
            True,
        )

def unittest_figure_images(mode=None, test_dir=None):
    """Images for Figure() class."""
    disp1_list = ["no", "yes"]
    disp2_list = ["no", "yes"]
    disp4_list = ["no", "yes"]
    master_list = [disp1_list, disp2_list, disp4_list]
    comb_list = itertools.product(*master_list)
    olist = []
    ref_panels_list = ref_panels()
    for disp1, disp2, disp4 in comb_list:
        create_axis_display_images(
            mode, test_dir, ref_panels_list, disp1, disp2, disp4, olist
        )
    create_basic_figure_image(mode, test_dir, olist)
    return olist

def main(argv):
    """Generate images."""
    if argv:
        unittest_series_images(mode="ref")
        unittest_panel_images(mode="ref")
        unittest_figure_images(mode="ref")
        unittest_sizing_images(mode="ref")
    else:
        unittest_series_images(mode="ref", test_dir=argv[0])
        unittest_panel_images(mode="ref", test_dir=argv[0])
        unittest_figure_images(mode="ref", test_dir=argv[0])
        unittest_sizing_images(mode="ref", test_dir=argv[0])

if __name__ == "__main__":
    main(sys.argv[1:])


text:
package net.imagej.ops.threshold.huang;

import net.imagej.ops.Ops;
import net.imagej.ops.threshold.AbstractComputeThresholdHistogram;
import net.imglib2.histogram.Histogram1d;
import net.imglib2.type.numeric.RealType;

import org.scijava.Priority;
import org.scijava.plugin.Plugin;

//NB - this plugin adapted from Gabriel Landini's code of his AutoThreshold
//plugin found in Fiji (version 1.14).

/**
 * Implements Huang's threshold method by Huang {@literal &} Wang.
 *
 * @author Barry DeZonia
 * @author Gabriel Landini
 */
@Plugin(type = Ops.Threshold.Huang.class, priority = Priority.HIGH)
public class ComputeHuangThreshold<T extends RealType<T>> extends
		AbstractComputeThresholdHistogram<T> implements Ops.Threshold.Huang {

	@Override
	public long computeBin(final Histogram1d<T> hist) {
		long[] histogram = hist.toLongArray();
		// Implements Huang's fuzzy thresholding method
		// Uses Shannon's entropy function (one can also use Yager's entropy
		// function) Huang L.-K. and Wang M.-J.J. (1995) "Image Thresholding by
		// Minimizing the Measures of Fuzziness" Pattern Recognition, 28(1):
		// 41-51
		// Reimplemented (to handle 16-bit efficiently) by Johannes Schindelin
		// Jan 31, 2011

		// find first and last non-empty bin
		int first, last;
		for (first = 0; first < histogram.length && histogram[first] == 0; first++) {
			// do nothing
		}
		for (last = histogram.length - 1; last > first && histogram[last] == 0; last--) {
			// do nothing
		}
		if (first == last)
			return 0;

		// calculate the cumulative density and the weighted cumulative density
		double[] S = new double[last + 1], W = new double[last + 1];
		S[0] = histogram[0];
		for (int i = Math.max(1, first); i <= last; i++) {
			S[i] = S[i - 1] + histogram[i];
			W[i] = W[i - 1] + i * histogram[i];
		}

		// precalculate the summands of the entropy given the absolute difference
		// x - mu (integral)
		double C = last - first;
		double[] Smu = new double[last + 1 - first];
		for (int i = 1; i < Smu.length; i++) {
			double mu = 1 / (1 + Math.abs(i) / C);
			Smu[i] = -mu * Math.log(mu) - (1 - mu) * Math.log(1 - mu);
		}

		// calculate the threshold
		int bestThreshold = 0;
		double bestEntropy = Double.POSITIVE_INFINITY;
		for (int threshold = first; threshold <= last; threshold++) {
			double entropy = 0;
			int mu = (int) Math.round(W[threshold] / S[threshold]);
			for (int i = first; i <= threshold; i++)
				entropy += Smu[Math.abs(i - mu)] * histogram[i];
			mu = (int) Math.round((W[last] - W[threshold])
					/ (S[last] - S[threshold]));
			for (int i = threshold + 1; i <= last; i++)
				entropy += Smu[Math.abs(i - mu)] * histogram[i];

			if (bestEntropy > entropy) {
				bestEntropy = entropy;
				bestThreshold = threshold;
			}
		}

		return bestThreshold;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/service#humanitarian-initiatives-dominican-republic-lds-695565" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">humanitarian-initiatives-dominican-republic-lds-695565</uri-title>
      <source>humanitarian-initiatives-dominican-republic-lds-695565</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2013-04-22">2013-04-22</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>service</subject>
          <subject>serve</subject>
          <subject>serving</subject>
          <subject>humanitarian</subject>
          <subject>dominican republic</subject>
          <subject>lds</subject>
          <subject>clothing</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/service/humanitarian-initiatives-dominican-republic-lds-695565-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/service/humanitarian-initiatives-dominican-republic-lds-695565-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>659 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/service/humanitarian-initiatives-dominican-republic-lds-695565-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>745 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/service/humanitarian-initiatives-dominican-republic-lds-695565-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>1.6 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/service/humanitarian-initiatives-dominican-republic-lds-695565-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>3.2 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/service/humanitarian-initiatives-dominican-republic-lds-695565-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>