text:
package net.byteseek.matcher.sequence;

import net.byteseek.matcher.Matcher;
import net.byteseek.matcher.bytes.ByteMatcher;

/**
 * An extension to the {@link Matcher} interface to support sequences of
 * Matchers.
 *
 * @author Matt Palmer
 */
 public interface SequenceMatcher extends Matcher, Iterable<ByteMatcher> {

    /**
     * Returns a {@link ByteMatcher} which matches all the bytes at
     * the requested position in the sequence.
     *
     * @param position The position in the byte matcher to return a dedicated byte matcher for.
     * @return A ByteMatcher for the position in the sequence provided.
     * @throws IndexOutOfBoundsException if an attempt is made to get a ByteMatcher
     *                                   for a position outside of the sequence.
     *
     */
    public ByteMatcher getMatcherForPosition(int position);

    /**
     * Returns whether there is a match or not at the given position in a byte array.
     *

     * It does not perform any bounds checking, so an IndexOutOfBoundsException
     * can be thrown by this method if matching is outside the bounds of the array.
     *

     * This method is useful when searching in byte arrays, where the bounds checking
     * of the search algorithm has already assured a safe usage, hence it is more
     * efficient in those circumstances.
     *

     * It is not recommended to use this method for normal matching without some
     * additional bounds checking, or unless you would rather accept the overhead
     * of an IndexOutOfBoundsException on an improper access.
     *
     * @param bytes An array of bytes to read from.
     * @param matchPosition The position to try to match at.
     * @return Whether there is a match at the given position.
     * @throws IndexOutOfBoundsException if a match is made outside the bounds of
     *                                   the array.
     * @throws NullPointerException if the byte array passed in is null.
     */
    public boolean matchesNoBoundsCheck(byte[] bytes, int matchPosition);

    /**
     * Returns the length of the matching sequence.
     *
     * @return Returns the length of a matching byte sequence.
     */
    public int length();

    /**
     * Returns a new SequenceMatcher which matches the reverse sequence of the
     * original sequence matcher.
     *
     * @return A SequenceMatcher which matches the reverse sequence.
     */
    public SequenceMatcher reverse();

    /**
     * Returns a new SequenceMatcher which matches a sub-sequence of the
     * original sequence.  The subsequence returned must match at least one
     * byte (an empty SequenceMatcher is prohibited).
     *
     * @param beginIndex The beginning index, starting at zero, inclusive.
     * @param endIndex The ending index, exclusive.
     * @return SequenceMatcher the specified sub-sequence.
     * @throws IndexOutOfBoundsException if the beginIndex is negative,
     *         or the endIndex is greater than the length of the sequence,
     *         or the beginIndex is greater than or equal to the endIndex.
     */
    public SequenceMatcher subsequence(int beginIndex, int endIndex);

    /**
     * Returns a new SequenceMatcher which matches a sub-sequence of the original
     * sequence starting from the begin index.  The subsequence returned must match
     * at least one byte (and empty SequenceMatcher is prohibited).
     *
     * @param beginIndex The beginning index, starting at zero.
     * @return SequenceMatcher the specified sub-sequence.
     * @throws IndexOutOfBoundsException if the beginIndex is negative,
     *         or the endIndex is greater than the length of the sequence,
     *         or the beginIndex is greater than or equal to the endIndex.
     */
    public SequenceMatcher subsequence(int beginIndex);

    /**
     * Returns a SequenceMatcher which matches this SequenceMatcher repeated
     * a number of times.
     *
     * @param numberOfRepeats The number of times to repeat this SequenceMatcher.
     * @return A SequenceMatcher which matches the same as this sequence repeated
     *         a number of times.
     */
    public SequenceMatcher repeat(final int numberOfRepeats);

    /**
     * Returns a regular expression representation of the matching sequence.
     *
     * @param prettyPrint whether to pretty print the regular expression with spacing.
     * @return A string containing a regular expression of the byte matcher.
     */
    public String toRegularExpression(boolean prettyPrint);

}


text:
// This file is automatically generated.

package adila.db;

/*
 * Smartfren B16C2G
 *
 * DEVICE: MSM8909QC
 * MODEL: Andromax B16C2G
 */
final class msm8909qc_andromax20b16c2g {
    public static final String DATA = "Smartfren|B16C2G|";
}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'base.html' %}

{% from 'host/common.html' import edit_field %}
{% from 'host/common.html' import alert_duplicate %}

{% if request.endpoint.endswith('edit') %}
    {% set isEdit = True %}
{% else %}
    {% set isEdit = False %}
{% endif %}

{% block extra_head %}

{% endblock extra_head %}

{% block main %}

        <form id="form" method=post class="form-horizontal">
            <legend>{% if isEdit %}Edit User{% else %}Create User{% endif %}</legend>
            {{ alert_duplicate(form.username.data, duplicate_error) }}

            {% if isEdit %}
                {% set extra_field ='
                    ' %}
                {{ edit_field(form.username, readonly=True, field_width="col-sm-6", maxlength=100, class="form-control", extra_field=extra_field ) }}
            {% else %}
                {{ edit_field(form.username, field_width="col-sm-6", maxlength=100, class="form-control") }}
            {% endif %}

                {% if isEdit %}
                    {{ edit_field(form.password, autocomplete="off", field_width="col-sm-6", maxlength=100, class="form-control",
                        placeholder="Use Password on File") }}
                {% else %}
                    {{ edit_field(form.password, autocomplete="off", field_width="col-sm-6", maxlength=100, class="form-control") }}
                {% endif %}

                {{ edit_field(form.privilege, class="form-control") }}

                    {{ form.active.label.text }}

                            <button type="button" id="active-yes-button" class="btn" data-value=1>Yes</button>
                            <button type="button" id="active-no-button" class="btn" data-value=0>No</button>

                    <input class="form-control" id="{{ form.active.id }}" name="{{ form.active.id }}" type="hidden" value="{{ form.active.data }}">

            <legend>Information</legend>

            {{ edit_field(form.fullname, class="form-control") }}
            {{ edit_field(form.email, class="form-control") }}

                    <button type="submit" class="btn btn-primary">Save</button>
                    <button type="button" onClick="location.href='{{ url_for('home') }}'" class="btn btn-default">Cancel</button>

        </form>

{% endblock main %}


text:
module.exports = {
	name: 'untitled-website',
	version: '0.0.0',
	description: 'My untitled website.',
	keywords: [],
	homepage: '',
	repository: '',
	license: '',
	dependencies: {
		'aero': '*'
	}
}


text:
package com.effektif.workflow.impl.json.types;

import com.effektif.workflow.impl.json.JsonTypeMapper;
import com.effektif.workflow.impl.json.Mappings;

/**
 * Maps values of some type to a JSON string field for serialisation and deserialisation.
 *
 * @author Tom Baeyens
 */
public abstract class AbstractTypeMapper<T> implements JsonTypeMapper<T> {

  protected Mappings mappings;

  public Mappings getMappings() {
    return mappings;
  }

  public void setMappings(Mappings mappings) {
    this.mappings = mappings;
  }

  @Override
  public String toString() {
    return getClass().getSimpleName();
  }

}


text:
title: maca
layout: default
---

# maca:  Machine Vision Tools for NeuroData

maca provides interfaces for a collection of popular machine learning and computer vision tools used in neuroscience.  This includes ilastik and gala in its initial release.

![](images/ndod/maca_example.png)

## Introduction

A number of tools exist for generating machine annotations (labels) for neuroscience data.  These tools have varying, specific input and output requirements, which makes it difficult to build interoperable pipelines and workflows.

maca provides a series of interfaces to get image data from the NeuroData spatial database, run a machine annotation tool, and convert the resulting annotations to a NeuroData compatible format that can be easily written back to a database project.

As workflows and additional functionalities are developed, we will continue to add to this repository.

Currently, we provide wrappers for the following tools/capabilities:

- ilastik (Pixel Classification)
- gala (agglomerative segmentation)
- rhoana (multi-hypothesis fusion/segmentation)
- membrane detection

## Configuration

In order to use this truthing protocol, users should have the following software:

### General dependencies

 - [CAJAL Toolbox](http://github.com/openconnectome/cajal)
 - A recent version of [MATLAB](http://mathworks.com)

### ilastik

- [ilastik v1.15+](http://www.ilastik.org/)

### gala

### rhoana

Please follow the instructions with each program to download and install, and setup cajal and ndod (as an installed toolbox).
 For the neurodata tools, you can be up and running with the following commands within MATLAB.  Please replace values inside ```< >``` (including the brackets) with the correct paths for your system.

~~~
run('<cajal root directory>/tools/matlab_install/setupEnvironment.m')
run('<cajal root directory>/cajal.m')
cajal.installToolbox('<ndod root directory>/setup.m')
~~~

*Note that this section is being rewritten to leverage conda and pip, to make the setup process much more streamlined.*

## Ilastik

ilastik is a tool developed to do machine annotation and is widely used by the connectomics community.
We present a lightweight protocol and data exchange format to allow users to use ilastik and NeuroData together.
This provides an easy method for users to quickly prototype, build, and deploy machine learning solutions
to neuroscience problems.  The figure below outlines a sample workflow.
The initial version of this workflow supports both pixel classification and an object detection step.

The example classifiers presented are used as a capability demonstration, not to demonstrate outstanding
classification performance.  If you would like to contribute a better performing classifier, please contact us.

Ilastik already supports exchanging data in hdf5 format.  The wrappers and functions provided here are used to help
read in raw NeuroData data and format the classifier output into RAMON objects suitable for uploading to NeuroData project databases.

LONI modules and an example workflow exist to enable rapid development.

![](./images/ndod/maca_ilastik_intro.png)

### Pixel Classification Train

- Identify a region of interest in NeuroData, and note the data server, token, resolution, and coordinates
- Create a query, using the instructions for NeuroData RESTful queries, CAJAL, or ndio (CAJAL: cubeCutoutPreprocessAdvanced.m).
- Download a raw data volume in HDF5 format (CAJAL: cubeCutout.m)
- Using ilastik, build a pixel classifier, following the [Pixel Classification instructions in Ilastik](http://ilastik.org/documentation/pixelclassification/pixelclassification.html)
- Save your ilastik project, containing your trained classifier

### Pixel Classification Deploy

- Identify a region of interest in NeuroData, and note the data server, token, resolution, and coordinates
- Create a query, using the instructions for NeuroData RESTful queries, CAJAL, or ndio (CAJAL: cubeCutoutPreprocessAdvanced.m).
- Download a raw data volume in HDF5 format (CAJAL: cubeCutout.m)
- Classify the volume of interest using [Ilastik in headless mode](http://ilastik.org/documentation/pixelclassification/headless.html)
- Reformat (using ilastikPixelToRAMON.m) and upload results (using CAJAL: cubeUploadProbabilities.m)

#### Ilastik Command:

~~~
<ilastik executable> --headless
--project <project file>.ilp
--output_format hdf5
--output_filename_format <output filename>
<path and filename for raw data>/<hdf5 dataset>
~~~

### Object Detection Train

- Identify a region of interest in NeuroData, and note the data server, token, resolution, and coordinates
- Create a query, using the instructions for NeuroData RESTful queries, CAJAL, or ndio (CAJAL: cubeCutoutPreprocessAdvanced.m).
- Download a raw data volume in HDF5 format (CAJAL: cubeCutout.m).
- Using ilastik, your raw data, and the results from a previous pixel classification step, build an object classifier, following the [Object Classification Workflow](http://ilastik.org/documentation/objects/objects.html).

### Object Detection Deploy

- Identify a region of interest in NeuroData, and note the data server, token, resolution, and coordinates
- Create a query, using the instructions for NeuroData RESTful queries, CAJAL, or ndio.
- Download a raw data volume in HDF5 format
- Create pixel classification outputs using the corresponding ilastik classifier
- Pass pixel classification and raw data inputs into the ilastik object classifier
- Reformat (using ilastikObjectToRAMON.m) and upload results (using CAJAL: cubeUploadDense.m)

#### Ilastik Command:

~~~
<ilastik executable> --headless
--project=<projectfile>.ilp
--export_object_prediction_img
--raw_data <path and filename for raw data>/</hdf5 dataset>
--prediction_maps <path and filename for probability maps>.h5/<hdf5 dataset>
--output_filename_format <output filename>
--output_format hdf5
~~~

### Example

*"I want to add annotations to my dataset."*

This example walks through obtaining data from NeuroData, building classifiers in ilastik and deploying these classifiers in the NeuroData framework.
The definitive documentation is at ilastik.org.  Here we seek to build a lightweight classifier to detect mitochondria in our images.

**For pixel classification in ilastik**

1.  Get datasets for training and test.  These volumes may be obtained via RESTful interface.  One simple option is to copy and paste the following URLs into a web browser.  All volumes should be renamed with an '.h5' extension.

**Pixel Classification Training Volume**

~~~
http://openconnecto.me/NeuroData/ca/kasthuri11cc/hdf5/1/3000,4000/5000,6000/1000,1016/
~~~

Link to first slice

~~~
http://openconnecto.me/NeuroData/ca/kasthuri11cc/xy/1/3000,4000/5000,6000/1000/
~~~

**Pixel Classification Test Volume / Object Detection Training Volume**

~~~
http://openconnecto.me/NeuroData/ca/kasthuri11cc/hdf5/1/3000,4000/5000,6000/1017,1032/
~~~

Link to first slice

~~~
http://openconnecto.me/NeuroData/ca/kasthuri11cc/xy/1/3000,4000/5000,6000/1017/
~~~

**Object Detection Test Volume**

~~~
http://openconnecto.me/NeuroData/ca/kasthuri11cc/hdf5/1/3000,4000/5000,6000/1033,1048/
~~~

Link to first slice

~~~
http://openconnecto.me/NeuroData/ca/kasthuri11cc/xy/1/3000,4000/5000,6000/1048/
~~~

2.  Open Ilastik
3.  Create New Project  > Pixel Classification
4.  Add new data > separate image > <training volume>
5.  Still in the input data tab, right click on dataset description, edit properties -> change storage to save with classifier; change axes to -> zyx
6.  In the feature selection tab, choose some features appropriate to your task (we choose color, edge, and texture with a sigma of 1 for this example)
7.  In the training tab, add two labels, mitochondria and background.  We assume that your target class is the first label, throughout this example *Live prediction can help guide you, but may require substantial memory, especially for large datasets.*
8.  Save project and exit.
9.  Run the Ilastik classifier, following the example above
10. Convert output data to an NeuroData compatible format (probability channel needs to be chosen, xy axes need to be switched, and data should be converted to a RAMONVolume) ilastik object detection requires the raw ilastik output
11.  Upload result to NeuroData, using (using CAJAL: cubeUploadProbabilities.m)

**For object detection in ilastik (depends on pixel classification)**

1.  Open Ilastik
2.  Create New Project > Object Classification with Inputs of Raw Data + Pixel Prediction Map
3.  Load data
4.  In the threshold and size filter tab, we chose only one threshold, with sigma values defaulted to 1. Threshold = 0.7, and size filter = 1000-1000000
5.  In the features tab, select all features
6.  Add labels of mitochondria and background (target/clutter)
7.  In the object classification tab, label detections as either target or clutter
8.  This is sufficient for classification, although subsequent ilastik steps may help improve classifier performance.
9.  Save project and exit ilastik.
10.  Run the Ilastik classifier, following the example above
11.  Convert output data to an NeuroData compatible format (xy axes need to be switched and array squeezed.  Making unique objects is handled in the next step)
12.  Group objects by connected component and upload to NeuroData using (using CAJAL: cubeUploadDense.m)

**Sample classifiers:**

~~~
./data/ilastik_mito_pixelclassification.ilp
./data/ilastik_mito_objclassification.ilp
~~~

Sample results:

~~~
http:///NeuroData/overlay/0.4/test_ilastik_prob1/xy/1/7000,8000/8500,9500/1010/
~~~

![](images/ndod/maca_ilastik_pixel_class_example.png)

### Advanced Topics/Future Functionality

- When uploading annotations processed as many small cubes, often some sort of padding or stitching operation is required.  These will differ slightly depending on use cases.  Examples exist (e.g., i2g, vesicle) to use as a starting point
- When running in an SGE cluster environment, we suggest limiting threads to 1 and RAM to the value specified in LONI to allow ilastik lazy operations to co-exist smoothly with SGE.  To do this, specify the following environment variables:  LAZYFLOW_THREADS=1 LAZYFLOW_TOTAL_RAM_MB=8000 run_ilastik.sh --headless ...

## Gala
Coming soon!

## Rhoana
Coming soon!

## Support

If you have questions about ndod, or have data to analyze, let us know:  support@neurodata.io


text:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="javascript" src="prepopulated.js"></script>
    <link rel="stylesheet" href="prepopulated.css">
</head>
<body>

</body>
</html>


text:
export default function(state = null, action) {
            // ES6 syntax. If state comes in as undefined, set it to null. Since redux does not allow undefined state.
    switch (action.type) {
        case 'BOOK_SELECTED':
            return action.payload;
    }
    return state; // when don't care about the action
}


text:
import React from "react";
import PropTypes from "prop-types";

class LoginMessage extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { error, logout, validateErrors } = this.props;

    let errorContainer;
    if (
      validateErrors.username.length > 0 ||
      validateErrors.password.length > 0
    ) {
      errorContainer = (

          {" "}
          {Object.keys(validateErrors).map((key, index) => {
            if (validateErrors[key].length > 0) {
              return
{validateErrors[key]}
;
            }
          })}

      );
    } else if (error) {
      errorContainer = (

            {" "}
            Invalid username and / or password.{" "}

      );
    } else if (logout) {
      errorContainer = (

            {" "}
            You have been logged out successfully.{" "}

      );
    } else {
      errorContainer = (

      );
    }

    return errorContainer;
  }
}

LoginMessage.propTypes = {
  error: PropTypes.bool.isRequired,
  logout: PropTypes.bool.isRequired,
  validateErrors: PropTypes.object
};

export default LoginMessage;


text:
package com.opengamma.financial.security.option;

import java.util.Map;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityVisitor;
import com.opengamma.id.ExternalId;
import com.opengamma.master.security.SecurityDescription;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Expiry;

/**
 * A security for equity options with a single barrier.
 */
@BeanDefinition
@SecurityDescription(type = EquityBarrierOptionSecurity.SECURITY_TYPE, description = "Equity barrier option")
public class EquityBarrierOptionSecurity extends FinancialSecurity {

  /** Serialization version. */
  private static final long serialVersionUID = 1L;

  /**
   * The security type.
   */
  public static final String SECURITY_TYPE = "EQUITY_BARRIER_OPTION";

  /**
   * The option type.
   */
  @PropertyDefinition(validate = "notNull")
  private OptionType _optionType;
  /**
   * The strike.
   */
  @PropertyDefinition
  private double _strike;
  /**
   * The currency.
   */
  @PropertyDefinition(validate = "notNull")
  private Currency _currency;
  /**
   * The underlying identifier.
   */
  @PropertyDefinition(validate = "notNull")
  private ExternalId _underlyingId;
  /**
   * The exercise type.
   */
  @PropertyDefinition(validate = "notNull")
  private ExerciseType _exerciseType;
  /**
   * The expiry.
   */
  @PropertyDefinition(validate = "notNull")
  private Expiry _expiry;
  /**
   * The point value.
   */
  @PropertyDefinition
  private double _pointValue;
  /**
   * The exchange.
   */
  @PropertyDefinition(validate = "notNull")
  private String _exchange;
  /**
   * The barrier type.
   */
  @PropertyDefinition(validate = "notNull")
  private BarrierType _barrierType;
  /**
   * The barrier direction.
   */
  @PropertyDefinition(validate = "notNull")
  private BarrierDirection _barrierDirection;
  /**
   * The monitoring type.
   */
  @PropertyDefinition(validate = "notNull")
  private MonitoringType _monitoringType;
  /**
   * The sampling frequency.
   */
  @PropertyDefinition(validate = "notNull")
  private SamplingFrequency _samplingFrequency;
  /**
   * The barrier level.
   */
  @PropertyDefinition(validate = "notNull")
  private double _barrierLevel;

  EquityBarrierOptionSecurity() { //For builder
    super(SECURITY_TYPE);
  }

  public EquityBarrierOptionSecurity(OptionType optionType, double strike, Currency currency, ExternalId underlyingId,
      ExerciseType exerciseType, Expiry expiry, double pointValue, String exchange, BarrierType barrierType,
      BarrierDirection barrierDirection, MonitoringType monitoringType, SamplingFrequency samplingFrequency, double barrierLevel) {
    super(SECURITY_TYPE);
    setOptionType(optionType);
    setStrike(strike);
    setCurrency(currency);
    setUnderlyingId(underlyingId);
    setExerciseType(exerciseType);
    setExpiry(expiry);
    setPointValue(pointValue);
    setExchange(exchange);
    setBarrierType(barrierType);
    setBarrierDirection(barrierDirection);
    setMonitoringType(monitoringType);
    setSamplingFrequency(samplingFrequency);
    setBarrierLevel(barrierLevel);
  }

  //-------------------------------------------------------------------------
  @Override
  public final <T> T accept(FinancialSecurityVisitor<T> visitor) {
    return visitor.visitEquityBarrierOptionSecurity(this);
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code EquityBarrierOptionSecurity}.
   * @return the meta-bean, not null
   */
  public static EquityBarrierOptionSecurity.Meta meta() {
    return EquityBarrierOptionSecurity.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(EquityBarrierOptionSecurity.Meta.INSTANCE);
  }

  @Override
  public EquityBarrierOptionSecurity.Meta metaBean() {
    return EquityBarrierOptionSecurity.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the option type.
   * @return the value of the property, not null
   */
  public OptionType getOptionType() {
    return _optionType;
  }

  /**
   * Sets the option type.
   * @param optionType  the new value of the property, not null
   */
  public void setOptionType(OptionType optionType) {
    JodaBeanUtils.notNull(optionType, "optionType");
    this._optionType = optionType;
  }

  /**
   * Gets the the {@code optionType} property.
   * @return the property, not null
   */
  public final Property<OptionType> optionType() {
    return metaBean().optionType().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the strike.
   * @return the value of the property
   */
  public double getStrike() {
    return _strike;
  }

  /**
   * Sets the strike.
   * @param strike  the new value of the property
   */
  public void setStrike(double strike) {
    this._strike = strike;
  }

  /**
   * Gets the the {@code strike} property.
   * @return the property, not null
   */
  public final Property<Double> strike() {
    return metaBean().strike().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the currency.
   * @return the value of the property, not null
   */
  public Currency getCurrency() {
    return _currency;
  }

  /**
   * Sets the currency.
   * @param currency  the new value of the property, not null
   */
  public void setCurrency(Currency currency) {
    JodaBeanUtils.notNull(currency, "currency");
    this._currency = currency;
  }

  /**
   * Gets the the {@code currency} property.
   * @return the property, not null
   */
  public final Property<Currency> currency() {
    return metaBean().currency().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the underlying identifier.
   * @return the value of the property, not null
   */
  public ExternalId getUnderlyingId() {
    return _underlyingId;
  }

  /**
   * Sets the underlying identifier.
   * @param underlyingId  the new value of the property, not null
   */
  public void setUnderlyingId(ExternalId underlyingId) {
    JodaBeanUtils.notNull(underlyingId, "underlyingId");
    this._underlyingId = underlyingId;
  }

  /**
   * Gets the the {@code underlyingId} property.
   * @return the property, not null
   */
  public final Property<ExternalId> underlyingId() {
    return metaBean().underlyingId().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the exercise type.
   * @return the value of the property, not null
   */
  public ExerciseType getExerciseType() {
    return _exerciseType;
  }

  /**
   * Sets the exercise type.
   * @param exerciseType  the new value of the property, not null
   */
  public void setExerciseType(ExerciseType exerciseType) {
    JodaBeanUtils.notNull(exerciseType, "exerciseType");
    this._exerciseType = exerciseType;
  }

  /**
   * Gets the the {@code exerciseType} property.
   * @return the property, not null
   */
  public final Property<ExerciseType> exerciseType() {
    return metaBean().exerciseType().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the expiry.
   * @return the value of the property, not null
   */
  public Expiry getExpiry() {
    return _expiry;
  }

  /**
   * Sets the expiry.
   * @param expiry  the new value of the property, not null
   */
  public void setExpiry(Expiry expiry) {
    JodaBeanUtils.notNull(expiry, "expiry");
    this._expiry = expiry;
  }

  /**
   * Gets the the {@code expiry} property.
   * @return the property, not null
   */
  public final Property<Expiry> expiry() {
    return metaBean().expiry().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the point value.
   * @return the value of the property
   */
  public double getPointValue() {
    return _pointValue;
  }

  /**
   * Sets the point value.
   * @param pointValue  the new value of the property
   */
  public void setPointValue(double pointValue) {
    this._pointValue = pointValue;
  }

  /**
   * Gets the the {@code pointValue} property.
   * @return the property, not null
   */
  public final Property<Double> pointValue() {
    return metaBean().pointValue().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the exchange.
   * @return the value of the property, not null
   */
  public String getExchange() {
    return _exchange;
  }

  /**
   * Sets the exchange.
   * @param exchange  the new value of the property, not null
   */
  public void setExchange(String exchange) {
    JodaBeanUtils.notNull(exchange, "exchange");
    this._exchange = exchange;
  }

  /**
   * Gets the the {@code exchange} property.
   * @return the property, not null
   */
  public final Property<String> exchange() {
    return metaBean().exchange().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the barrier type.
   * @return the value of the property, not null
   */
  public BarrierType getBarrierType() {
    return _barrierType;
  }

  /**
   * Sets the barrier type.
   * @param barrierType  the new value of the property, not null
   */
  public void setBarrierType(BarrierType barrierType) {
    JodaBeanUtils.notNull(barrierType, "barrierType");
    this._barrierType = barrierType;
  }

  /**
   * Gets the the {@code barrierType} property.
   * @return the property, not null
   */
  public final Property<BarrierType> barrierType() {
    return metaBean().barrierType().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the barrier direction.
   * @return the value of the property, not null
   */
  public BarrierDirection getBarrierDirection() {
    return _barrierDirection;
  }

  /**
   * Sets the barrier direction.
   * @param barrierDirection  the new value of the property, not null
   */
  public void setBarrierDirection(BarrierDirection barrierDirection) {
    JodaBeanUtils.notNull(barrierDirection, "barrierDirection");
    this._barrierDirection = barrierDirection;
  }

  /**
   * Gets the the {@code barrierDirection} property.
   * @return the property, not null
   */
  public final Property<BarrierDirection> barrierDirection() {
    return metaBean().barrierDirection().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the monitoring type.
   * @return the value of the property, not null
   */
  public MonitoringType getMonitoringType() {
    return _monitoringType;
  }

  /**
   * Sets the monitoring type.
   * @param monitoringType  the new value of the property, not null
   */
  public void setMonitoringType(MonitoringType monitoringType) {
    JodaBeanUtils.notNull(monitoringType, "monitoringType");
    this._monitoringType = monitoringType;
  }

  /**
   * Gets the the {@code monitoringType} property.
   * @return the property, not null
   */
  public final Property<MonitoringType> monitoringType() {
    return metaBean().monitoringType().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the sampling frequency.
   * @return the value of the property, not null
   */
  public SamplingFrequency getSamplingFrequency() {
    return _samplingFrequency;
  }

  /**
   * Sets the sampling frequency.
   * @param samplingFrequency  the new value of the property, not null
   */
  public void setSamplingFrequency(SamplingFrequency samplingFrequency) {
    JodaBeanUtils.notNull(samplingFrequency, "samplingFrequency");
    this._samplingFrequency = samplingFrequency;
  }

  /**
   * Gets the the {@code samplingFrequency} property.
   * @return the property, not null
   */
  public final Property<SamplingFrequency> samplingFrequency() {
    return metaBean().samplingFrequency().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the barrier level.
   * @return the value of the property, not null
   */
  public double getBarrierLevel() {
    return _barrierLevel;
  }

  /**
   * Sets the barrier level.
   * @param barrierLevel  the new value of the property, not null
   */
  public void setBarrierLevel(double barrierLevel) {
    JodaBeanUtils.notNull(barrierLevel, "barrierLevel");
    this._barrierLevel = barrierLevel;
  }

  /**
   * Gets the the {@code barrierLevel} property.
   * @return the property, not null
   */
  public final Property<Double> barrierLevel() {
    return metaBean().barrierLevel().createProperty(this);
  }

  //-----------------------------------------------------------------------
  @Override
  public EquityBarrierOptionSecurity clone() {
    return JodaBeanUtils.cloneAlways(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      EquityBarrierOptionSecurity other = (EquityBarrierOptionSecurity) obj;
      return JodaBeanUtils.equal(getOptionType(), other.getOptionType()) &&
          JodaBeanUtils.equal(getStrike(), other.getStrike()) &&
          JodaBeanUtils.equal(getCurrency(), other.getCurrency()) &&
          JodaBeanUtils.equal(getUnderlyingId(), other.getUnderlyingId()) &&
          JodaBeanUtils.equal(getExerciseType(), other.getExerciseType()) &&
          JodaBeanUtils.equal(getExpiry(), other.getExpiry()) &&
          JodaBeanUtils.equal(getPointValue(), other.getPointValue()) &&
          JodaBeanUtils.equal(getExchange(), other.getExchange()) &&
          JodaBeanUtils.equal(getBarrierType(), other.getBarrierType()) &&
          JodaBeanUtils.equal(getBarrierDirection(), other.getBarrierDirection()) &&
          JodaBeanUtils.equal(getMonitoringType(), other.getMonitoringType()) &&
          JodaBeanUtils.equal(getSamplingFrequency(), other.getSamplingFrequency()) &&
          JodaBeanUtils.equal(getBarrierLevel(), other.getBarrierLevel()) &&
          super.equals(obj);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = 7;
    hash = hash * 31 + JodaBeanUtils.hashCode(getOptionType());
    hash = hash * 31 + JodaBeanUtils.hashCode(getStrike());
    hash = hash * 31 + JodaBeanUtils.hashCode(getCurrency());
    hash = hash * 31 + JodaBeanUtils.hashCode(getUnderlyingId());
    hash = hash * 31 + JodaBeanUtils.hashCode(getExerciseType());
    hash = hash * 31 + JodaBeanUtils.hashCode(getExpiry());
    hash = hash * 31 + JodaBeanUtils.hashCode(getPointValue());
    hash = hash * 31 + JodaBeanUtils.hashCode(getExchange());
    hash = hash * 31 + JodaBeanUtils.hashCode(getBarrierType());
    hash = hash * 31 + JodaBeanUtils.hashCode(getBarrierDirection());
    hash = hash * 31 + JodaBeanUtils.hashCode(getMonitoringType());
    hash = hash * 31 + JodaBeanUtils.hashCode(getSamplingFrequency());
    hash = hash * 31 + JodaBeanUtils.hashCode(getBarrierLevel());
    return hash ^ super.hashCode();
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(448);
    buf.append("EquityBarrierOptionSecurity{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  @Override
  protected void toString(StringBuilder buf) {
    super.toString(buf);
    buf.append("optionType").append('=').append(JodaBeanUtils.toString(getOptionType())).append(',').append(' ');
    buf.append("strike").append('=').append(JodaBeanUtils.toString(getStrike())).append(',').append(' ');
    buf.append("currency").append('=').append(JodaBeanUtils.toString(getCurrency())).append(',').append(' ');
    buf.append("underlyingId").append('=').append(JodaBeanUtils.toString(getUnderlyingId())).append(',').append(' ');
    buf.append("exerciseType").append('=').append(JodaBeanUtils.toString(getExerciseType())).append(',').append(' ');
    buf.append("expiry").append('=').append(JodaBeanUtils.toString(getExpiry())).append(',').append(' ');
    buf.append("pointValue").append('=').append(JodaBeanUtils.toString(getPointValue())).append(',').append(' ');
    buf.append("exchange").append('=').append(JodaBeanUtils.toString(getExchange())).append(',').append(' ');
    buf.append("barrierType").append('=').append(JodaBeanUtils.toString(getBarrierType())).append(',').append(' ');
    buf.append("barrierDirection").append('=').append(JodaBeanUtils.toString(getBarrierDirection())).append(',').append(' ');
    buf.append("monitoringType").append('=').append(JodaBeanUtils.toString(getMonitoringType())).append(',').append(' ');
    buf.append("samplingFrequency").append('=').append(JodaBeanUtils.toString(getSamplingFrequency())).append(',').append(' ');
    buf.append("barrierLevel").append('=').append(JodaBeanUtils.toString(getBarrierLevel())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code EquityBarrierOptionSecurity}.
   */
  public static class Meta extends FinancialSecurity.Meta {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code optionType} property.
     */
    private final MetaProperty<OptionType> _optionType = DirectMetaProperty.ofReadWrite(
        this, "optionType", EquityBarrierOptionSecurity.class, OptionType.class);
    /**
     * The meta-property for the {@code strike} property.
     */
    private final MetaProperty<Double> _strike = DirectMetaProperty.ofReadWrite(
        this, "strike", EquityBarrierOptionSecurity.class, Double.TYPE);
    /**
     * The meta-property for the {@code currency} property.
     */
    private final MetaProperty<Currency> _currency = DirectMetaProperty.ofReadWrite(
        this, "currency", EquityBarrierOptionSecurity.class, Currency.class);
    /**
     * The meta-property for the {@code underlyingId} property.
     */
    private final MetaProperty<ExternalId> _underlyingId = DirectMetaProperty.ofReadWrite(
        this, "underlyingId", EquityBarrierOptionSecurity.class, ExternalId.class);
    /**
     * The meta-property for the {@code exerciseType} property.
     */
    private final MetaProperty<ExerciseType> _exerciseType = DirectMetaProperty.ofReadWrite(
        this, "exerciseType", EquityBarrierOptionSecurity.class, ExerciseType.class);
    /**
     * The meta-property for the {@code expiry} property.
     */
    private final MetaProperty<Expiry> _expiry = DirectMetaProperty.ofReadWrite(
        this, "expiry", EquityBarrierOptionSecurity.class, Expiry.class);
    /**
     * The meta-property for the {@code pointValue} property.
     */
    private final MetaProperty<Double> _pointValue = DirectMetaProperty.ofReadWrite(
        this, "pointValue", EquityBarrierOptionSecurity.class, Double.TYPE);
    /**
     * The meta-property for the {@code exchange} property.
     */
    private final MetaProperty<String> _exchange = DirectMetaProperty.ofReadWrite(
        this, "exchange", EquityBarrierOptionSecurity.class, String.class);
    /**
     * The meta-property for the {@code barrierType} property.
     */
    private final MetaProperty<BarrierType> _barrierType = DirectMetaProperty.ofReadWrite(
        this, "barrierType", EquityBarrierOptionSecurity.class, BarrierType.class);
    /**
     * The meta-property for the {@code barrierDirection} property.
     */
    private final MetaProperty<BarrierDirection> _barrierDirection = DirectMetaProperty.ofReadWrite(
        this, "barrierDirection", EquityBarrierOptionSecurity.class, BarrierDirection.class);
    /**
     * The meta-property for the {@code monitoringType} property.
     */
    private final MetaProperty<MonitoringType> _monitoringType = DirectMetaProperty.ofReadWrite(
        this, "monitoringType", EquityBarrierOptionSecurity.class, MonitoringType.class);
    /**
     * The meta-property for the {@code samplingFrequency} property.
     */
    private final MetaProperty<SamplingFrequency> _samplingFrequency = DirectMetaProperty.ofReadWrite(
        this, "samplingFrequency", EquityBarrierOptionSecurity.class, SamplingFrequency.class);
    /**
     * The meta-property for the {@code barrierLevel} property.
     */
    private final MetaProperty<Double> _barrierLevel = DirectMetaProperty.ofReadWrite(
        this, "barrierLevel", EquityBarrierOptionSecurity.class, Double.TYPE);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, (DirectMetaPropertyMap) super.metaPropertyMap(),
        "optionType",
        "strike",
        "currency",
        "underlyingId",
        "exerciseType",
        "expiry",
        "pointValue",
        "exchange",
        "barrierType",
        "barrierDirection",
        "monitoringType",
        "samplingFrequency",
        "barrierLevel");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1373587791:  // optionType
          return _optionType;
        case -891985998:  // strike
          return _strike;
        case 575402001:  // currency
          return _currency;
        case -771625640:  // underlyingId
          return _underlyingId;
        case -466331342:  // exerciseType
          return _exerciseType;
        case -1289159373:  // expiry
          return _expiry;
        case 1257391553:  // pointValue
          return _pointValue;
        case 1989774883:  // exchange
          return _exchange;
        case 1029043089:  // barrierType
          return _barrierType;
        case 502579592:  // barrierDirection
          return _barrierDirection;
        case -1483652190:  // monitoringType
          return _monitoringType;
        case 1178782005:  // samplingFrequency
          return _samplingFrequency;
        case 1827586573:  // barrierLevel
          return _barrierLevel;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends EquityBarrierOptionSecurity> builder() {
      return new DirectBeanBuilder<EquityBarrierOptionSecurity>(new EquityBarrierOptionSecurity());
    }

    @Override
    public Class<? extends EquityBarrierOptionSecurity> beanType() {
      return EquityBarrierOptionSecurity.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code optionType} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<OptionType> optionType() {
      return _optionType;
    }

    /**
     * The meta-property for the {@code strike} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<Double> strike() {
      return _strike;
    }

    /**
     * The meta-property for the {@code currency} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<Currency> currency() {
      return _currency;
    }

    /**
     * The meta-property for the {@code underlyingId} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<ExternalId> underlyingId() {
      return _underlyingId;
    }

    /**
     * The meta-property for the {@code exerciseType} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<ExerciseType> exerciseType() {
      return _exerciseType;
    }

    /**
     * The meta-property for the {@code expiry} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<Expiry> expiry() {
      return _expiry;
    }

    /**
     * The meta-property for the {@code pointValue} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<Double> pointValue() {
      return _pointValue;
    }

    /**
     * The meta-property for the {@code exchange} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> exchange() {
      return _exchange;
    }

    /**
     * The meta-property for the {@code barrierType} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<BarrierType> barrierType() {
      return _barrierType;
    }

    /**
     * The meta-property for the {@code barrierDirection} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<BarrierDirection> barrierDirection() {
      return _barrierDirection;
    }

    /**
     * The meta-property for the {@code monitoringType} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<MonitoringType> monitoringType() {
      return _monitoringType;
    }

    /**
     * The meta-property for the {@code samplingFrequency} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<SamplingFrequency> samplingFrequency() {
      return _samplingFrequency;
    }

    /**
     * The meta-property for the {@code barrierLevel} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<Double> barrierLevel() {
      return _barrierLevel;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 1373587791:  // optionType
          return ((EquityBarrierOptionSecurity) bean).getOptionType();
        case -891985998:  // strike
          return ((EquityBarrierOptionSecurity) bean).getStrike();
        case 575402001:  // currency
          return ((EquityBarrierOptionSecurity) bean).getCurrency();
        case -771625640:  // underlyingId
          return ((EquityBarrierOptionSecurity) bean).getUnderlyingId();
        case -466331342:  // exerciseType
          return ((EquityBarrierOptionSecurity) bean).getExerciseType();
        case -1289159373:  // expiry
          return ((EquityBarrierOptionSecurity) bean).getExpiry();
        case 1257391553:  // pointValue
          return ((EquityBarrierOptionSecurity) bean).getPointValue();
        case 1989774883:  // exchange
          return ((EquityBarrierOptionSecurity) bean).getExchange();
        case 1029043089:  // barrierType
          return ((EquityBarrierOptionSecurity) bean).getBarrierType();
        case 502579592:  // barrierDirection
          return ((EquityBarrierOptionSecurity) bean).getBarrierDirection();
        case -1483652190:  // monitoringType
          return ((EquityBarrierOptionSecurity) bean).getMonitoringType();
        case 1178782005:  // samplingFrequency
          return ((EquityBarrierOptionSecurity) bean).getSamplingFrequency();
        case 1827586573:  // barrierLevel
          return ((EquityBarrierOptionSecurity) bean).getBarrierLevel();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 1373587791:  // optionType
          ((EquityBarrierOptionSecurity) bean).setOptionType((OptionType) newValue);
          return;
        case -891985998:  // strike
          ((EquityBarrierOptionSecurity) bean).setStrike((Double) newValue);
          return;
        case 575402001:  // currency
          ((EquityBarrierOptionSecurity) bean).setCurrency((Currency) newValue);
          return;
        case -771625640:  // underlyingId
          ((EquityBarrierOptionSecurity) bean).setUnderlyingId((ExternalId) newValue);
          return;
        case -466331342:  // exerciseType
          ((EquityBarrierOptionSecurity) bean).setExerciseType((ExerciseType) newValue);
          return;
        case -1289159373:  // expiry
          ((EquityBarrierOptionSecurity) bean).setExpiry((Expiry) newValue);
          return;
        case 1257391553:  // pointValue
          ((EquityBarrierOptionSecurity) bean).setPointValue((Double) newValue);
          return;
        case 1989774883:  // exchange
          ((EquityBarrierOptionSecurity) bean).setExchange((String) newValue);
          return;
        case 1029043089:  // barrierType
          ((EquityBarrierOptionSecurity) bean).setBarrierType((BarrierType) newValue);
          return;
        case 502579592:  // barrierDirection
          ((EquityBarrierOptionSecurity) bean).setBarrierDirection((BarrierDirection) newValue);
          return;
        case -1483652190:  // monitoringType
          ((EquityBarrierOptionSecurity) bean).setMonitoringType((MonitoringType) newValue);
          return;
        case 1178782005:  // samplingFrequency
          ((EquityBarrierOptionSecurity) bean).setSamplingFrequency((SamplingFrequency) newValue);
          return;
        case 1827586573:  // barrierLevel
          ((EquityBarrierOptionSecurity) bean).setBarrierLevel((Double) newValue);
          return;
      }
      super.propertySet(bean, propertyName, newValue, quiet);
    }

    @Override
    protected void validate(Bean bean) {
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._optionType, "optionType");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._currency, "currency");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._underlyingId, "underlyingId");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._exerciseType, "exerciseType");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._expiry, "expiry");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._exchange, "exchange");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._barrierType, "barrierType");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._barrierDirection, "barrierDirection");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._monitoringType, "monitoringType");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._samplingFrequency, "samplingFrequency");
      JodaBeanUtils.notNull(((EquityBarrierOptionSecurity) bean)._barrierLevel, "barrierLevel");
      super.validate(bean);
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
package cmd

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/3Blades/cli-tools/tbs/api"
	"github.com/3Blades/cli-tools/tbs/utils"
	"github.com/3Blades/go-sdk/client/billing"
	"github.com/3Blades/go-sdk/models"
	"github.com/spf13/cobra"
	jww "github.com/spf13/jwalterweatherman"
	"github.com/spf13/viper"
	"github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/token"
)

func init() {
	cmd := billingCmd()
	cmd.AddCommand(billingListCardCmd(),
		billingDescribeCardCmd(),
		billingUpdateCardCmd(),
		billingDeleteCardCmd(),
		billingCreateCardInteractiveCmd())
	RootCmd.AddCommand(cmd)
}

func billingCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "billing",
		Short: "Handle Credit Cards",
	}
	cmd.PersistentFlags().StringP("format", "f", "json", "Output format")
	viper.BindPFlag("billing_format", cmd.PersistentFlags().Lookup("format"))
	return cmd
}

func billingListCardCmd() *cobra.Command {
	var lf utils.ListFlags
	cmd := &cobra.Command{
		Use:   "ls",
		Short: "List payment methods",
		RunE: func(cmd *cobra.Command, args []string) error {
			cli := api.Client()
			params := billing.NewBillingCardsListParams()
			params.SetNamespace(cli.Namespace)
			lf.Apply(params)
			resp, err := cli.Billing.BillingCardsList(params, cli.AuthInfo)
			if err != nil {
				return err
			}
			return api.Render("billing_format", resp.Payload)
		},
	}
	lf.Set(cmd)
	return cmd
}

func billingDescribeCardCmd() *cobra.Command {
	var cardID string
	cmd := &cobra.Command{
		Use:   "describe",
		Short: "Credit Card Details",
		RunE: func(cmd *cobra.Command, args []string) error {
			cli := api.Client()
			params := billing.NewBillingCardsReadParams()
			params.SetNamespace(cli.Namespace)
			params.SetID(cardID)
			resp, err := cli.Billing.BillingCardsRead(params, cli.AuthInfo)
			if err != nil {
				return err
			}
			return api.Render("billing_format", resp.Payload)
		},
	}
	cmd.Flags().StringVar(&cardID, "uuid", "", "Card id")
	return cmd
}

func billingUpdateCardCmd() *cobra.Command {
	var cardID string
	updateBody := &models.CardDataPutandPatch{}
	cmd := &cobra.Command{
		Use:   "update",
		Short: "Update credit card information.",
		RunE: func(cmd *cobra.Command, args []string) error {
			cli := api.Client()

			params := billing.NewBillingCardsUpdateParams()
			params.SetNamespace(cli.Namespace)
			params.SetID(cardID)
			params.SetCardData(updateBody)

			resp, err := cli.Billing.BillingCardsUpdate(params, cli.AuthInfo)
			if err != nil {
				return err
			}

			jww.FEEDBACK.Println("Card Updated.")
			return api.Render("billing_format", resp.Payload)

		},
	}
	cmd.Flags().StringVar(&cardID, "uuid", "", "Card ID")
	cmd.Flags().StringVar(&updateBody.Name, "name", "", "Cardholder name")
	cmd.Flags().StringVar(&updateBody.AddressLine1, "address_line1", "", "Address Line One")
	cmd.Flags().StringVar(&updateBody.AddressLine2, "address_line2", "", "Address Line Two")
	cmd.Flags().StringVar(&updateBody.AddressCity, "city", "", "City")
	cmd.Flags().StringVar(&updateBody.AddressState, "state", "", "State")
	cmd.Flags().StringVar(&updateBody.AddressCountry, "country", "", "Country")
	cmd.Flags().StringVar(&updateBody.AddressZip, "zip_code", "", "ZIP Code")
	return cmd
}

func billingDeleteCardCmd() *cobra.Command {
	var cardID string
	cmd := &cobra.Command{
		Use:   "rm",
		Short: "Delete a credit card.",
		RunE: func(cmd *cobra.Command, args []string) error {
			confirm, err := readStdin(fmt.Sprint("Are you sure you want to delete this card? (Y/n): "))
			if err != nil {
				return err
			}
			confirm = strings.ToLower(confirm)
			if confirm == "n" || confirm == "no" {
				jww.FEEDBACK.Println("Aborted")
				return nil
			}

			cli := api.Client()
			params := billing.NewBillingCardsDeleteParams()
			params.SetNamespace(cli.Namespace)
			params.SetID(cardID)

			_, err = cli.Billing.BillingCardsDelete(params, cli.AuthInfo)
			if err != nil {
				return err
			}
			jww.FEEDBACK.Println("Card deleted")
			return nil
		},
	}

	cmd.Flags().StringVar(&cardID, "uuid", "", "Card UUID")
	return cmd
}

func billingCreateCardInteractiveCmd() *cobra.Command {
	body := BillingCardsCreateBody{}
	cmd := &cobra.Command{
		Use:   "add",
		Short: "Add a credit card.",
		RunE: func(cmd *cobra.Command, args []string) error {
			name, err := readStdin("Cardholder Name:")
			if err != nil {
				return err
			}
			body.Name = name

			number, err := readStdin("Card Number:")
			if err != nil {
				return err
			}
			body.Number = number

			var expMonth int64

			fmt.Println("Expiry Month:")
			fmt.Scan(&expMonth)
			body.ExpMonth = expMonth

			var expYear int64

			fmt.Println("Expiry Year:")
			fmt.Scan(&expYear)
			body.ExpYear = expYear

			Cvc, err := readStdin("CVC: ")
			if err != nil {
				return err
			}
			body.Cvc = Cvc

			address1, err := readStdin("Address Line 1: ")
			if err != nil {
				return err
			}
			body.AddressLine1 = address1

			address2, err := readStdin("Address Line 2: ")
			if err != nil {
				return err
			}
			body.AddressLine2 = address2

			city, err := readStdin("City: ")
			if err != nil {
				return err
			}
			body.AddressCity = city

			state, err := readStdin("State: ")
			if err != nil {
				return err
			}
			body.AddressState = state

			zip, err := readStdin("Zip Code: ")
			if err != nil {
				return err
			}
			body.AddressZip = zip

			country, err := readStdin("Country: ")
			if err != nil {
				return err
			}
			body.AddressCountry = country

			stripe.Key = os.Getenv("STRIPE_SECRET_KEY")

			tkn, err := token.New(&stripe.TokenParams{
				Card: &stripe.CardParams{
					Number:   body.Number,
					Month:    strconv.FormatInt(body.ExpMonth, 10),
					Year:     strconv.FormatInt(body.ExpYear, 10),
					CVC:      body.Cvc,
					City:     body.AddressCity,
					Country:  body.AddressCountry,
					Address1: body.AddressLine1,
					Address2: body.AddressLine2,
					State:    body.AddressState,
					Zip:      body.AddressZip,
					Name:     body.Name,
				},
			})

			cli := api.Client()
			params := billing.NewBillingCardsCreateParams()
			params.SetNamespace(cli.Namespace)
			body := &models.CardDataPost{
				Token: tkn.ID,
			}
			params.SetCardData(body)

			resp, err := cli.Billing.BillingCardsCreate(params, cli.AuthInfo)

			jww.FEEDBACK.Println("Card added")
			return api.Render("billing_format", resp.Payload)
		},
	}

	return cmd
}

type BillingCardsCreateBody struct {

	// address city
	AddressCity string `json:"address_city,omitempty"`

	// address country
	AddressCountry string `json:"address_country,omitempty"`

	// address line1
	AddressLine1 string `json:"address_line1,omitempty"`

	// address line2
	AddressLine2 string `json:"address_line2,omitempty"`

	// address state
	AddressState string `json:"address_state,omitempty"`

	// address zip
	AddressZip string `json:"address_zip,omitempty"`

	Cvc string `json:"cvc,omitempty"`

	// exp month
	ExpMonth int64 `json:"exp_month,omitempty"`

	// exp year
	ExpYear int64 `json:"exp_year,omitempty"`

	// name
	Name string `json:"name,omitempty"`

	Number string `json:"number,omitempty"`

	// token
	Token string `json:"token,omitempty"`
}


text:
namespace {
QList<QTreeWidgetItem*> buildLimitsList(VkPhysicalDeviceLimits limits);
}

namespace Ui
{

CentralWidget::CentralWidget(QWidget* parent)
    :QWidget(parent),
     m_layersLabel(new QLabel("Instance Layers", this)), m_layersList(new QListWidget(this)),
     m_layersDescription(new QTextEdit(this)),
     m_extensionsLabel(new QLabel("Instance Extensions", this)), m_extensionsList(new QListWidget(this)),
     m_extensionsDescription(new QTextEdit(this)),
     m_physicalDevicesLabel(new QLabel("Physical Devices", this)), m_physicalDevicesList(new QListWidget(this)),
     m_physicalDeviceDescription(new QTextEdit(this)), m_physicalDeviceProperties(new QTreeWidget(this)),
     m_errorConsole(new QTextEdit(this)), m_instance(nullptr)
{
    QSizePolicy sp(QSizePolicy::Preferred, QSizePolicy::Preferred);
    sp.setVerticalStretch(2);

    m_instancePaneLayout.addWidget(m_layersLabel);
    m_layersList->setSizePolicy(sp);
    m_instancePaneLayout.addWidget(m_layersList);
    m_instancePaneLayout.addWidget(m_layersDescription);
    m_layersDescription->setEnabled(false);
    sp.setVerticalStretch(1);
    m_layersDescription->setSizePolicy(sp);
    m_instancePaneLayout.addWidget(m_extensionsLabel);
    sp.setVerticalStretch(2);
    m_extensionsList->setSizePolicy(sp);
    m_instancePaneLayout.addWidget(m_extensionsList);
    m_extensionsDescription->setEnabled(false);
    sp.setVerticalStretch(1);
    m_extensionsDescription->setSizePolicy(sp);
    m_instancePaneLayout.addWidget(m_extensionsDescription);
    m_innerLayout.addLayout(&m_instancePaneLayout);

    m_physicalDevicesPaneLayout.addWidget(m_physicalDevicesLabel);
    m_physicalDevicesPaneLayout.addWidget(m_physicalDevicesList);
    m_physicalDeviceDescription->setReadOnly(true);
    m_physicalDevicesPaneLayout.addWidget(m_physicalDeviceDescription);
    m_physicalDevicesPaneLayout.addWidget(m_physicalDeviceProperties);
    m_innerLayout.addLayout(&m_physicalDevicesPaneLayout);

    m_layout.addLayout(&m_innerLayout);

    sp.setVerticalPolicy(QSizePolicy::Fixed);
    m_errorConsole->setMinimumHeight(50);
    m_errorConsole->setSizePolicy(sp);
    m_errorConsole->setReadOnly(true);
    m_layout.addWidget(m_errorConsole);

    setLayout(&m_layout);

    connect(this, &CentralWidget::errorCreateInstance,
            this, &CentralWidget::logError);

    connect(this, &CentralWidget::newInstanceCreated,
            this, &CentralWidget::enumeratePhysicalDevices);

    connect(m_physicalDevicesList, &QListWidget::currentRowChanged,
            this, &CentralWidget::onPhysicalDeviceSelected);

    connectInstanceLayerListSignals();
    connectInstanceExtensionListSignals();
}

CentralWidget::~CentralWidget() = default;

void CentralWidget::connectInstanceLayerListSignals()
{
    connect(m_layersList, &QListWidget::currentRowChanged,
            this, &CentralWidget::onInstanceLayerSelected);
    connect(m_layersList, &QListWidget::itemChanged,
            this, &CentralWidget::onInstanceConfigurationChanged);
}

void CentralWidget::connectInstanceExtensionListSignals()
{
    connect(m_extensionsList, &QListWidget::currentRowChanged,
            this, &CentralWidget::onInstanceExtensionSelected);
    connect(m_extensionsList, &QListWidget::itemChanged,
            this, &CentralWidget::onInstanceConfigurationChanged);
}

void CentralWidget::enumerateInstanceOptions()
{
    disconnect(m_layersList, nullptr, nullptr, nullptr);
    m_layersList->clear();
    m_layersDescriptionStrings.clear();
    m_layersDescription->clear();

    auto const layer_props = GhulbusVulkan::Instance::enumerateInstanceLayerProperties();
    for(auto const& p : layer_props) {
        auto item = new QListWidgetItem(QString(p.layerName));
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
        item->setCheckState(Qt::Unchecked);
        m_layersDescriptionStrings.emplace_back(
            QString(p.description) %
            "\n\nSpec Version: " % QString::fromStdString(GhulbusVulkan::version_to_string(p.specVersion)) %
            "\nImplementation Version: " % QString::fromStdString(GhulbusVulkan::version_to_string(p.implementationVersion))
        );
        m_layersList->addItem(item);
    }
    onInstanceLayerSelected(0);
    connectInstanceLayerListSignals();

    disconnect(m_extensionsList, nullptr, nullptr, nullptr);
    m_extensionsList->clear();
    m_extensionsDescriptionStrings.clear();
    m_extensionsDescription->clear();

    auto const extension_props = GhulbusVulkan::Instance::enumerateInstanceExtensionProperties();
    for(auto const& p : extension_props) {
        auto item = new QListWidgetItem(QString(p.extensionName));
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
        item->setCheckState(Qt::Unchecked);
        m_extensionsDescriptionStrings.emplace_back(
            QString("Spec Version: ") % QString::fromStdString(GhulbusVulkan::version_to_string(p.specVersion))
        );
        m_extensionsList->addItem(item);
    }
    onInstanceExtensionSelected(0);
    connectInstanceExtensionListSignals();
}

void CentralWidget::enumeratePhysicalDevices()
{
    m_physicalDevices.clear();
    m_physicalDevicesList->clear();
    m_physicalDevicesList->setEnabled(false);
    if(!m_instance) { return; }

    m_physicalDevices = m_instance->enumeratePhysicalDevices();
    for(auto& pd : m_physicalDevices) {
        m_physicalDevicesList->addItem(QString(pd.getProperties().deviceName));
    }
    m_physicalDevicesList->setEnabled(true);
}

void CentralWidget::logError(QString msg)
{
    m_errorConsole->append(msg);
}

void CentralWidget::onInstanceLayerSelected(int index)
{
    if(index < 0 || index >= m_layersDescriptionStrings.size()) {
        m_layersDescription->clear();
    } else {
        m_layersDescription->setText(m_layersDescriptionStrings[index]);
    }
}

void CentralWidget::onInstanceExtensionSelected(int index)
{
    if(index < 0 || index >= m_extensionsDescriptionStrings.size()) {
        m_extensionsDescription->clear();
    } else {
        m_extensionsDescription->setText(m_extensionsDescriptionStrings[index]);
    }
}

void CentralWidget::onPhysicalDeviceSelected(int index)
{
    if(index < 0 || index >= m_physicalDevices.size()) {
        m_physicalDeviceDescription->clear();
        m_physicalDeviceProperties->clear();
    } else {
        auto& pd = m_physicalDevices[index];
        auto props = pd.getProperties();
        std::stringstream sstr;
        sstr << props.deviceName << " (" << props.deviceType << ")\n\n"
             << "Vendor ID: " << props.vendorID << "\n"
             << "Device ID: " << props.deviceID << "\n"
             << "Pipeline Cache UUID: " << GhulbusVulkan::uuid_to_string(props.pipelineCacheUUID) << "\n"
             << "API Version: " << GhulbusVulkan::version_to_string(props.apiVersion) << "\n"
             << "Driver Version: " << GhulbusVulkan::version_to_string(props.driverVersion);
        m_physicalDeviceDescription->setText(QString::fromStdString(sstr.str()));

        m_physicalDeviceProperties->setColumnCount(2);
        m_physicalDeviceProperties->addTopLevelItems(buildLimitsList(props.limits));
    }
}

void CentralWidget::onInstanceConfigurationChanged()
{
    m_instance.reset();

    GhulbusVulkan::Instance::Layers layers;
    std::vector<std::string> layer_storage;
    for(int i = 0; i < m_layersList->count(); ++i) {
        auto item = m_layersList->item(i);
        if(item->checkState() == Qt::Checked) {
            layer_storage.emplace_back(item->text().toStdString());
        }
    }
    for(auto const& l :layer_storage) { layers.addLayer(l.c_str()); }
    GhulbusVulkan::Instance::Extensions extensions(GhulbusVulkan::Instance::Extensions::DeactivateSurfaceExtensions{});
    std::vector<std::string> extensions_storage;
    for(int i = 0; i < m_extensionsList->count(); ++i) {
        auto item = m_extensionsList->item(i);
        if(item->checkState() == Qt::Checked) {
            extensions_storage.emplace_back(item->text().toStdString());
        }
    }
    for(auto const& e : extensions_storage) { extensions.addExtension(e.c_str()); }

    try {
        m_instance = std::make_unique<GhulbusVulkan::Instance>(
            GhulbusVulkan::Instance::createInstance(
                "gbVk Device Explorer", GhulbusVulkan::Instance::Version(1, 0, 0), layers, extensions));
    } catch(GhulbusVulkan::Exceptions::VulkanError& e) {
        auto desc = Ghulbus::getErrorInfo<GhulbusVulkan::Exception_Info::description>(e);
        auto vkres = Ghulbus::getErrorInfo<GhulbusVulkan::Exception_Info::vulkan_error_code>(e);
        emit errorCreateInstance(QString::fromStdString(*desc) % " - " % GhulbusVulkan::to_string(*vkres));
        return;
    }
    emit newInstanceCreated();
}
}

namespace {
QList<QTreeWidgetItem*> buildLimitsList(VkPhysicalDeviceLimits limits)
{
    QList<QTreeWidgetItem*> ret;
    auto add_item = [&ret](char const* label, std::string const& value) {
        QStringList qsl;
        qsl.push_back(QString::fromUtf8(label));
        qsl.push_back(QString::fromStdString(value));
        ret.push_back(new QTreeWidgetItem(qsl));
    };
#define ADD_ITEM(field) add_item(#field, std::to_string(limits.field))
#define ADD_ITEM_SIZE(field) add_item(#field, GhulbusVulkan::memory_size_to_string(limits.field))
    ADD_ITEM(maxImageDimension1D);
    ADD_ITEM(maxImageDimension2D);
    ADD_ITEM(maxImageDimension3D);
    ADD_ITEM(maxImageDimensionCube);
    ADD_ITEM(maxImageArrayLayers);
    ADD_ITEM(maxTexelBufferElements);
    ADD_ITEM(maxUniformBufferRange);
    ADD_ITEM(maxStorageBufferRange);
    ADD_ITEM(maxPushConstantsSize);
    ADD_ITEM(maxMemoryAllocationCount);
    ADD_ITEM(maxSamplerAllocationCount);
    ADD_ITEM_SIZE(bufferImageGranularity);
    ADD_ITEM_SIZE(sparseAddressSpaceSize);
    ADD_ITEM(maxBoundDescriptorSets);
    ADD_ITEM(maxPerStageDescriptorSamplers);
    ADD_ITEM(maxPerStageDescriptorUniformBuffers);
    ADD_ITEM(maxPerStageDescriptorStorageBuffers);
    ADD_ITEM(maxPerStageDescriptorSampledImages);
    ADD_ITEM(maxPerStageDescriptorStorageImages);
    ADD_ITEM(maxPerStageDescriptorInputAttachments);
    ADD_ITEM(maxPerStageResources);
    ADD_ITEM(maxDescriptorSetSamplers);
    ADD_ITEM(maxDescriptorSetUniformBuffers);
    ADD_ITEM(maxDescriptorSetUniformBuffersDynamic);
    ADD_ITEM(maxDescriptorSetStorageBuffers);
    ADD_ITEM(maxDescriptorSetStorageBuffersDynamic);
    ADD_ITEM(maxDescriptorSetSampledImages);
    ADD_ITEM(maxDescriptorSetStorageImages);
    ADD_ITEM(maxDescriptorSetInputAttachments);
    ADD_ITEM(maxVertexInputAttributes);
    ADD_ITEM(maxVertexInputBindings);
    ADD_ITEM(maxVertexInputAttributeOffset);
    ADD_ITEM(maxVertexInputBindingStride);
    ADD_ITEM(maxVertexOutputComponents);
    ADD_ITEM(maxTessellationGenerationLevel);
    ADD_ITEM(maxTessellationPatchSize);
    ADD_ITEM(maxTessellationControlPerVertexInputComponents);
    ADD_ITEM(maxTessellationControlPerVertexOutputComponents);
    ADD_ITEM(maxTessellationControlPerPatchOutputComponents);
    ADD_ITEM(maxTessellationControlTotalOutputComponents);
    ADD_ITEM(maxTessellationEvaluationInputComponents);
    ADD_ITEM(maxTessellationEvaluationOutputComponents);
    ADD_ITEM(maxGeometryShaderInvocations);
    ADD_ITEM(maxGeometryInputComponents);
    ADD_ITEM(maxGeometryOutputComponents);
    ADD_ITEM(maxGeometryOutputVertices);
    ADD_ITEM(maxGeometryTotalOutputComponents);
    ADD_ITEM(maxFragmentInputComponents);
    ADD_ITEM(maxFragmentOutputAttachments);
    ADD_ITEM(maxFragmentDualSrcAttachments);
    ADD_ITEM(maxFragmentCombinedOutputResources);
    ADD_ITEM(maxComputeSharedMemorySize);
    // uint32_t              maxComputeWorkGroupCount[3];
    //uint32_t              maxComputeWorkGroupInvocations;
    //uint32_t              maxComputeWorkGroupSize[3];
    ADD_ITEM(subPixelPrecisionBits);
    ADD_ITEM(subTexelPrecisionBits);
    ADD_ITEM(mipmapPrecisionBits);
    ADD_ITEM(maxDrawIndexedIndexValue);
    ADD_ITEM(maxDrawIndirectCount);
    ADD_ITEM(maxSamplerLodBias);
    ADD_ITEM(maxSamplerAnisotropy);
    ADD_ITEM(maxViewports);
    //uint32_t              maxViewportDimensions[2];
    //float                 viewportBoundsRange[2];
    ADD_ITEM(viewportSubPixelBits);
    ADD_ITEM(minMemoryMapAlignment);
    ADD_ITEM_SIZE(minTexelBufferOffsetAlignment);
    ADD_ITEM_SIZE(minUniformBufferOffsetAlignment);
    ADD_ITEM_SIZE(minStorageBufferOffsetAlignment);
    ADD_ITEM(minTexelOffset);
    ADD_ITEM(maxTexelOffset);
    ADD_ITEM(minTexelGatherOffset);
    ADD_ITEM(maxTexelGatherOffset);
    ADD_ITEM(minInterpolationOffset);
    ADD_ITEM(maxInterpolationOffset);
    ADD_ITEM(subPixelInterpolationOffsetBits);
    ADD_ITEM(maxFramebufferWidth);
    ADD_ITEM(maxFramebufferHeight);
    ADD_ITEM(maxFramebufferLayers);
    //VkSampleCountFlags    framebufferColorSampleCounts;
    //VkSampleCountFlags    framebufferDepthSampleCounts;
    //VkSampleCountFlags    framebufferStencilSampleCounts;
    //VkSampleCountFlags    framebufferNoAttachmentsSampleCounts;
    ADD_ITEM(maxColorAttachments);
    //VkSampleCountFlags    sampledImageColorSampleCounts;
    //VkSampleCountFlags    sampledImageIntegerSampleCounts;
    //VkSampleCountFlags    sampledImageDepthSampleCounts;
    //VkSampleCountFlags    sampledImageStencilSampleCounts;
    //VkSampleCountFlags    storageImageSampleCounts;
    ADD_ITEM(maxSampleMaskWords);
    ADD_ITEM(timestampComputeAndGraphics);
    ADD_ITEM(timestampPeriod);
    ADD_ITEM(maxClipDistances);
    ADD_ITEM(maxCullDistances);
    ADD_ITEM(maxCombinedClipAndCullDistances);
    ADD_ITEM(discreteQueuePriorities);
    //float                 pointSizeRange[2];
    //float                 lineWidthRange[2];
    ADD_ITEM(pointSizeGranularity);
    ADD_ITEM(lineWidthGranularity);
    ADD_ITEM(strictLines);
    ADD_ITEM(standardSampleLocations);
    ADD_ITEM_SIZE(optimalBufferCopyOffsetAlignment);
    ADD_ITEM_SIZE(optimalBufferCopyRowPitchAlignment);
    ADD_ITEM_SIZE(nonCoherentAtomSize);
#undef ADD_ITEM
#undef ADD_ITEM_SIZE
    return ret;
}
}


text:
package org.apache.wicket.extensions.markup.html.repeater.tree.table;

import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.tree.ITreeProvider;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;

/**
 * An adapter of a {@link ITreeProvider} to a {@link IDataProvider}.
 *
 * @author svenmeier
 * @param <T>
 *            node type
 */
public abstract class TreeDataProvider<T> implements ITreeDataProvider<T>
{
	private static final long serialVersionUID = 1L;

	private final ITreeProvider<T> provider;

	private transient Branch<T> currentBranch;

	private transient Branch<T> previousBranch;

	private int size = -1;

	/**
	 * Construct.
	 *
	 * @param provider
	 *            the provider to adapt
	 */
	protected TreeDataProvider(ITreeProvider<T> provider)
	{
		this.provider = provider;
	}

	@Override
	public long size()
	{
		if (size == -1)
		{
			size = 0;

			Iterator<? extends T> iterator = iterator(0, Integer.MAX_VALUE);
			while (iterator.hasNext())
			{
				iterator.next();

				size++;
			}
		}
		return size;
	}

	@Override
	public Iterator<? extends T> iterator(long first, long count)
	{
		currentBranch = new Branch<>(null, provider.getRoots());

		Iterator<T> iterator = new Iterator<T>()
		{
			@Override
			public boolean hasNext()
			{
				while (currentBranch != null)
				{
					if (currentBranch.hasNext())
					{
						return true;
					}
					currentBranch = currentBranch.parent;
				}

				return false;
			}

			@Override
			public T next()
			{
				if (!hasNext())
				{
					throw new IllegalStateException();
				}

				T next = currentBranch.next();

				previousBranch = currentBranch;

				if (iterateChildren(next))
				{
					currentBranch = new Branch<>(previousBranch, provider.getChildren(next));
				}

				return next;
			}

			@Override
			public void remove()
			{
				throw new UnsupportedOperationException();
			}
		};

		for (int i = 0; i < first; i++)
		{
			iterator.next();
		}

		return iterator;
	}

	/**
	 * Hook method to decide whether the given node's children should be iterated.
	 *
	 * @param node
	 *            node
	 *
	 * @return {@code true} if the node's children should be iterated
	 */
	protected abstract boolean iterateChildren(T node);

	@Override
	public NodeModel<T> model(T object)
	{
		return previousBranch.wrapModel(provider.model(object));
	}

	@Override
	public void detach()
	{
		currentBranch = null;
		previousBranch = null;
		size = -1;
	}

	private static class Branch<T> implements Iterator<T>
	{
		private Branch<T> parent;

		private Iterator<? extends T> children;

		Branch(Branch<T> parent, Iterator<? extends T> children)
		{
			this.parent = parent;
			this.children = children;
		}

		NodeModel<T> wrapModel(IModel<T> model)
		{
			boolean[] branches = new boolean[getDepth()];

			Branch<T> branch = this;
			for (int c = branches.length - 1; c >= 0; c--)
			{
				branches[c] = branch.hasNext();

				branch = branch.parent;
			}

			return new NodeModel<>(model, branches);
		}

		int getDepth()
		{
			if (parent == null)
			{
				return 1;
			}
			else
			{
				return parent.getDepth() + 1;
			}
		}

		@Override
		public boolean hasNext()
		{
			return children.hasNext();
		}

		@Override
		public T next()
		{
			if (!hasNext())
			{
				throw new IllegalStateException();
			}

			return children.next();
		}

		@Override
		public void remove()
		{
			throw new UnsupportedOperationException();
		}
	}
}


text:
<?php

namespace Illuminate\Routing;

use Illuminate\Support\Str;

class ResourceRegistrar
{
    /**
     * The router instance.
     *
     * @var \Illuminate\Routing\Router
     */
    protected $router;

    /**
     * The default actions for a resourceful controller.
     *
     * @var array
     */
    protected $resourceDefaults = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy'];

    /**
     * The parameters set for this resource instance.
     *
     * @var array|string
     */
    protected $parameters;

    /**
     * The global parameter mapping.
     *
     * @var array
     */
    protected static $parameterMap = [];

    /**
     * Singular global parameters.
     *
     * @var bool
     */
    protected static $singularParameters = true;

    /**
     * The verbs used in the resource URIs.
     *
     * @var array
     */
    protected static $verbs = [
        'create' => 'create',
        'edit' => 'edit',
    ];

    /**
     * Create a new resource registrar instance.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    /**
     * Route a resource to a controller.
     *
     * @param  string  $name
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\RouteCollection
     */
    public function register($name, $controller, array $options = [])
    {
        if (isset($options['parameters']) && ! isset($this->parameters)) {
            $this->parameters = $options['parameters'];
        }

        // If the resource name contains a slash, we will assume the developer wishes to
        // register these resource routes with a prefix so we will set that up out of
        // the box so they don't have to mess with it. Otherwise, we will continue.
        if (Str::contains($name, '/')) {
            $this->prefixedResource($name, $controller, $options);

            return;
        }

        // We need to extract the base resource from the resource name. Nested resources
        // are supported in the framework, but we need to know what name to use for a
        // place-holder on the route parameters, which should be the base resources.
        $base = $this->getResourceWildcard(last(explode('.', $name)));

        $defaults = $this->resourceDefaults;

        $collection = new RouteCollection;

        foreach ($this->getResourceMethods($defaults, $options) as $m) {
            $collection->add($this->{'addResource'.ucfirst($m)}(
                $name, $base, $controller, $options
            ));
        }

        return $collection;
    }

    /**
     * Build a set of prefixed resource routes.
     *
     * @param  string  $name
     * @param  string  $controller
     * @param  array   $options
     * @return void
     */
    protected function prefixedResource($name, $controller, array $options)
    {
        [$name, $prefix] = $this->getResourcePrefix($name);

        // We need to extract the base resource from the resource name. Nested resources
        // are supported in the framework, but we need to know what name to use for a
        // place-holder on the route parameters, which should be the base resources.
        $callback = function ($me) use ($name, $controller, $options) {
            $me->resource($name, $controller, $options);
        };

        return $this->router->group(compact('prefix'), $callback);
    }

    /**
     * Extract the resource and prefix from a resource name.
     *
     * @param  string  $name
     * @return array
     */
    protected function getResourcePrefix($name)
    {
        $segments = explode('/', $name);

        // To get the prefix, we will take all of the name segments and implode them on
        // a slash. This will generate a proper URI prefix for us. Then we take this
        // last segment, which will be considered the final resources name we use.
        $prefix = implode('/', array_slice($segments, 0, -1));

        return [end($segments), $prefix];
    }

    /**
     * Get the applicable resource methods.
     *
     * @param  array  $defaults
     * @param  array  $options
     * @return array
     */
    protected function getResourceMethods($defaults, $options)
    {
        if (isset($options['only'])) {
            return array_intersect($defaults, (array) $options['only']);
        } elseif (isset($options['except'])) {
            return array_diff($defaults, (array) $options['except']);
        }

        return $defaults;
    }

    /**
     * Add the index method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceIndex($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name);

        $action = $this->getResourceAction($name, $controller, 'index', $options);

        return $this->router->get($uri, $action);
    }

    /**
     * Add the create method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceCreate($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/'.static::$verbs['create'];

        $action = $this->getResourceAction($name, $controller, 'create', $options);

        return $this->router->get($uri, $action);
    }

    /**
     * Add the store method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceStore($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name);

        $action = $this->getResourceAction($name, $controller, 'store', $options);

        return $this->router->post($uri, $action);
    }

    /**
     * Add the show method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceShow($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/{'.$base.'}';

        $action = $this->getResourceAction($name, $controller, 'show', $options);

        return $this->router->get($uri, $action);
    }

    /**
     * Add the edit method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceEdit($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/{'.$base.'}/'.static::$verbs['edit'];

        $action = $this->getResourceAction($name, $controller, 'edit', $options);

        return $this->router->get($uri, $action);
    }

    /**
     * Add the update method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceUpdate($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/{'.$base.'}';

        $action = $this->getResourceAction($name, $controller, 'update', $options);

        return $this->router->match(['PUT', 'PATCH'], $uri, $action);
    }

    /**
     * Add the destroy method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceDestroy($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/{'.$base.'}';

        $action = $this->getResourceAction($name, $controller, 'destroy', $options);

        return $this->router->delete($uri, $action);
    }

    /**
     * Get the base resource URI for a given resource.
     *
     * @param  string  $resource
     * @return string
     */
    public function getResourceUri($resource)
    {
        if (! Str::contains($resource, '.')) {
            return $resource;
        }

        // Once we have built the base URI, we'll remove the parameter holder for this
        // base resource name so that the individual route adders can suffix these
        // paths however they need to, as some do not have any parameters at all.
        $segments = explode('.', $resource);

        $uri = $this->getNestedResourceUri($segments);

        return str_replace('/{'.$this->getResourceWildcard(end($segments)).'}', '', $uri);
    }

    /**
     * Get the URI for a nested resource segment array.
     *
     * @param  array   $segments
     * @return string
     */
    protected function getNestedResourceUri(array $segments)
    {
        // We will spin through the segments and create a place-holder for each of the
        // resource segments, as well as the resource itself. Then we should get an
        // entire string for the resource URI that contains all nested resources.
        return implode('/', array_map(function ($s) {
            return $s.'/{'.$this->getResourceWildcard($s).'}';
        }, $segments));
    }

    /**
     * Format a resource parameter for usage.
     *
     * @param  string  $value
     * @return string
     */
    public function getResourceWildcard($value)
    {
        if (isset($this->parameters[$value])) {
            $value = $this->parameters[$value];
        } elseif (isset(static::$parameterMap[$value])) {
            $value = static::$parameterMap[$value];
        } elseif ($this->parameters === 'singular' || static::$singularParameters) {
            $value = Str::singular($value);
        }

        return str_replace('-', '_', $value);
    }

    /**
     * Get the action array for a resource route.
     *
     * @param  string  $resource
     * @param  string  $controller
     * @param  string  $method
     * @param  array   $options
     * @return array
     */
    protected function getResourceAction($resource, $controller, $method, $options)
    {
        $name = $this->getResourceRouteName($resource, $method, $options);

        $action = ['as' => $name, 'uses' => $controller.'@'.$method];

        if (isset($options['middleware'])) {
            $action['middleware'] = $options['middleware'];
        }

        return $action;
    }

    /**
     * Get the name for a given resource.
     *
     * @param  string  $resource
     * @param  string  $method
     * @param  array   $options
     * @return string
     */
    protected function getResourceRouteName($resource, $method, $options)
    {
        $name = $resource;

        // If the names array has been provided to us we will check for an entry in the
        // array first. We will also check for the specific method within this array
        // so the names may be specified on a more "granular" level using methods.
        if (isset($options['names'])) {
            if (is_string($options['names'])) {
                $name = $options['names'];
            } elseif (isset($options['names'][$method])) {
                return $options['names'][$method];
            }
        }

        // If a global prefix has been assigned to all names for this resource, we will
        // grab that so we can prepend it onto the name when we create this name for
        // the resource action. Otherwise we'll just use an empty string for here.
        $prefix = isset($options['as']) ? $options['as'].'.' : '';

        return trim(sprintf('%s%s.%s', $prefix, $name, $method), '.');
    }

    /**
     * Set or unset the unmapped global parameters to singular.
     *
     * @param  bool  $singular
     * @return void
     */
    public static function singularParameters($singular = true)
    {
        static::$singularParameters = (bool) $singular;
    }

    /**
     * Get the global parameter map.
     *
     * @return array
     */
    public static function getParameters()
    {
        return static::$parameterMap;
    }

    /**
     * Set the global parameter mapping.
     *
     * @param  array $parameters
     * @return void
     */
    public static function setParameters(array $parameters = [])
    {
        static::$parameterMap = $parameters;
    }

    /**
     * Get or set the action verbs used in the resource URIs.
     *
     * @param  array  $verbs
     * @return array
     */
    public static function verbs(array $verbs = [])
    {
        if (empty($verbs)) {
            return static::$verbs;
        } else {
            static::$verbs = array_merge(static::$verbs, $verbs);
        }
    }
}


text:
using System;
using FluentAssertions;
using Paramore.Brighter.DynamoDB.Tests.TestDoubles;
using Paramore.Brighter.Inbox.DynamoDB;
using Xunit;

namespace Paramore.Brighter.DynamoDB.Tests.Inbox
{
    [Trait("Category", "DynamoDB")]
    public class DynamoDbCommandExistsTests : DynamoDBInboxBaseTest
    {
        private readonly MyCommand _command;

        private readonly DynamoDbInbox _dynamoDbInbox;
        private readonly Guid _guid = Guid.NewGuid();
        private string _contextKey;

        public DynamoDbCommandExistsTests()
        {
            _command = new MyCommand { Id = _guid, Value = "Test Earliest"};
            _contextKey = "test-context-key";

            _dynamoDbInbox = new DynamoDbInbox(Client);

            _dynamoDbInbox.Add(_command, _contextKey);
        }

        [Fact]
        public void When_checking_a_command_exist()
        {
            var commandExists = _dynamoDbInbox.Exists<MyCommand>(_command.Id, _contextKey);

            commandExists.Should().BeTrue("because the command exists.", commandExists);
        }

        [Fact]
        public void When_checking_a_command_exist_different_context_key()
        {
            var commandExists = _dynamoDbInbox.Exists<MyCommand>(_command.Id, "some-other-context-key");

            commandExists.Should().BeFalse("because the command exists for a different context key.", commandExists);
        }

        [Fact]
        public void When_checking_a_command_does_not_exist()
        {
            var commandExists = _dynamoDbInbox.Exists<MyCommand>(Guid.Empty, _contextKey);

            commandExists.Should().BeFalse("because the command doesn't exists.", commandExists);
        }
    }
}


text:
class Cms::ImportController < ApplicationController
  include Cms::BaseFilter
  include Cms::CrudFilter

  model Cms::ImportJobFile

  navi_view "cms/main/navi"
  menu_view nil

  private

  def fix_params
    { cur_site: @cur_site, cur_user: @cur_user }
  end

  def set_task
    @task = Cms::Task.find_or_create_by name: task_name, site_id: @cur_site.id
  end

  def task_name
    "cms:import_files"
  end

  public

  def import
    raise "403" unless Cms::Node.allowed?(:import, @cur_user, site: @cur_site, node: @cur_node, owned: true)

    set_task

    if request.get?
      respond_to do |format|
        format.html { render }
        format.json { render file: "ss/tasks/index", content_type: json_content_type, locals: { item: @task } }
      end
      return
    end

    @item = @model.new get_params
    render_create @item.save_with_import, location: { action: :import },
      render: { file: :import }, notice: t("ss.notice.started_import")
  end

  def download_logs
    raise "403" unless Cms::Node.allowed?(:import, @cur_user, site: @cur_site, node: @cur_node, owned: true)

    set_task

    send_file @task.log_file_path, type: 'text/plain', filename: "#{@task.id}.log",
              disposition: :attachment, x_sendfile: true
  end
end


text:
                    <input id='RP_hiddenDesc' type='hidden'>
                    <textarea id='RP_description' style='width:370px;' rows=3></textarea>

          <button class="pentaho-button" id="RP_descBtnSave">@{btnLabelSave}</button>

          <button class="pentaho-button" id="RP_descBtnCancel">@{btnLabelCancel}</button>

                @{dlgReportPropsLocation}:

        @{dlgReportPropsCreated}:

        @{dlgReportPropsModified}:

        @{dlgReportPropsModifiedBy}:

        @{dlgReportPropsCube}:

        Based on Data as of:


text:
package com.impetus.kundera.index;

import java.util.Map;

import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.metadata.model.MetamodelImpl;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;
import com.impetus.kundera.persistence.PersistenceDelegator;
import com.impetus.kundera.query.KunderaQuery;

/**
 * Indexer interface. Any custom implementation for this interface can be
 * plugged-in by configuring kundera.indexer.class property in persistence.xml.
 * Once this is enabled in persistence provider, Kundera will automatically
 * delegate index related requests to configure indexer interface implementation
 * but will keep functioning for any database specific requests. For example,
 * developer may rely upon custom index implementation for inverted indexes(e.g. @Id
 * attributes) but entity data population will be handled by Kundera.
 *
 * @author vivek.mishra
 *
 */
public interface Indexer
{
    /**
     * Index a document for given entity class and collection of values.
     *
     * @param entityClazz
     *            entity class
     *
     * @param values
     *            map of values containing field name as key and it's value.
     */
    void index(final Class entityClazz, EntityMetadata entityMetadata, Map<String, Object> values,
            final Object parentId, final Class parentClazz);

    /**
     * Executes lucene query and returns inverted indices as output. TODO:
     * Indexer interface shouldn't make any assumption about its implementation,
     * this method signature accepts lucene query, and hence should go away
     *
     * @param queryString
     *            lucene query.
     * @param start
     *            start counter
     * @param end
     *            end counter
     * @return collection containing stored index value.
     */
    @Deprecated
    Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int count);

    /**
     * Searches into a secondary index
     *
     * @return
     */
    Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata, Class<?> childClass,
            EntityMetadata childMetadata, Object entityId, int start, int count);

    Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,
            PersistenceDelegator persistenceDelegator, EntityMetadata m, int maxResults);

    /**
     * Deletes index for given entity class.
     *
     * @param entityClazz
     *            entity class
     *
     * @param entity
     *            Entity object
     */
    void unIndex(final Class entityClazz, final Object entity, EntityMetadata entityMetadata, MetamodelImpl metamodel);

    /**
     * Close indexer instance.
     */
    void close();

}


text:
package example.com.pagetransformerdemo.transformers;

import android.graphics.Color;
import android.view.View;

import example.com.pagetransformerdemo.MainActivity;

public class ColorTransformer extends BasePageTransformer {

	private static int blendColors(int color1, int color2, float ratio) {
		final float inverseRation = 1f - ratio;
		float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
		float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
		float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
		return Color.rgb((int) r, (int) g, (int) b);
	}

	@SuppressWarnings("UnnecessaryLocalVariable")
	@Override
	public void transformPage(final View page, final int pageIndex, final float position) {

		if (inRange(position)) {
			if (isRightPage(position)) {

				final int leftIndex = pageIndex - 1;
				final int rightIndex = pageIndex;

				final int leftColor = MainActivity.Content.values()[leftIndex].getColor();
				final int rightColor = MainActivity.Content.values()[rightIndex].getColor();

				final int composedColor = blendColors(leftColor, rightColor, position);
				page.setBackgroundColor(composedColor);
			} else if (isLeftPage(position)) {

				final int leftIndex = pageIndex;
				final int rightIndex = leftIndex + 1;

				final int leftColor = MainActivity.Content.values()[leftIndex].getColor();
				final int rightColor = MainActivity.Content.values()[rightIndex].getColor();

				final int composedColor = blendColors(leftColor, rightColor, 1 - Math.abs(position));
				page.setBackgroundColor(composedColor);
			} else {
				page.setBackgroundColor(MainActivity.Content.values()[pageIndex].getColor());
			}
		} else {
			page.setBackgroundColor(MainActivity.Content.values()[pageIndex].getColor());
		}
	}
}


text:
import java.io.InputStream;
import java.util.Iterator;

import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.RDFS;

public class test {
	static String base = "http://raypan.me/smarthome";

	public static void main(String[] args) {
		OntModel ontModel = ModelFactory
				.createOntologyModel(OntModelSpec.OWL_MEM);
		ontModel.read("home_latest.owl");
		// ontModel.write(System.out);
		ExtendedIterator classes = ontModel.listClasses();
		while (classes.hasNext()) {
			OntClass thisClass = (OntClass) classes.next();
			if (thisClass.toString().equals(
					"http://raypan.me/smarthome#Measurement")) {
				System.out
						.println("Looking for class: " + thisClass.toString());
				System.out.println("Found!!");
				System.out.println("Here are the subclasses of this class");
				ExtendedIterator sub = thisClass.listSubClasses();
				while (sub.hasNext()) {
					OntClass tempClass = (OntClass) sub.next();
					System.out.println(tempClass.toString());
				}

				ExtendedIterator temp = ontModel.listIndividuals();
				while (temp.hasNext()) {
					System.out.println("Individual Found");
					Individual h = (Individual) temp.next();
					System.out.println(h.toString());
				}
			}
		}
		// ontModel.write(System.out);\

		// String NS = "urn:x-hp-jena:eg/";
		// Model rdfsExample = ModelFactory.createDefaultModel();
		// Property p = rdfsExample.createProperty(NS, "p");
		// Property q = rdfsExample.createProperty(NS, "q");
		// rdfsExample.add(p, RDFS.subPropertyOf, q);
		// rdfsExample.createResource(NS + "a").addProperty(p, "foo");
		// InfModel inf = ModelFactory.createRDFSModel(rdfsExample);
		// Resource a = inf.getResource(NS+"a");
		// System.out.println("Statement: " + a.getProperty(q));
		// rdfsExample.write(System.out);

		InfModel inf = ModelFactory.createRDFSModel(ontModel);
		Resource a = inf.getResource("http://raypan.me/smarthome#A_Kitchen");
		ExtendedIterator temp1 = a.listProperties();
		while (temp1.hasNext()) {
			System.out.println("Property:");

			System.out.println(temp1.next().toString());
		}

	}
}